Completed
Push — master ( 0babc9...e6e40c )
by
unknown
16:29
created

ImageViewHelper::renderStatic()   D

Complexity

Conditions 17
Paths 160

Size

Total Lines 55
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 37
c 1
b 0
f 0
nc 160
nop 3
dl 0
loc 55
rs 4.7166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace TYPO3\CMS\Fluid\ViewHelpers\Uri;
3
4
/*                                                                        *
5
 * This script is part of the TYPO3 project - inspiring people to share!  *
6
 *                                                                        *
7
 * TYPO3 is free software; you can redistribute it and/or modify it under *
8
 * the terms of the GNU General Public License version 2 as published by  *
9
 * the Free Software Foundation.                                          *
10
 *                                                                        *
11
 * This script is distributed in the hope that it will be useful, but     *
12
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
13
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General      *
14
 * Public License for more details.                                       *
15
 *                                                                        */
16
17
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
18
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Extbase\Object\ObjectManager;
21
use TYPO3\CMS\Extbase\Service\ImageService;
22
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
23
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
24
use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
25
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
26
27
/**
28
 * Resizes a given image (if required) and returns its relative path.
29
 *
30
 * External URLs are not processed and just returned as is.
31
 *
32
 * Examples
33
 * ========
34
 *
35
 * Default
36
 * -------
37
 *
38
 * ::
39
 *
40
 *    <f:uri.image src="EXT:myext/Resources/Public/typo3_logo.png" />
41
 *
42
 * Results in the following output within TYPO3 frontend:
43
 *
44
 * ``typo3conf/ext/myext/Resources/Public/typo3_logo.png``
45
 *
46
 * and the following output inside TYPO3 backend:
47
 *
48
 * ``../typo3conf/ext/myext/Resources/Public/typo3_logo.png``
49
 *
50
 * Image Object
51
 * ------------
52
 *
53
 * ::
54
 *
55
 *    <f:uri.image image="{imageObject}" />
56
 *
57
 * Results in the following output within TYPO3 frontend:
58
 *
59
 * ``fileadmin/images/image.png``
60
 *
61
 * and the following output inside TYPO3 backend:
62
 *
63
 * ``fileadmin/images/image.png``
64
 *
65
 * Inline notation
66
 * ---------------
67
 *
68
 * ::
69
 *
70
 *    {f:uri.image(src: 'EXT:myext/Resources/Public/typo3_logo.png', minWidth: 30, maxWidth: 40)}
71
 *
72
 * ``typo3temp/assets/images/[b4c0e7ed5c].png``
73
 *
74
 * Depending on your TYPO3s encryption key.
75
 *
76
 * Non existing image
77
 * ------------------
78
 *
79
 * ::
80
 *
81
 *    <f:uri.image src="NonExistingImage.png" />
82
 *
83
 * ``Could not get image resource for "NonExistingImage.png".``
84
 */
85
class ImageViewHelper extends AbstractViewHelper
86
{
87
    use CompileWithRenderStatic;
88
89
    /**
90
     * Initialize arguments
91
     */
92
    public function initializeArguments()
93
    {
94
        $this->registerArgument('src', 'string', 'src', false, '');
95
        $this->registerArgument('treatIdAsReference', 'bool', 'given src argument is a sys_file_reference record', false, false);
96
        $this->registerArgument('image', 'object', 'image');
97
        $this->registerArgument('crop', 'string|bool', 'overrule cropping of image (setting to FALSE disables the cropping set in FileReference)');
98
        $this->registerArgument('cropVariant', 'string', 'select a cropping variant, in case multiple croppings have been specified or stored in FileReference', false, 'default');
99
        $this->registerArgument('fileExtension', 'string', 'Custom file extension to use');
100
101
        $this->registerArgument('width', 'string', 'width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
102
        $this->registerArgument('height', 'string', 'height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.');
103
        $this->registerArgument('minWidth', 'int', 'minimum width of the image');
104
        $this->registerArgument('minHeight', 'int', 'minimum height of the image');
105
        $this->registerArgument('maxWidth', 'int', 'maximum width of the image');
106
        $this->registerArgument('maxHeight', 'int', 'maximum height of the image');
107
        $this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false);
108
    }
109
110
    /**
111
     * Resizes the image (if required) and returns its path. If the image was not resized, the path will be equal to $src
112
     *
113
     * @param array $arguments
114
     * @param \Closure $renderChildrenClosure
115
     * @param RenderingContextInterface $renderingContext
116
     * @return string
117
     * @throws Exception
118
     */
119
    public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
120
    {
121
        $src = (string)$arguments['src'];
122
        $image = $arguments['image'];
123
        $treatIdAsReference = (bool)$arguments['treatIdAsReference'];
124
        $cropString = $arguments['crop'];
125
        $absolute = $arguments['absolute'];
126
127
        if (($src === '' && $image === null) || ($src !== '' && $image !== null)) {
128
            throw new Exception('You must either specify a string src or a File object.', 1460976233);
129
        }
130
131
        // A URL was given as src, this is kept as is
132
        if ($src !== '' && preg_match('/^(https?:)?\/\//', $src)) {
133
            return $src;
134
        }
135
136
        try {
137
            $imageService = self::getImageService();
138
            $image = $imageService->getImage($src, $image, $treatIdAsReference);
139
140
            if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) {
141
                $cropString = $image->getProperty('crop');
142
            }
143
144
            $cropVariantCollection = CropVariantCollection::create((string)$cropString);
145
            $cropVariant = $arguments['cropVariant'] ?: 'default';
146
            $cropArea = $cropVariantCollection->getCropArea($cropVariant);
147
            $processingInstructions = [
148
                'width' => $arguments['width'],
149
                'height' => $arguments['height'],
150
                'minWidth' => $arguments['minWidth'],
151
                'minHeight' => $arguments['minHeight'],
152
                'maxWidth' => $arguments['maxWidth'],
153
                'maxHeight' => $arguments['maxHeight'],
154
                'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image),
155
            ];
156
            if (!empty($arguments['fileExtension'])) {
157
                $processingInstructions['fileExtension'] = $arguments['fileExtension'];
158
            }
159
160
            $processedImage = $imageService->applyProcessingInstructions($image, $processingInstructions);
161
            return $imageService->getImageUri($processedImage, $absolute);
162
        } catch (ResourceDoesNotExistException $e) {
163
            // thrown if file does not exist
164
            throw new Exception($e->getMessage(), 1509741907, $e);
165
        } catch (\UnexpectedValueException $e) {
166
            // thrown if a file has been replaced with a folder
167
            throw new Exception($e->getMessage(), 1509741908, $e);
168
        } catch (\RuntimeException $e) {
169
            // RuntimeException thrown if a file is outside of a storage
170
            throw new Exception($e->getMessage(), 1509741909, $e);
171
        } catch (\InvalidArgumentException $e) {
172
            // thrown if file storage does not exist
173
            throw new Exception($e->getMessage(), 1509741910, $e);
174
        }
175
    }
176
177
    /**
178
     * Return an instance of ImageService using object manager
179
     *
180
     * @return ImageService
181
     */
182
    protected static function getImageService()
183
    {
184
        /** @var ObjectManager $objectManager */
185
        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
186
        return $objectManager->get(ImageService::class);
187
    }
188
}
189