<?php
namespace App\Doctrine\DBAL\Types;
use App\Model\Mobile\Shortcut;
use App\Util\Json;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\JsonType;
/**
*
*/
final class ShortcutArrayType extends JsonType
{
/**
* {@inheritdoc}
*/
public function getName(): string
{
return 'shortcut_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 null;
}
// we should have an array
if ( ! is_array($value)) {
throw new \LogicException();
}
// send back the json string
// technically, it should be a numeric array
// decode and enforce a numeric array
return Json::encode(array_values($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 null;
}
// 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 [];
}
// convert all items to their proper media type
return array_map(
static function (array $data) {
return Shortcut::build($data);
},
$data
);
}
}