Completed
Push — master ( a06a95...a1d542 )
by dan
15s
created

ResponsiveImageExtension::getFunctions()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 41
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 26
nc 1
nop 0
1
<?php
2
/**
3
 * This file is part of the IrishDan\ResponsiveImageBundle package.
4
 *
5
 * (c) Daniel Byrne <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source
8
 * code.
9
 */
10
11
namespace IrishDan\ResponsiveImageBundle\Twig;
12
13
14
use IrishDan\ResponsiveImageBundle\ImageProcessing\ImageManager;
15
use IrishDan\ResponsiveImageBundle\ResponsiveImageInterface;
16
use IrishDan\ResponsiveImageBundle\StyleManager;
17
use IrishDan\ResponsiveImageBundle\Url\UrlBuilder;
18
19
/**
20
 * Class ResponsiveImageExtension
21
 *
22
 * @package ResponsiveImageBundle\Twig
23
 */
24
class ResponsiveImageExtension extends \Twig_Extension
25
{
26
    /**
27
     * @var StyleManager
28
     */
29
    private $styleManager;
30
    /**
31
     * @var UrlBuilder
32
     */
33
    private $urlBuilder;
34
    /**
35
     * @var ImageManager
36
     */
37
    private $imageManager;
38
39
    /**
40
     * ResponsiveImageExtension constructor.
41
     *
42
     * @param StyleManager      $styleManager
43
     * @param UrlBuilder        $urlBuilder
44
     * @param ImageManager|null $imageManager
45
     */
46
    public function __construct(StyleManager $styleManager, UrlBuilder $urlBuilder, ImageManager $imageManager = null)
47
    {
48
        $this->styleManager = $styleManager;
49
        $this->urlBuilder   = $urlBuilder;
50
        $this->imageManager = $imageManager;
51
    }
52
53
    /**
54
     * @return array
55
     */
56
    public function getFunctions()
57
    {
58
        return [
59
            new \Twig_SimpleFunction(
60
                'picture_image', [$this, 'generatePictureImage'], [
61
                    'is_safe'           => ['html'],
62
                    'needs_environment' => true,
63
                ]
64
            ),
65
            new \Twig_SimpleFunction(
66
                'sizes_image', [$this, 'generateSizesImage'], [
67
                    'is_safe'           => ['html'],
68
                    'needs_environment' => true,
69
                ]
70
            ),
71
            new \Twig_SimpleFunction(
72
                'styled_image', [$this, 'generateStyledImage'], [
73
                    'is_safe'           => ['html'],
74
                    'needs_environment' => true,
75
                ]
76
            ),
77
            new \Twig_SimpleFunction(
78
                'crop_image', [$this, 'cropImage'], [
79
                    'is_safe'           => ['html'],
80
                    'needs_environment' => true,
81
                ]
82
            ),
83
            new \Twig_SimpleFunction(
84
                'scale_image', [$this, 'scaleImage'], [
85
                    'is_safe'           => ['html'],
86
                    'needs_environment' => true,
87
                ]
88
            ),
89
            new \Twig_SimpleFunction(
90
                'background_responsive_image', [$this, 'generateBackgroundImage'], [
91
                    'is_safe'           => ['html'],
92
                    'needs_environment' => true,
93
                ]
94
            ),
95
        ];
96
    }
97
98
    /**
99
     * @param \Twig_Environment        $environment
100
     * @param ResponsiveImageInterface $image
101
     * @param                          $pictureSetName
102
     * @param                          $selector
103
     *
104
     * @return mixed|string
105
     */
106 View Code Duplication
    public function generateBackgroundImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $pictureSetName, $selector)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
    {
108
        $cssData = $this->styleManager->getPictureData($image, $pictureSetName);
109
        $this->convertPathsToUrls($cssData, ['fallback', 'sources']);
110
111
        return $environment->render(
112
            'ResponsiveImageBundle::css.html.twig',
113
            [
114
                'fallback' => $cssData['fallback'],
115
                'sources'  => $cssData['sources'],
116
                'image'    => $image,
117
                'selector' => $selector,
118
            ]
119
        );
120
    }
121
122
    /**
123
     * @param \Twig_Environment        $environment
124
     * @param ResponsiveImageInterface $image
125
     * @param                          $pictureSetName
126
     * @param bool                     $generate
127
     *
128
     * @return mixed|string
129
     */
130 View Code Duplication
    public function generatePictureImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $pictureSetName, $generate = false)
0 ignored issues
show
Unused Code introduced by
The parameter $generate 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...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
    {
132
        $pictureData = $this->styleManager->getPictureData($image, $pictureSetName);
133
        $this->convertPathsToUrls($pictureData, ['fallback', 'sources']);
134
135
        return $environment->render(
136
            'ResponsiveImageBundle::picture.html.twig',
137
            [
138
                'fallback' => $pictureData['fallback'],
139
                'sources'  => $pictureData['sources'],
140
                'image'    => $image,
141
            ]
142
        );
143
    }
144
145
    /**
146
     * @internal
147
     *
148
     * @param array $data
149
     * @param array $keys
150
     */
151
    private function convertPathsToUrls(array &$data, array $keys)
152
    {
153
        foreach ($keys as $key) {
154
            if (is_array($data[$key])) {
155
                $subData = [];
156
                foreach ($data[$key] as $item => $path) {
157
                    $subData[$item] = $this->createPublicFileUrl($path);
158
                }
159
                $data[$key] = $subData;
160
            }
161
            else {
162
                $data[$key] = $this->createPublicFileUrl($data[$key]);
163
            }
164
        }
165
    }
166
167
    /**
168
     * Some path strings could contain more than one path, eg 1x and 2x paths.
169
     * This function breaks them up and converts to the full public url.
170
     *
171
     * @param $path
172
     *
173
     * @return string
174
     */
175
    private function createPublicFileUrl($path)
176
    {
177
        $pathArray = explode(',', $path);
178
        foreach ($pathArray as $key => $item) {
179
            $pathArray[$key] = $this->urlBuilder->filePublicUrl(trim($item));
180
        }
181
182
        return implode(', ', $pathArray);
183
    }
184
185
    /**
186
     * @param \Twig_Environment        $environment
187
     * @param ResponsiveImageInterface $image
188
     * @param                          $pictureSetName
189
     * @param bool                     $generate
190
     *
191
     * @return mixed|string
192
     */
193
    public function generateSizesImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $pictureSetName, $generate = false)
0 ignored issues
show
Unused Code introduced by
The parameter $generate 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...
194
    {
195
        $sizesData = $this->styleManager->getImageSizesData($image, $pictureSetName);
196
197
        // Replace the relative path with the real path.
198
        foreach ($sizesData['srcsets'] as $path => $width) {
199
            $sizesData['srcsets'][$path] = $this->urlBuilder->filePublicUrl($path) . ' ' . $width . 'w';
200
        }
201
202
        // @TODO: We need to incorporate a fallback image style
203
        return $environment->render(
204
            'ResponsiveImageBundle::img_sizes.html.twig',
205
            [
206
                'image'   => $image,
207
                'sizes'   => implode(', ', $sizesData['sizes']),
208
                'srcsets' => implode(', ', $sizesData['srcsets']),
209
            ]
210
        );
211
    }
212
213
    /**
214
     * @param \Twig_Environment        $environment
215
     * @param ResponsiveImageInterface $image
216
     * @param null                     $styleName
217
     * @param bool                     $generate
218
     *
219
     * @return mixed|string
220
     */
221
    public function generateStyledImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $styleName = null, $generate = false)
0 ignored issues
show
Unused Code introduced by
The parameter $generate 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...
222
    {
223
        // @TODO: Implement generate if missing.
224
225
        return $this->renderImage($environment, $image, $styleName);
226
    }
227
228
    /**
229
     * @param \Twig_Environment        $environment
230
     * @param ResponsiveImageInterface $image
231
     * @param string                   $width
232
     * @param null                     $height
233
     *
234
     * @return mixed|string
235
     */
236 View Code Duplication
    public function cropImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $width = '', $height = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237
    {
238
        $styleName = 'custom_crop_' . $width . '_' . $height;
239
240
        if (!empty($this->imageManager)) {
241
            $this->imageManager->createCustomStyledImage($image, $styleName);
242
        }
243
244
        return $this->renderImage($environment, $image, $styleName);
245
    }
246
247
    /**
248
     * @param \Twig_Environment        $environment
249
     * @param ResponsiveImageInterface $image
250
     * @param string                   $width
251
     * @param string                   $height
252
     *
253
     * @return mixed|string
254
     */
255 View Code Duplication
    public function scaleImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $width = '', $height = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
    {
257
        $styleName = 'custom_scale_' . $width . '_' . $height;
258
259
        if (!empty($this->imageManager)) {
260
            $this->imageManager->createCustomStyledImage($image, $styleName);
261
        }
262
263
        return $this->renderImage($environment, $image, $styleName);
264
    }
265
266
    /**
267
     * @param \Twig_Environment        $environment
268
     * @param ResponsiveImageInterface $image
269
     * @param null                     $styleName
270
     *
271
     * @return mixed|string
272
     */
273
    protected function renderImage(\Twig_Environment $environment, ResponsiveImageInterface $image, $styleName = null)
274
    {
275 View Code Duplication
        if (!empty($styleName)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
276
            $path = $this->styleManager->getStylePath($image, $styleName);
277
        }
278
        else {
279
            $path = $image->getPath();
280
        }
281
282
        $src = $this->urlBuilder->filePublicUrl($path);
283
        // Set the image attributes.
284
        $this->styleManager->setImageAttributes($image, $styleName, $src);
285
286
        return $environment->render(
287
            'ResponsiveImageBundle::img.html.twig',
288
            [
289
                'image' => $image,
290
            ]
291
        );
292
    }
293
294
    /**
295
     * @return string
296
     */
297
    public function getName()
298
    {
299
        return 'responsive_image_extension';
300
    }
301
}