ResaveOptimizedImages::execute()   C
last analyzed

Complexity

Conditions 15
Paths 28

Size

Total Lines 66
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 41
c 1
b 0
f 0
dl 0
loc 66
rs 5.9166
cc 15
nc 28
nop 1

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
/**
3
 * ImageOptimize plugin for Craft CMS
4
 *
5
 * Automatically optimize images after they've been transformed
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\imageoptimize\jobs;
12
13
use Craft;
14
use craft\base\ElementInterface;
0 ignored issues
show
Bug introduced by
The type craft\base\ElementInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use craft\base\Field;
16
use craft\console\Application as ConsoleApplication;
17
use craft\db\Paginator;
18
use craft\elements\Asset;
19
use craft\elements\db\ElementQuery;
20
use craft\helpers\App;
21
use craft\queue\BaseJob;
22
use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField;
23
use nystudio107\imageoptimize\ImageOptimize;
24
use yii\base\Exception;
25
26
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
27
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
28
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
29
 * @since     1.4.8
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
30
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
31
class ResaveOptimizedImages extends BaseJob
32
{
33
    // Constants
34
    // =========================================================================
35
36
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
37
     * @const The number of assets to return in a single paginated query
38
     */
39
    protected const ASSET_QUERY_PAGE_SIZE = 100;
40
41
    // Properties
42
    // =========================================================================
43
44
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
45
     * @var ?array The element criteria that determines which elements should be resaved
46
     */
47
    public ?array $criteria = null;
48
49
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
50
     * @var int|null The id of the field to resave images for, or null for all images
51
     */
52
    public ?int $fieldId = null;
53
54
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
55
     * @var bool Whether image variants should be forced to recreated, even if they already exist on disk
0 ignored issues
show
Coding Style introduced by
Tag value for @var tag indented incorrectly; expected 3 spaces but found 1
Loading history...
56
     * @since 1.6.18
57
     */
58
    public bool $force = false;
59
60
    // Public Methods
61
    // =========================================================================
62
63
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $queue should have a doc-comment as per coding-style.
Loading history...
64
     * @inheritdoc
65
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
66
    public function execute($queue): void
67
    {
68
        // Let's save ourselves some trouble and just clear all the caches for this element class
69
        Craft::$app->getElements()->invalidateCachesForElementType(Asset::class);
70
71
        // Now find the affected element IDs
72
        /** @var ElementQuery $query */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
73
        $query = Asset::find();
74
        if (!empty($this->criteria)) {
75
            Craft::configure($query, $this->criteria);
76
        }
77
        if (Craft::$app instanceof ConsoleApplication) {
78
            echo $this->description . PHP_EOL;
79
        }
80
        // Use craft\db\Paginator to paginate the results so we don't exceed any memory limits
81
        // See batch() and each() discussion here: https://github.com/yiisoft/yii2/issues/8420
82
        // and here: https://github.com/craftcms/cms/issues/7338
83
        $paginator = new Paginator($query, [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
84
            'pageSize' => self::ASSET_QUERY_PAGE_SIZE,
85
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
86
        $currentElement = 0;
87
        $totalElements = $paginator->getTotalResults();
88
        // Iterate through the paginated results
89
        while ($currentElement < $totalElements) {
90
            $elements = $paginator->getPageResults();
91
            if (Craft::$app instanceof ConsoleApplication) {
92
                echo 'Query ' . $paginator->getCurrentPage() . '/' . $paginator->getTotalPages()
93
                    . ' - assets: ' . $paginator->getTotalResults()
94
                    . PHP_EOL;
95
            }
96
            /** @var ElementInterface $element */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
97
            foreach ($elements as $element) {
98
                $currentElement++;
99
                // Find each OptimizedImages field and process it
100
                $layout = $element->getFieldLayout();
101
                if ($layout !== null) {
102
                    $fields = $layout->getCustomFields();
103
                    /** @var Field $field */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
104
                    foreach ($fields as $field) {
105
                        if ($field instanceof OptimizedImagesField && $element instanceof Asset) {
106
                            if ($this->fieldId === null || (int)$field->id === (int)$this->fieldId) {
107
                                if (Craft::$app instanceof ConsoleApplication) {
108
                                    echo $currentElement . '/' . $totalElements
109
                                        . ' - processing asset: ' . $element->title
110
                                        . ' from field: ' . $field->name . PHP_EOL;
111
                                }
112
                                try {
113
                                    ImageOptimize::$plugin->optimizedImages->updateOptimizedImageFieldData($field, $element, $this->force);
114
                                } catch (Exception $e) {
115
                                    Craft::error($e->getMessage(), __METHOD__);
116
                                    if (Craft::$app instanceof ConsoleApplication) {
117
                                        echo '[error]: '
118
                                            . $e->getMessage()
119
                                            . ' while processing '
120
                                            . $currentElement . '/' . $totalElements
121
                                            . ' - processing asset: ' . $element->title
122
                                            . ' from field: ' . $field->name . PHP_EOL;
123
                                    }
124
                                }
125
                            }
126
                        }
127
                    }
128
                }
129
                $this->setProgress($queue, $currentElement / $totalElements);
130
            }
131
            $paginator->currentPage++;
132
        }
133
    }
134
135
    // Protected Methods
136
    // =========================================================================
137
138
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
139
     * @inheritdoc
140
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
141
    protected function defaultDescription(): ?string
142
    {
143
        return Craft::t('app', 'Resaving {class} elements', [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
144
            'class' => App::humanizeClass(Asset::class),
145
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
146
    }
147
}
148