CodeUnitCollection.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/code-unit.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\CodeUnit;
  11. use function array_merge;
  12. use function count;
  13. use Countable;
  14. use IteratorAggregate;
  15. /**
  16. * @template-implements IteratorAggregate<int, CodeUnit>
  17. *
  18. * @psalm-immutable
  19. */
  20. final class CodeUnitCollection implements Countable, IteratorAggregate
  21. {
  22. /**
  23. * @psalm-var list<CodeUnit>
  24. */
  25. private readonly array $codeUnits;
  26. public static function fromList(CodeUnit ...$codeUnits): self
  27. {
  28. return new self($codeUnits);
  29. }
  30. /**
  31. * @psalm-param list<CodeUnit> $codeUnits
  32. */
  33. private function __construct(array $codeUnits)
  34. {
  35. $this->codeUnits = $codeUnits;
  36. }
  37. /**
  38. * @psalm-return list<CodeUnit>
  39. */
  40. public function asArray(): array
  41. {
  42. return $this->codeUnits;
  43. }
  44. public function getIterator(): CodeUnitCollectionIterator
  45. {
  46. return new CodeUnitCollectionIterator($this);
  47. }
  48. public function count(): int
  49. {
  50. return count($this->codeUnits);
  51. }
  52. public function isEmpty(): bool
  53. {
  54. return empty($this->codeUnits);
  55. }
  56. public function mergeWith(self $other): self
  57. {
  58. return new self(
  59. array_merge(
  60. $this->asArray(),
  61. $other->asArray()
  62. )
  63. );
  64. }
  65. }