<?php
namespace App\Doctrine\DBAL\Types;
use App\Model\Content\Media\MediaCollection;
use App\Util\Json;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\JsonType;
/**
*
*/
final class MediaArrayType extends JsonType
{
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'media_array';
}
/**
* {@inheritdoc}
*/
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return true;
}
/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
// if null, just return that
if ($value === null) {
return '[]';
}
// we should have an array
if ( ! $value instanceof MediaCollection) {
throw new \LogicException();
}
// send back the json string
// technically, it should be a numeric array
return Json::encode($value);
}
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
// handle empty values
// empty arrays are allowed and should not be considered as null!
if ($value === null || $value === '') {
return new MediaCollection();
}
// decode the json and check for errors
$data = Json::decode($value, true);
// if there is no data in any way, return an empty array
// this handles json encoded nulls, empty strings, bools, etc
if (empty($data) || ! is_array($data)) {
return new MediaCollection();
}
// convert all items to their proper media type
return new MediaCollection($data);
}
}