Passed
Push — dependabot/composer/doctrine/d... ( bc1a80...bcc5a8 )
by
unknown
47:19 queued 41:28
created

Modules/MediaLibrary/Helper/FrontendHelper.php (2 issues)

Labels
Severity
1
<?php
2
3
namespace Frontend\Modules\MediaLibrary\Helper;
4
5
use Backend\Modules\MediaLibrary\Domain\MediaGroupMediaItem\MediaGroupMediaItem;
6
use Frontend\Core\Header\Header;
7
use Frontend\Core\Engine\Model as FrontendModel;
8
use Frontend\Core\Engine\Block\Widget as FrontendBlockWidget;
9
use Backend\Modules\MediaLibrary\Domain\MediaGroup\MediaGroup;
10
use Backend\Modules\MediaLibrary\Domain\MediaItem\MediaItem;
11
use Backend\Modules\MediaLibrary\Domain\MediaGroupMediaItem\MediaGroupMediaItemRepository;
12
13
/**
14
 * Frontend Helper
15
 * With this helper you can use the MediaLibrary Module easier then ever.
16
 */
17
class FrontendHelper
18
{
19
    /** @var MediaGroupMediaItemRepository */
20
    protected $mediaGroupMediaItemRepository;
21
22
    public function __construct(MediaGroupMediaItemRepository $mediaGroupMediaItemRepository)
23
    {
24
        $this->mediaGroupMediaItemRepository = $mediaGroupMediaItemRepository;
25
    }
26
27
    /**
28
     * Use this function for index pages,
29
     * where you only want to get the first media item for your entities.
30
     *
31
     * @param array $entities
32
     * @param string $methodForMediaGroup - F.e.: "getImagesMediaGroup"
33
     * @param string $newVariableName - F.e.: "image", this variable will be assigned in your entity
34
     * @param bool $onlyGetTheFirstMediaItem - true = only get the first item, false = get all items
35
     *
36
     * @throws \Exception
37
     */
38
    public function addMediaItemsToEntities(
39
        array $entities,
40
        string $methodForMediaGroup,
41
        string $newVariableName,
42
        bool $onlyGetTheFirstMediaItem = true
43
    ): void {
44
        // Init variables
45
        $mediaGroupIds = [];
46
        $entityKeys = [];
47
        $counter = 1;
48
49
        // Loop entities to get mediaGroup id
50
        foreach ($entities as $entityKey => $entity) {
51
            if ($entity === null) {
52
                unset($entities[$entityKey]);
53
                continue;
54
            }
55
56
            // Check if variable already exists or not
57
            if ($counter === 1) {
58
                if (property_exists($entities[$entityKey], $newVariableName)) {
59
                    throw new \Exception(
60
                        'The $newVariableName "' . $newVariableName . '" already exists, choose another name.'
61
                    );
62
                }
63
            }
64
65
            // Check if media group is not null
66
            if ($entity->{$methodForMediaGroup}() === null) {
67
                // skip this item
68
                continue;
69
            }
70
71
            // Define keys for later use
72
            $mediaGroupIds[(string) $entity->{$methodForMediaGroup}()->getId()] = $entity->getId();
73
            $entityKeys[$entity->getId()] = $entityKey;
74
75
            ++$counter;
76
        }
77
78
        // Define all MediaGroupMediaItem entities
79
        $mediaGroupMediaItems = $this->mediaGroupMediaItemRepository->getAll(
80
            array_keys($mediaGroupIds),
81
            (bool) $onlyGetTheFirstMediaItem
82
        );
83
84
        /** @var MediaGroupMediaItem $mediaGroupMediaItem */
85
        foreach ($mediaGroupMediaItems as $mediaGroupMediaItem) {
86
            $entityKey = $entityKeys[$mediaGroupIds[(string) $mediaGroupMediaItem->getGroup()->getId()]];
87
            $mediaItem = $mediaGroupMediaItem->getItem();
88
89
            if ($onlyGetTheFirstMediaItem) {
90
                // Define frontend media item
91
                $entities[$entityKey]->{$newVariableName} = $mediaItem;
92
93
                continue;
94
            }
95
96
            // Define frontend media item
97
            $entities[$entityKey]->{$newVariableName}[] = $mediaItem;
98
        }
99
    }
100
101
    /**
102
     * Add Open Graph Images for MediaGroup
103
     *
104
     * @param MediaGroup $mediaGroup
105
     * @param Header $header @todo: when we have a header in our services, use that one instead and remove this method variable
106
     * @param int $maximumItems Default is null, which means infinite images will be added to header
107
     */
108
    public function addOpenGraphImagesForMediaGroup(MediaGroup $mediaGroup, Header $header, int $maximumItems = 0): void
109
    {
110
        // Define variables
111
        $counter = 0;
112
113
        // Loop all connected items
114
        foreach ($mediaGroup->getConnectedItems() as $connectedItem) {
115
            if ($maximumItems !== 0 && $counter >= $maximumItems) {
116
                break;
117
            }
118
119
            if ($this->addOpenGraphImageForMediaItem($connectedItem->getItem(), $header)) {
120
                ++$counter;
121
            }
122
        }
123
    }
124
125
    /**
126
     * @param MediaItem $mediaItem
127
     * @param Header $header @todo: when we have a header in our services, use that one instead and remove this method variable
128
     *
129
     * @return bool
130
     */
131
    public function addOpenGraphImageForMediaItem(MediaItem $mediaItem, Header $header): bool
132
    {
133
        // Only image allowed
134
        if (!$mediaItem->getType()->isImage()) {
135
            return false;
136
        }
137
138
        $header->addOpenGraphImage(
139
            $mediaItem->getAbsoluteWebPath(),
140
            false,
141
            $mediaItem->getWidth(),
0 ignored issues
show
It seems like $mediaItem->getWidth() can also be of type null; however, parameter $width of Frontend\Core\Header\Header::addOpenGraphImage() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

141
            /** @scrutinizer ignore-type */ $mediaItem->getWidth(),
Loading history...
142
            $mediaItem->getHeight()
0 ignored issues
show
It seems like $mediaItem->getHeight() can also be of type null; however, parameter $height of Frontend\Core\Header\Header::addOpenGraphImage() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

142
            /** @scrutinizer ignore-type */ $mediaItem->getHeight()
Loading history...
143
        );
144
145
        return true;
146
    }
147
148
    /**
149
     * Parse widget for a MediaGroupId in a custom module.
150
     *
151
     * Example:
152
     * $this->template->assign(
153
     *     'imagesWidget',
154
     *     // We can create widget for the MediaGroup id
155
     *     $this->get('media_library.helper.frontend')->parseWidget(
156
     *         'Lightbox',
157
     *         $this->blogArticle->getImageMediaGroup()->getId(),
158
     *         'My custom optional title',
159
     *         'CustomModule' // Optional field, if not given, defaults to "MediaLibrary"
160
     *     )
161
     * );
162
     *
163
     * @param string $mediaWidgetAction The ClassName from the Media widget you want to use.
164
     * @param string $mediaGroupId The MediaGroup id you want to parse
165
     * @param string $title You can give your optional custom title.
166
     * @param string $module You can parse a widget from a custom module. Default is the "MediaLibrary" module.
167
     *
168
     * @throws \Exception
169
     *
170
     * @return mixed
171
     */
172
    public function parseWidget(
173
        string $mediaWidgetAction,
174
        string $mediaGroupId,
175
        string $title = null,
176
        string $module = null
177
    ) {
178
        if ($module === null) {
179
            $module = 'MediaLibrary';
180
        }
181
182
        // Create new widget instance and return parsed content
183
        $widget = new FrontendBlockWidget(
184
            FrontendModel::get('kernel'),
185
            $module,
186
            $mediaWidgetAction,
187
            serialize(
188
                [
189
                    'group_id' => $mediaGroupId,
190
                    'title' => $title,
191
                ]
192
            )
193
        );
194
195
        return $this->parseWidgetContent($widget);
196
    }
197
198
    private function parseWidgetContent(FrontendBlockWidget $widget): string
199
    {
200
        try {
201
            $widget->execute();
202
203
            return $widget->getContent();
204
        } catch (\Exception $e) {
205
            // if we are debugging, we want to see the exception
206
            if (FrontendModel::getContainer()->getParameter('kernel.debug')) {
207
                throw $e;
208
            }
209
210
            return '';
211
        }
212
    }
213
}
214