<?php
 namespace Eluceo\iCal\Presentation; use Eluceo\iCal\Presentation\Component\Property; use Generator; use IteratorAggregate; use Traversable; class Component implements IteratorAggregate { private string $componentName; private array $properties = []; private iterable $components = []; public function __construct(string $componentName, array $properties = [], iterable $components = []) { $this->componentName = $componentName; $this->properties = $properties; $this->components = $components; } public function withProperty(Property $property): self { $new = clone $this; $new->properties[] = $property; return $new; } public function __toString(): string { return implode( '', iterator_to_array($this->getContentLines(), false) ); } public function getIterator(): Traversable { return $this->getContentLines(); } protected function getContentLines(): Generator { yield new ContentLine('BEGIN:' . $this->componentName); yield from $this->getContentLinesGenerator(); yield new ContentLine('END:' . $this->componentName); } protected function getContentLinesGenerator(): Generator { foreach ($this->properties as $property) { yield new ContentLine((string) $property); } foreach ($this->components as $component) { yield from $component->getContentLines(); } } } 