FlexRelationshipsTrait.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php declare(strict_types=1);
  2. namespace Grav\Framework\Flex\Traits;
  3. use Grav\Framework\Contracts\Relationships\RelationshipInterface;
  4. use Grav\Framework\Contracts\Relationships\RelationshipsInterface;
  5. use Grav\Framework\Flex\FlexIdentifier;
  6. use Grav\Framework\Relationships\Relationships;
  7. /**
  8. * Trait FlexRelationshipsTrait
  9. */
  10. trait FlexRelationshipsTrait
  11. {
  12. /** @var RelationshipsInterface|null */
  13. private $_relationships = null;
  14. /**
  15. * @return Relationships
  16. */
  17. public function getRelationships(): Relationships
  18. {
  19. if (!isset($this->_relationships)) {
  20. $blueprint = $this->getBlueprint();
  21. $options = $blueprint->get('config/relationships', []);
  22. $parent = FlexIdentifier::createFromObject($this);
  23. $this->_relationships = new Relationships($parent, $options);
  24. }
  25. return $this->_relationships;
  26. }
  27. /**
  28. * @param string $name
  29. * @return RelationshipInterface|null
  30. */
  31. public function getRelationship(string $name): ?RelationshipInterface
  32. {
  33. return $this->getRelationships()[$name];
  34. }
  35. protected function resetRelationships(): void
  36. {
  37. $this->_relationships = null;
  38. }
  39. /**
  40. * @param iterable $collection
  41. * @return array
  42. */
  43. protected function buildFlexIdentifierList(iterable $collection): array
  44. {
  45. $list = [];
  46. foreach ($collection as $object) {
  47. $list[] = FlexIdentifier::createFromObject($object);
  48. }
  49. return $list;
  50. }
  51. }