vendor/ibexa/seo/src/bundle/EventSubscriber/Migrations/FieldValueHashMapperSubscriber.php line 60

Open in your IDE?
  1. <?php
  2. /**
  3. * @copyright Copyright (C) Ibexa AS. All rights reserved.
  4. * @license For full copyright and license information view LICENSE file distributed with this source code.
  5. */
  6. declare(strict_types=1);
  7. namespace Ibexa\Bundle\Seo\EventSubscriber\Migrations;
  8. use Ibexa\Migration\Event\FieldValueFromHashEvent;
  9. use Ibexa\Migration\Event\HashFromFieldValueEvent;
  10. use Ibexa\Migration\Event\MigrationEvents;
  11. use Ibexa\Seo\FieldType\SeoType;
  12. use Ibexa\Seo\FieldType\SeoValue;
  13. use Ibexa\Seo\Value\SeoTypesValue;
  14. use Ibexa\Seo\Value\SeoTypeValue;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Webmozart\Assert\Assert;
  17. final class FieldValueHashMapperSubscriber implements EventSubscriberInterface
  18. {
  19. /**
  20. * @return array<string, array{string, int}>
  21. */
  22. public static function getSubscribedEvents(): array
  23. {
  24. return [
  25. MigrationEvents::BEFORE_FIELD_VALUE_FROM_HASH => [
  26. 'convertScalarHashIntoObjects',
  27. -100,
  28. ],
  29. MigrationEvents::AFTER_HASH_FROM_FIELD_VALUE => [
  30. 'convertObjectHashIntoScalarHash',
  31. -100,
  32. ],
  33. ];
  34. }
  35. public function convertScalarHashIntoObjects(FieldValueFromHashEvent $event): void
  36. {
  37. /** @var array<mixed> $hash */
  38. $hash = $event->getHash();
  39. $fieldTypeIdentifier = $event->getFieldTypeIdentifier();
  40. if ($fieldTypeIdentifier !== SeoType::IDENTIFIER || empty($hash['types'])) {
  41. return;
  42. }
  43. Assert::isArray($hash['types']);
  44. $fieldValueHash = ['value' => new SeoTypesValue()];
  45. foreach ($hash['types'] as $type) {
  46. $fieldValueHash['value']->setType($type['type'], new SeoTypeValue($type['type'], $type['fields']));
  47. }
  48. $event->setHash($fieldValueHash);
  49. }
  50. public function convertObjectHashIntoScalarHash(HashFromFieldValueEvent $event): void
  51. {
  52. /** @var array{value: \Ibexa\Seo\FieldType\SeoValue} $hash */
  53. $hash = $event->getHash();
  54. if (empty($hash['value']) || !$hash['value'] instanceof SeoValue) {
  55. return;
  56. }
  57. $seoTypesValue = $hash['value']->getSeoTypesValue();
  58. Assert::notNull($seoTypesValue);
  59. $scalarHash = ['types' => []];
  60. foreach ($seoTypesValue->getSeoTypesValues() as $seoTypeValue) {
  61. $type = $seoTypeValue->getType();
  62. $scalarHash['types'][$type] = $seoTypeValue->jsonSerialize();
  63. }
  64. $event->setHash($scalarHash);
  65. }
  66. }