FlexIdentifier.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php declare(strict_types=1);
  2. namespace Grav\Framework\Flex;
  3. use Grav\Common\Grav;
  4. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  5. use Grav\Framework\Object\Identifiers\Identifier;
  6. use RuntimeException;
  7. /**
  8. * Interface IdentifierInterface
  9. *
  10. * @template T of FlexObjectInterface
  11. * @extends Identifier<T>
  12. */
  13. class FlexIdentifier extends Identifier
  14. {
  15. /** @var string */
  16. private $keyField;
  17. /** @var FlexObjectInterface|null */
  18. private $object = null;
  19. /**
  20. * @param FlexObjectInterface $object
  21. * @return FlexIdentifier<T>
  22. */
  23. public static function createFromObject(FlexObjectInterface $object): FlexIdentifier
  24. {
  25. $instance = new static($object->getKey(), $object->getFlexType(), 'key');
  26. $instance->setObject($object);
  27. return $instance;
  28. }
  29. /**
  30. * IdentifierInterface constructor.
  31. * @param string $id
  32. * @param string $type
  33. * @param string $keyField
  34. */
  35. public function __construct(string $id, string $type, string $keyField = 'key')
  36. {
  37. parent::__construct($id, $type);
  38. $this->keyField = $keyField;
  39. }
  40. /**
  41. * @return T
  42. */
  43. public function getObject(): ?FlexObjectInterface
  44. {
  45. if (!isset($this->object)) {
  46. /** @var Flex $flex */
  47. $flex = Grav::instance()['flex'];
  48. $this->object = $flex->getObject($this->getId(), $this->getType(), $this->keyField);
  49. }
  50. return $this->object;
  51. }
  52. /**
  53. * @param T $object
  54. */
  55. public function setObject(FlexObjectInterface $object): void
  56. {
  57. $type = $this->getType();
  58. if ($type !== $object->getFlexType()) {
  59. throw new RuntimeException(sprintf('Object has to be type %s, %s given', $type, $object->getFlexType()));
  60. }
  61. $this->object = $object;
  62. }
  63. }