Completed
Push — master ( 173f5d...31a9ea )
by
unknown
15:41 queued 11s
created

MediaBlockService::validateBlock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\MediaBundle\Block;
15
16
use Doctrine\ORM\Mapping\ClassMetadataInfo;
17
use Sonata\AdminBundle\Form\FormMapper;
18
use Sonata\AdminBundle\Form\Type\ModelListType;
19
use Sonata\BlockBundle\Block\BlockContextInterface;
20
use Sonata\BlockBundle\Block\Service\AbstractBlockService;
21
use Sonata\BlockBundle\Meta\Metadata;
22
use Sonata\BlockBundle\Model\BlockInterface;
23
use Sonata\Doctrine\Model\ManagerInterface;
24
use Sonata\Form\Type\ImmutableArrayType;
25
use Sonata\Form\Validator\ErrorElement;
26
use Sonata\MediaBundle\Admin\BaseMediaAdmin;
27
use Sonata\MediaBundle\Model\MediaInterface;
28
use Sonata\MediaBundle\Provider\Pool;
29
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
30
use Symfony\Component\DependencyInjection\ContainerInterface;
31
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
32
use Symfony\Component\Form\Extension\Core\Type\TextType;
33
use Symfony\Component\Form\FormBuilder;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\OptionsResolver\OptionsResolver;
36
use Twig\Environment;
37
38
/**
39
 * @final since sonata-project/media-bundle 3.21.0
40
 *
41
 * @author Thomas Rabaix <[email protected]>
42
 */
43
class MediaBlockService extends AbstractBlockService
44
{
45
    /**
46
     * @var BaseMediaAdmin
47
     */
48
    protected $mediaAdmin;
49
50
    /**
51
     * @var ManagerInterface
52
     */
53
    protected $mediaManager;
54
55
    /**
56
     * @var ContainerInterface
57
     */
58
    private $container;
59
60
    /**
61
     * NEXT_MAJOR: Remove `$templating` argument.
62
     *
63
     * @param Environment|string $twigOrName
64
     */
65
    public function __construct(
66
        $twigOrName,
67
        ?EngineInterface $templating,
68
        ContainerInterface $container,
69
        ManagerInterface $mediaManager
70
    ) {
71
        parent::__construct($twigOrName, $templating);
72
73
        $this->mediaManager = $mediaManager;
74
        $this->container = $container;
75
    }
76
77
    /**
78
     * @return Pool
79
     */
80
    public function getMediaPool()
81
    {
82
        return $this->getMediaAdmin()->getPool();
83
    }
84
85
    /**
86
     * @return BaseMediaAdmin
87
     */
88
    public function getMediaAdmin()
89
    {
90
        if (!$this->mediaAdmin) {
91
            $this->mediaAdmin = $this->container->get('sonata.media.admin.media');
92
        }
93
94
        return $this->mediaAdmin;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function configureSettings(OptionsResolver $resolver): void
101
    {
102
        $resolver->setDefaults([
103
            'media' => false,
104
            'title' => null,
105
            'translation_domain' => null,
106
            'icon' => null,
107
            'class' => null,
108
            'context' => false,
109
            'mediaId' => null,
110
            'format' => false,
111
            'template' => '@SonataMedia/Block/block_media.html.twig',
112
        ]);
113
    }
114
115
    /**
116
     * NEXT_MAJOR: Remove this method.
117
     *
118
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
119
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
120
     */
121
    public function buildEditForm(FormMapper $formMapper, BlockInterface $block): void
122
    {
123
        if (!$block->getSetting('mediaId') instanceof MediaInterface) {
124
            $this->load($block);
125
        }
126
127
        $formatChoices = $this->getFormatChoices($block->getSetting('mediaId'));
128
129
        $formMapper->add('settings', ImmutableArrayType::class, [
130
            'keys' => [
131
                ['title', TextType::class, [
132
                    'label' => 'form.label_title',
133
                    'required' => false,
134
                ]],
135
                ['translation_domain', TextType::class, [
136
                    'label' => 'form.label_translation_domain',
137
                    'required' => false,
138
                ]],
139
                ['icon', TextType::class, [
140
                    'label' => 'form.label_icon',
141
                    'required' => false,
142
                ]],
143
                ['class', TextType::class, [
144
                    'label' => 'form.label_class',
145
                    'required' => false,
146
                ]],
147
                [$this->getMediaBuilder($formMapper), null, []],
148
                ['format', ChoiceType::class, [
149
                    'required' => \count($formatChoices) > 0,
150
                    'choices' => $formatChoices,
151
                    'label' => 'form.label_format',
152
                ]],
153
            ],
154
            'translation_domain' => 'SonataMediaBundle',
155
        ]);
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function execute(BlockContextInterface $blockContext, ?Response $response = null)
162
    {
163
        // make sure we have a valid format
164
        $media = $blockContext->getBlock()->getSetting('mediaId');
165
        if ($media instanceof MediaInterface) {
166
            $choices = $this->getFormatChoices($media);
167
168
            if (!\array_key_exists($blockContext->getSetting('format'), $choices)) {
169
                $blockContext->setSetting('format', key($choices));
170
            }
171
        }
172
173
        return $this->renderResponse($blockContext->getTemplate(), [
174
            'media' => $blockContext->getSetting('mediaId'),
175
            'block' => $blockContext->getBlock(),
176
            'settings' => $blockContext->getSettings(),
177
        ], $response);
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function load(BlockInterface $block): void
184
    {
185
        $media = $block->getSetting('mediaId', null);
186
187
        if (\is_int($media)) {
188
            $media = $this->mediaManager->findOneBy(['id' => $media]);
189
        }
190
191
        $block->setSetting('mediaId', $media);
192
    }
193
194
    /**
195
     * {@inheritdoc}
196
     */
197
    public function prePersist(BlockInterface $block): void
198
    {
199
        $block->setSetting('mediaId', \is_object($block->getSetting('mediaId')) ? $block->getSetting('mediaId')->getId() : null);
200
    }
201
202
    /**
203
     * {@inheritdoc}
204
     */
205
    public function preUpdate(BlockInterface $block): void
206
    {
207
        $block->setSetting('mediaId', \is_object($block->getSetting('mediaId')) ? $block->getSetting('mediaId')->getId() : null);
208
    }
209
210
    /**
211
     * NEXT_MAJOR: Remove this method.
212
     *
213
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
214
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
215
     */
216
    public function getBlockMetadata($code = null)
217
    {
218
        return new Metadata($this->getName(), (null !== $code ? $code : $this->getName()), false, 'SonataMediaBundle', [
219
            'class' => 'fa fa-picture-o',
220
        ]);
221
    }
222
223
    /**
224
     * NEXT_MAJOR: Remove this method.
225
     *
226
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
227
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
228
     */
229
    public function buildCreateForm(FormMapper $formMapper, BlockInterface $block)
230
    {
231
        $this->buildEditForm($formMapper, $block);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\MediaBundle\Block...ervice::buildEditForm() has been deprecated with message: since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
232
    }
233
234
    /**
235
     * NEXT_MAJOR: Remove this method.
236
     *
237
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
238
     */
239
    public function postPersist(BlockInterface $block)
0 ignored issues
show
Unused Code introduced by
The parameter $block is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
240
    {
241
    }
242
243
    /**
244
     * NEXT_MAJOR: Remove this method.
245
     *
246
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
247
     */
248
    public function postUpdate(BlockInterface $block)
0 ignored issues
show
Unused Code introduced by
The parameter $block is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
249
    {
250
    }
251
252
    /**
253
     * NEXT_MAJOR: Remove this method.
254
     *
255
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
256
     */
257
    public function preRemove(BlockInterface $block)
0 ignored issues
show
Unused Code introduced by
The parameter $block is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
258
    {
259
    }
260
261
    /**
262
     * NEXT_MAJOR: Remove this method.
263
     *
264
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
265
     */
266
    public function postRemove(BlockInterface $block)
0 ignored issues
show
Unused Code introduced by
The parameter $block is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
267
    {
268
    }
269
270
    /**
271
     * NEXT_MAJOR: Remove this method.
272
     *
273
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
274
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
275
     */
276
    public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
0 ignored issues
show
Unused Code introduced by
The parameter $errorElement is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $block is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
277
    {
278
    }
279
280
    /**
281
     * @return array
282
     */
283
    protected function getFormatChoices(?MediaInterface $media = null)
284
    {
285
        $formatChoices = [];
286
287
        if (!$media instanceof MediaInterface) {
288
            return $formatChoices;
289
        }
290
291
        $formats = $this->getMediaPool()->getFormatNamesByContext($media->getContext());
292
293
        foreach ($formats as $code => $format) {
0 ignored issues
show
Bug introduced by
The expression $formats of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
294
            $formatChoices[$code] = $code;
295
        }
296
297
        return $formatChoices;
298
    }
299
300
    /**
301
     * @return FormBuilder
302
     */
303
    protected function getMediaBuilder(FormMapper $formMapper)
304
    {
305
        // simulate an association ...
306
        $fieldDescription = $this->getMediaAdmin()->getModelManager()->getNewFieldDescriptionInstance($this->mediaAdmin->getClass(), 'media', [
307
            'translation_domain' => 'SonataMediaBundle',
308
        ]);
309
        $fieldDescription->setAssociationAdmin($this->getMediaAdmin());
310
        $fieldDescription->setAdmin($formMapper->getAdmin());
311
        $fieldDescription->setOption('edit', 'list');
312
        $fieldDescription->setAssociationMapping([
313
            'fieldName' => 'media',
314
            'type' => ClassMetadataInfo::MANY_TO_ONE,
315
        ]);
316
317
        return $formMapper->create('mediaId', ModelListType::class, [
318
            'sonata_field_description' => $fieldDescription,
319
            'class' => $this->getMediaAdmin()->getClass(),
320
            'model_manager' => $this->getMediaAdmin()->getModelManager(),
321
            'label' => 'form.label_media',
322
        ]);
323
    }
324
}
325