RowRange.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Cell;
  3. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  4. class RowRange implements AddressRange
  5. {
  6. /**
  7. * @var ?Worksheet
  8. */
  9. protected $worksheet;
  10. /**
  11. * @var int
  12. */
  13. protected $from;
  14. /**
  15. * @var int
  16. */
  17. protected $to;
  18. public function __construct(int $from, ?int $to = null, ?Worksheet $worksheet = null)
  19. {
  20. $this->validateFromTo($from, $to ?? $from);
  21. $this->worksheet = $worksheet;
  22. }
  23. public static function fromArray(array $array, ?Worksheet $worksheet = null): self
  24. {
  25. [$from, $to] = $array;
  26. return new self($from, $to, $worksheet);
  27. }
  28. private function validateFromTo(int $from, int $to): void
  29. {
  30. // Identify actual top and bottom values (in case we've been given bottom and top)
  31. $this->from = min($from, $to);
  32. $this->to = max($from, $to);
  33. }
  34. public function from(): int
  35. {
  36. return $this->from;
  37. }
  38. public function to(): int
  39. {
  40. return $this->to;
  41. }
  42. public function rowCount(): int
  43. {
  44. return $this->to - $this->from + 1;
  45. }
  46. public function shiftRight(int $offset = 1): self
  47. {
  48. $newFrom = $this->from + $offset;
  49. $newFrom = ($newFrom < 1) ? 1 : $newFrom;
  50. $newTo = $this->to + $offset;
  51. $newTo = ($newTo < 1) ? 1 : $newTo;
  52. return new self($newFrom, $newTo, $this->worksheet);
  53. }
  54. public function shiftLeft(int $offset = 1): self
  55. {
  56. return $this->shiftRight(0 - $offset);
  57. }
  58. public function toCellRange(): CellRange
  59. {
  60. return new CellRange(
  61. CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString('A'), $this->from, $this->worksheet),
  62. CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString(AddressRange::MAX_COLUMN), $this->to)
  63. );
  64. }
  65. public function __toString(): string
  66. {
  67. if ($this->worksheet !== null) {
  68. $title = str_replace("'", "''", $this->worksheet->getTitle());
  69. return "'{$title}'!{$this->from}:{$this->to}";
  70. }
  71. return "{$this->from}:{$this->to}";
  72. }
  73. }