MediaBlockService::getMediaAdmin()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
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
    public function configureSettings(OptionsResolver $resolver): void
98
    {
99
        $resolver->setDefaults([
100
            'media' => false,
101
            'title' => null,
102
            'translation_domain' => null,
103
            'icon' => null,
104
            'class' => null,
105
            'context' => false,
106
            'mediaId' => null,
107
            'format' => false,
108
            'template' => '@SonataMedia/Block/block_media.html.twig',
109
        ]);
110
    }
111
112
    /**
113
     * NEXT_MAJOR: Remove this method.
114
     *
115
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
116
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
117
     */
118
    public function buildEditForm(FormMapper $formMapper, BlockInterface $block): void
119
    {
120
        if (!$block->getSetting('mediaId') instanceof MediaInterface) {
121
            $this->load($block);
122
        }
123
124
        $formatChoices = $this->getFormatChoices($block->getSetting('mediaId'));
125
126
        $formMapper->add('settings', ImmutableArrayType::class, [
127
            'keys' => [
128
                ['title', TextType::class, [
129
                    'label' => 'form.label_title',
130
                    'required' => false,
131
                ]],
132
                ['translation_domain', TextType::class, [
133
                    'label' => 'form.label_translation_domain',
134
                    'required' => false,
135
                ]],
136
                ['icon', TextType::class, [
137
                    'label' => 'form.label_icon',
138
                    'required' => false,
139
                ]],
140
                ['class', TextType::class, [
141
                    'label' => 'form.label_class',
142
                    'required' => false,
143
                ]],
144
                [$this->getMediaBuilder($formMapper), null, []],
145
                ['format', ChoiceType::class, [
146
                    'required' => \count($formatChoices) > 0,
147
                    'choices' => $formatChoices,
148
                    'label' => 'form.label_format',
149
                ]],
150
            ],
151
            'translation_domain' => 'SonataMediaBundle',
152
        ]);
153
    }
154
155
    public function execute(BlockContextInterface $blockContext, ?Response $response = null)
156
    {
157
        // make sure we have a valid format
158
        $media = $blockContext->getBlock()->getSetting('mediaId');
159
        if ($media instanceof MediaInterface) {
160
            $choices = $this->getFormatChoices($media);
161
162
            if (!\array_key_exists($blockContext->getSetting('format'), $choices)) {
163
                $blockContext->setSetting('format', key($choices));
164
            }
165
        }
166
167
        return $this->renderResponse($blockContext->getTemplate(), [
168
            'media' => $blockContext->getSetting('mediaId'),
169
            'block' => $blockContext->getBlock(),
170
            'settings' => $blockContext->getSettings(),
171
        ], $response);
172
    }
173
174
    public function load(BlockInterface $block): void
175
    {
176
        $media = $block->getSetting('mediaId', null);
177
178
        if (\is_int($media)) {
179
            $media = $this->mediaManager->findOneBy(['id' => $media]);
180
        }
181
182
        $block->setSetting('mediaId', $media);
183
    }
184
185
    public function prePersist(BlockInterface $block): void
186
    {
187
        $block->setSetting('mediaId', \is_object($block->getSetting('mediaId')) ? $block->getSetting('mediaId')->getId() : null);
188
    }
189
190
    public function preUpdate(BlockInterface $block): void
191
    {
192
        $block->setSetting('mediaId', \is_object($block->getSetting('mediaId')) ? $block->getSetting('mediaId')->getId() : null);
193
    }
194
195
    /**
196
     * NEXT_MAJOR: Remove this method.
197
     *
198
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
199
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
200
     */
201
    public function getBlockMetadata($code = null)
202
    {
203
        return new Metadata($this->getName(), (null !== $code ? $code : $this->getName()), false, 'SonataMediaBundle', [
204
            'class' => 'fa fa-picture-o',
205
        ]);
206
    }
207
208
    /**
209
     * NEXT_MAJOR: Remove this method.
210
     *
211
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
212
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
213
     */
214
    public function buildCreateForm(FormMapper $formMapper, BlockInterface $block)
215
    {
216
        $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...
217
    }
218
219
    /**
220
     * NEXT_MAJOR: Remove this method.
221
     *
222
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
223
     */
224
    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...
225
    {
226
    }
227
228
    /**
229
     * NEXT_MAJOR: Remove this method.
230
     *
231
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
232
     */
233
    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...
234
    {
235
    }
236
237
    /**
238
     * NEXT_MAJOR: Remove this method.
239
     *
240
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
241
     */
242
    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...
243
    {
244
    }
245
246
    /**
247
     * NEXT_MAJOR: Remove this method.
248
     *
249
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0.
250
     */
251
    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...
252
    {
253
    }
254
255
    /**
256
     * NEXT_MAJOR: Remove this method.
257
     *
258
     * @deprecated since sonata-project/media-bundle 3.25, to be removed in 4.0. You should use
259
     *             `Sonata\BlockBundle\Block\Service\EditableBlockService` interface instead.
260
     */
261
    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...
262
    {
263
    }
264
265
    /**
266
     * @return array
267
     */
268
    protected function getFormatChoices(?MediaInterface $media = null)
269
    {
270
        $formatChoices = [];
271
272
        if (!$media instanceof MediaInterface) {
273
            return $formatChoices;
274
        }
275
276
        $formats = $this->getMediaPool()->getFormatNamesByContext($media->getContext());
277
278
        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...
279
            $formatChoices[$code] = $code;
280
        }
281
282
        return $formatChoices;
283
    }
284
285
    /**
286
     * @return FormBuilder
287
     */
288
    protected function getMediaBuilder(FormMapper $formMapper)
289
    {
290
        // simulate an association ...
291
        $fieldDescription = $this->getMediaAdmin()->getModelManager()->getNewFieldDescriptionInstance($this->mediaAdmin->getClass(), 'media', [
292
            'translation_domain' => 'SonataMediaBundle',
293
        ]);
294
        $fieldDescription->setAssociationAdmin($this->getMediaAdmin());
295
        $fieldDescription->setAdmin($formMapper->getAdmin());
296
        $fieldDescription->setOption('edit', 'list');
297
        $fieldDescription->setAssociationMapping([
298
            'fieldName' => 'media',
299
            'type' => ClassMetadataInfo::MANY_TO_ONE,
300
        ]);
301
302
        return $formMapper->create('mediaId', ModelListType::class, [
303
            'sonata_field_description' => $fieldDescription,
304
            'class' => $this->getMediaAdmin()->getClass(),
305
            'model_manager' => $this->getMediaAdmin()->getModelManager(),
306
            'label' => 'form.label_media',
307
        ]);
308
    }
309
}
310