src/App/Doctrine/DBAL/Types/MediaArrayType.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Doctrine\DBAL\Types;
  3. use App\Model\Content\Media\MediaCollection;
  4. use App\Util\Json;
  5. use Doctrine\DBAL\Platforms\AbstractPlatform;
  6. use Doctrine\DBAL\Types\JsonType;
  7. /**
  8.  *
  9.  */
  10. final class MediaArrayType extends JsonType
  11. {
  12.     /**
  13.      * {@inheritdoc}
  14.      */
  15.     public function getName(): string
  16.     {
  17.         return 'media_array';
  18.     }
  19.     /**
  20.      * {@inheritdoc}
  21.      */
  22.     public function requiresSQLCommentHint(AbstractPlatform $platform): bool
  23.     {
  24.         return true;
  25.     }
  26.     /**
  27.      * {@inheritdoc}
  28.      */
  29.     public function convertToDatabaseValue($valueAbstractPlatform $platform)
  30.     {
  31.         // if null, just return that
  32.         if ($value === null) {
  33.             return '[]';
  34.         }
  35.         // we should have an array
  36.         if ( ! $value instanceof MediaCollection) {
  37.             throw new \LogicException();
  38.         }
  39.         // send back the json string
  40.         // technically, it should be a numeric array
  41.         return Json::encode($value);
  42.     }
  43.     /**
  44.      * {@inheritdoc}
  45.      */
  46.     public function convertToPHPValue($valueAbstractPlatform $platform)
  47.     {
  48.         // handle empty values
  49.         // empty arrays are allowed and should not be considered as null!
  50.         if ($value === null || $value === '') {
  51.             return new MediaCollection();
  52.         }
  53.         // decode the json and check for errors
  54.         $data Json::decode($valuetrue);
  55.         // if there is no data in any way, return an empty array
  56.         // this handles json encoded nulls, empty strings, bools, etc
  57.         if (empty($data) || ! is_array($data)) {
  58.             return new MediaCollection();
  59.         }
  60.         // convert all items to their proper media type
  61.         return new MediaCollection($data);
  62.     }
  63. }