Completed
Push — 7.1 ( c93e68...5ccb92 )
by
unknown
29:26
created

AliasGenerator::getVariation()   B

Complexity

Conditions 8
Paths 11

Size

Total Lines 59
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 38
nc 11
nop 4
dl 0
loc 59
rs 7.132
c 0
b 0
f 0

How to fix   Long Method   

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
3
/**
4
 * File containing the ImagineAliasGenerator class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Bundle\EzPublishCoreBundle\Imagine;
10
11
use eZ\Publish\API\Repository\Exceptions\InvalidVariationException;
12
use eZ\Publish\Core\MVC\Exception\SourceImageNotFoundException;
13
use eZ\Publish\API\Repository\Values\Content\Field;
14
use eZ\Publish\API\Repository\Values\Content\VersionInfo;
15
use eZ\Publish\SPI\Variation\Values\ImageVariation;
16
use eZ\Publish\SPI\Variation\VariationHandler;
17
use eZ\Publish\SPI\FieldType\Value;
18
use eZ\Publish\Core\FieldType\Image\Value as ImageValue;
19
use Imagine\Exception\RuntimeException;
20
use Liip\ImagineBundle\Binary\BinaryInterface;
21
use Liip\ImagineBundle\Binary\Loader\LoaderInterface;
22
use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
23
use Liip\ImagineBundle\Exception\Imagine\Cache\Resolver\NotResolvableException;
24
use Liip\ImagineBundle\Imagine\Cache\Resolver\ResolverInterface;
25
use Liip\ImagineBundle\Imagine\Filter\FilterConfiguration;
26
use Liip\ImagineBundle\Imagine\Filter\FilterManager;
27
use Psr\Log\LoggerInterface;
28
use InvalidArgumentException;
29
use Psr\Log\NullLogger;
30
use SplFileInfo;
31
32
/**
33
 * Image alias generator using LiipImagineBundle API.
34
 * Doesn't use DataManager/CacheManager as it's directly bound to IO Repository for convenience.
35
 */
36
class AliasGenerator implements VariationHandler
37
{
38
    const ALIAS_ORIGINAL = 'original';
39
40
    /**
41
     * @var \Psr\Log\LoggerInterface
42
     */
43
    private $logger;
44
45
    /**
46
     * Loader used to retrieve the original image.
47
     * DataManager is not used to remain independent from ImagineBundle configuration.
48
     *
49
     * @var \Liip\ImagineBundle\Binary\Loader\LoaderInterface
50
     */
51
    private $dataLoader;
52
53
    /**
54
     * @var \Liip\ImagineBundle\Imagine\Filter\FilterManager
55
     */
56
    private $filterManager;
57
58
    /**
59
     * @var FilterConfiguration
60
     */
61
    private $filterConfiguration;
62
63
    /**
64
     * @var \Liip\ImagineBundle\Imagine\Cache\Resolver\ResolverInterface
65
     */
66
    private $ioResolver;
67
68
    public function __construct(
69
        LoaderInterface $dataLoader,
70
        FilterManager $filterManager,
71
        ResolverInterface $ioResolver,
72
        FilterConfiguration $filterConfiguration,
73
        LoggerInterface $logger = null
74
    ) {
75
        $this->dataLoader = $dataLoader;
76
        $this->filterManager = $filterManager;
77
        $this->ioResolver = $ioResolver;
78
        $this->filterConfiguration = $filterConfiguration;
79
        $this->logger = null !== $logger ? $logger : new NullLogger();
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     *
85
     * @throws \InvalidArgumentException If field value is not an instance of \eZ\Publish\Core\FieldType\Image\Value.
86
     * @throws \eZ\Publish\Core\MVC\Exception\SourceImageNotFoundException If source image cannot be found.
87
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidVariationException If a problem occurs with generated variation.
88
     */
89
    public function getVariation(Field $field, VersionInfo $versionInfo, $variationName, array $parameters = array())
90
    {
91
        /** @var \eZ\Publish\Core\FieldType\Image\Value $imageValue */
92
        $imageValue = $field->value;
93
        $fieldId = $field->id;
94
        $fieldDefIdentifier = $field->fieldDefIdentifier;
95
        if (!$this->supportsValue($imageValue)) {
96
            throw new InvalidArgumentException("Value for field #$fieldId ($fieldDefIdentifier) cannot be used for image alias generation.");
97
        }
98
99
        $originalPath = $imageValue->id;
100
101
        $variationWidth = $variationHeight = null;
102
        // Create the image alias only if it does not already exist.
103
        if ($variationName !== IORepositoryResolver::VARIATION_ORIGINAL && !$this->ioResolver->isStored($originalPath, $variationName)) {
104
            try {
105
                $originalBinary = $this->dataLoader->find($originalPath);
106
            } catch (NotLoadableException $e) {
107
                throw new SourceImageNotFoundException($originalPath, 0, $e);
108
            }
109
110
            $this->logger->debug("Generating '$variationName' variation on $originalPath, field #$fieldId ($fieldDefIdentifier)");
111
112
            $this->ioResolver->store(
113
                $this->applyFilter($originalBinary, $variationName),
0 ignored issues
show
Bug introduced by
It seems like $originalBinary defined by $this->dataLoader->find($originalPath) on line 105 can also be of type string; however, eZ\Bundle\EzPublishCoreB...enerator::applyFilter() does only seem to accept object<Liip\ImagineBundle\Binary\BinaryInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
114
                $originalPath,
115
                $variationName
116
            );
117
        } else {
118
            if ($variationName === IORepositoryResolver::VARIATION_ORIGINAL) {
119
                $variationWidth = $imageValue->width;
120
                $variationHeight = $imageValue->height;
121
            }
122
            $this->logger->debug("'$variationName' variation on $originalPath is already generated. Loading from cache.");
123
        }
124
125
        try {
126
            $aliasInfo = new SplFileInfo(
127
                $this->ioResolver->resolve($originalPath, $variationName)
128
            );
129
        } catch (NotResolvableException $e) {
130
            // If for some reason image alias cannot be resolved, throw the appropriate exception.
131
            throw new InvalidVariationException($variationName, 'image', 0, $e);
132
        } catch (RuntimeException $e) {
133
            throw new InvalidVariationException($variationName, 'image', 0, $e);
134
        }
135
136
        return new ImageVariation(
137
            [
138
                'name' => $variationName,
139
                'fileName' => $aliasInfo->getFilename(),
140
                'dirPath' => $aliasInfo->getPath(),
141
                'uri' => $aliasInfo->getPathname(),
142
                'imageId' => $imageValue->imageId,
143
                'width' => $variationWidth,
144
                'height' => $variationHeight,
145
            ]
146
        );
147
    }
148
149
    /**
150
     * Applies $variationName filters on $image.
151
     *
152
     * Both variations configured in eZ (SiteAccess context) and LiipImagineBundle are used.
153
     * An eZ variation may have a "reference".
154
     * In that case, reference's filters are applied first, recursively (a reference may also have another reference).
155
     * Reference must be a valid variation name, configured in eZ or in LiipImagineBundle.
156
     *
157
     * @param BinaryInterface $image
158
     * @param string $variationName
159
     *
160
     * @return \Liip\ImagineBundle\Binary\BinaryInterface
161
     */
162
    private function applyFilter(BinaryInterface $image, $variationName)
163
    {
164
        $filterConfig = $this->filterConfiguration->get($variationName);
165
        // If the variation has a reference, we recursively call this method to apply reference's filters.
166
        if (isset($filterConfig['reference']) && $filterConfig['reference'] !== IORepositoryResolver::VARIATION_ORIGINAL) {
167
            $image = $this->applyFilter($image, $filterConfig['reference']);
168
        }
169
170
        return $this->filterManager->applyFilter($image, $variationName);
171
    }
172
173
    public function supportsValue(Value $value)
174
    {
175
        return $value instanceof ImageValue;
176
    }
177
}
178