Passed
Push — develop-v4 ( 01c404...563ce7 )
by Andrew
18:55 queued 08:57
created

MetaScriptContainer::includeMetaData()   B

Complexity

Conditions 10
Paths 12

Size

Total Lines 70
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 70
ccs 0
cts 52
cp 0
rs 7.6666
c 0
b 0
f 0
cc 10
nc 12
nop 1
crap 110

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
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\models;
13
14
use nystudio107\seomatic\Seomatic;
15
use nystudio107\seomatic\base\NonceContainer;
16
use nystudio107\seomatic\helpers\ImageTransform as ImageTransformHelper;
17
18
use Craft;
19
20
use yii\caching\TagDependency;
21
use yii\web\View;
22
23
/**
24
 * @author    nystudio107
25
 * @package   Seomatic
26
 * @since     3.0.0
27
 */
28
class MetaScriptContainer extends NonceContainer
29
{
30
    // Constants
31
    // =========================================================================
32
33
    const CONTAINER_TYPE = 'MetaScriptContainer';
34
35
    // Public Properties
36
    // =========================================================================
37
38
    /**
39
     * The data in this container
40
     *
41
     * @var MetaScript[] $data
42
     */
43
    public $data = [];
44
45
    /**
46
     * @var int
47
     */
48
    public $position = View::POS_HEAD;
49
50
    // Public Methods
51
    // =========================================================================
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public function includeMetaData($dependency)
57
    {
58
        Craft::beginProfile('MetaScriptContainer::includeMetaData', __METHOD__);
59
        $uniqueKey = $this->handle.$dependency->tags[3].$this->dataLayerHash();
60
        $cache = Craft::$app->getCache();
61
        if ($this->clearCache) {
62
            TagDependency::invalidate($cache, $dependency->tags[3]);
63
        }
64
        $tagData = $cache->getOrSet(
65
            self::CONTAINER_TYPE.$uniqueKey,
66
            function () use ($uniqueKey) {
67
                Craft::info(
68
                    self::CONTAINER_TYPE.' cache miss: '.$uniqueKey,
69
                    __METHOD__
70
                );
71
                $tagData = [];
72
                if ($this->prepForInclusion()) {
73
                    /** @var $metaScriptModel MetaScript */
74
                    foreach ($this->data as $metaScriptModel) {
75
                        if ($metaScriptModel->include) {
76
                            $js = $metaScriptModel->render();
77
                            if (!empty($js)) {
78
                                $scenario = $this->scenario;
79
                                $metaScriptModel->setScenario('render');
80
                                $options = $metaScriptModel->tagAttributes();
81
                                $metaScriptModel->setScenario($scenario);
82
                                $tagData[] = [
83
                                    'js' => $js,
84
                                    'position' => $metaScriptModel->position ?? $this->position,
85
                                    'nonce' => $metaScriptModel->nonce ?? null,
86
                                    'tagAttrs' => $options,
87
                                ];
88
                                // If `devMode` is enabled, validate the Meta Script and output any model errors
89
                                if (Seomatic::$devMode) {
90
                                    $metaScriptModel->debugMetaItem(
91
                                        'Script attribute: '
92
                                    );
93
                                }
94
                            }
95
                        }
96
                    }
97
                }
98
99
                return $tagData;
100
            },
101
            Seomatic::$cacheDuration,
102
            $dependency
103
        );
104
        // Invalidate the cache we just created if there were pending image transforms in it
105
        if (ImageTransformHelper::$pendingImageTransforms) {
106
            TagDependency::invalidate($cache, $dependency->tags[3]);
107
        }
108
        // Register the tags
109
        foreach ($tagData as $config) {
110
            // Register the tags
111
            $attrs = $config['tagAttrs'] ?? [];
112
            if (!empty($config['nonce'])) {
113
                /** @noinspection SlowArrayOperationsInLoopInspection */
114
                $attrs = array_merge($attrs, [
115
                    'nonce' => $config['nonce'],
116
                ]);
117
            }
118
            Seomatic::$view->registerScript(
0 ignored issues
show
Bug introduced by
The method registerScript() does not exist on null. ( Ignorable by Annotation )

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

118
            Seomatic::$view->/** @scrutinizer ignore-call */ 
119
                             registerScript(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
119
                $config['js'],
120
                $config['position'],
121
                $attrs
122
            );
123
        }
124
125
        Craft::endProfile('MetaScriptContainer::includeMetaData', __METHOD__);
126
    }
127
128
    /**
129
     * @inheritdoc
130
     */
131
    public function render(array $params = []): string
132
    {
133
        $html = parent::render($params);
134
        if ($params['renderScriptTags']) {
135
            $html =
136
                '<script>'
137
                .$html
138
                .'</script>'
139
            ;
140
        }
141
142
        return $html;
143
    }
144
145
    /**
146
     * @inheritdoc
147
     */
148
    public function normalizeContainerData()
149
    {
150
        parent::normalizeContainerData();
151
152
        foreach ($this->data as $key => $config) {
153
            $config['key'] = $key;
154
            $this->data[$key] = MetaScript::create($config);
0 ignored issues
show
Bug introduced by
$config of type nystudio107\seomatic\models\MetaScript is incompatible with the type array expected by parameter $config of nystudio107\seomatic\models\MetaScript::create(). ( Ignorable by Annotation )

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

154
            $this->data[$key] = MetaScript::create(/** @scrutinizer ignore-type */ $config);
Loading history...
155
        }
156
    }
157
158
    // Protected Methods
159
    // =========================================================================
160
161
    protected function dataLayerHash(): string
162
    {
163
        $data = '';
164
        foreach ($this->data as $metaScriptModel) {
165
            $data .= serialize($metaScriptModel->dataLayer);
166
        }
167
168
        return md5($data);
169
    }
170
}
171