<?php
namespace App\Form\Type;
use App\Model\Content\Media\AbstractMedia;
use App\Model\Content\Media\AbstractLooseMedia;
use App\Model\Content\Media\MediaCollection;
use App\Service\MediaDecorator;
use App\Util\Arrays;
use App\Util\Json;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\RouterInterface;
/**
*
*/
final class ReactMediaManagerType extends AbstractReactType implements DataTransformerInterface
{
protected const REACT_APP = 'media-manager';
// DI
protected MediaDecorator $decorator;
protected RouterInterface $router;
/**
*
*/
public function __construct(
MediaDecorator $decorator,
RouterInterface $router
)
{
$this->decorator = $decorator;
$this->router = $router;
}
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addModelTransformer($this);
}
/**
* {@inheritDoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['react_config'] = [
'filetypes' => $options['filetypes'] ?: [],
'limit' => $options['limit'] ?: 0,
];
$view->vars['react_routing'] = Arrays::array_map_assoc(
function (string $route, ?array $params) {
return $this->router->generate(
$route,
$params ?: [],
);
},
[
'app.ajax.filesystem.allocate_files' => null,
'app.ajax.filesystem.uploaded' => null,
'app.ajax.filesystem.check' => null,
'app.notifications.dashboard.recording.phone_wait' => [
'recording' => '~recording~',
],
],
);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'filetypes' => [],
'limit' => 0,
]);
$resolver->setAllowedTypes('filetypes', 'array');
$resolver->setAllowedTypes('limit', 'int');
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if ( ! $value instanceof MediaCollection) {
return Json::encode([]);
}
$this->decorator
->entities($value)
->uploads($value)
->meta($value)
->urls($value);
$folder = null;
foreach (($medias = $value->toArray()) as $media) {
if ($media instanceof AbstractLooseMedia && $media->getFile() && $media->getFile()->getFolder()) {
$folder = $media->getFile()->getFolder()->getId();
}
}
return Json::encode([
'storage' => 'temporary',
'location' => $folder,
'media' => array_map(
static function (AbstractMedia $media) {
return array_merge(
$media->jsonSerialize(),
[
'uploaded' => true,
'processed' => true,
]
);
},
$medias
)
]);
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if (empty($value)) {
return new MediaCollection();
}
$value = Json::decode($value, true);
if (empty($value)) {
return new MediaCollection();
}
return new MediaCollection($value['media'] ?: []);
}
}