Test Failed
Push — v4 ( e72076...9a8180 )
by Andrew
35:31 queued 15:18
created

ShortLink::getElementValidationRules()   A

Complexity

Conditions 5
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 14
ccs 0
cts 0
cp 0
rs 9.6111
cc 5
nc 1
nop 0
crap 30
1
<?php
2
/**
3
 * Retour plugin for Craft CMS
4
 *
5
 * @link      https://nystudio107.com/
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
6
 * @copyright Copyright (c) 2022 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
7
 * @license   https://nystudio107.com/license
0 ignored issues
show
Coding Style introduced by
@license tag must contain a URL and a license name
Loading history...
8
 */
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...
9
10
namespace nystudio107\retour\fields;
11
12
use Craft;
13
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...
14
use craft\base\Field;
15
use craft\base\PreviewableFieldInterface;
16
use craft\helpers\ElementHelper;
17
use craft\helpers\Json;
18
use craft\helpers\UrlHelper;
19
use nystudio107\retour\Retour as RetourPlugin;
20
use yii\helpers\StringHelper;
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @author    nystudio107
0 ignored issues
show
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...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
24
 * @package   Retour
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @since     4.1.0
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...
26
 *
27
 * @property-read string $contentColumnType
28
 */
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...
29
class ShortLink extends Field implements PreviewableFieldInterface
30
{
31
    protected static bool $allowShortLinkUpdates = true;
32
    public string $redirectSrcMatch = 'pathonly';
33
    public int $redirectHttpCode = 301;
34
35
    // Static Methods
36
    // =========================================================================
37
38
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
39
     * @inheritdoc
40
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
41
    public static function displayName(): string
42
    {
43
        return Craft::t('retour', 'Short Link');
44
    }
45
46
    /**
47
     * Prevent element updates from updating the short link redirects.
48
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
49
    public static function preventShortLinkUpdates(): void
50
    {
51
        self::$allowShortLinkUpdates = false;
52
    }
53
54
    /**
55
     * Allow element updates to update the short link redirects.
56
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
57
    public static function allowShortLinkUpdates(): void
58
    {
59
        self::$allowShortLinkUpdates = true;
60
    }
61
62
    // Public Methods
63
    // =========================================================================
64
65
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $value should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
66
     * @inheritdoc
67
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
68
    public function getInputHtml($value, ElementInterface $element = null): string
69
    {
70
        // Render the input template
71
        return Craft::$app->getView()->renderTemplate(
72
            'retour/_components/fields/ShortLink_input',
73
            [
74
                'name' => $this->handle,
75
                'value' => $value,
76
                'field' => $this,
77
            ]
78
        );
79
    }
80
81
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
82
     * @inheritdoc
83
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
84
    public function getSettingsHtml(): string
85
    {
86
        return Craft::$app->getView()->renderTemplate('retour/_components/fields/ShortLink_settings',
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...
87
            [
88
                'field' => $this,
89
            ]);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 12.
Loading history...
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...
90
    }
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $isNew should have a doc-comment as per coding-style.
Loading history...
93
     * @inheritdoc
94
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
95
    public function afterElementSave(ElementInterface $element, bool $isNew): void
96
    {
97
        if (!self::$allowShortLinkUpdates || $element->getIsDraft() || !$element->getSite()->hasUrls) {
98
            return;
99
        }
100
101
        $value = $element->getFieldValue($this->handle);
102
        // Return for propagating elements
103
        if ($this->redirectSrcMatch === 'pathonly') {
104
            $parentElement = ElementHelper::rootElement($element);
0 ignored issues
show
Deprecated Code introduced by
The function craft\helpers\ElementHelper::rootElement() has been deprecated: in 4.12.0. Use [[ElementInterface::getRootOwner()]] instead. ( Ignorable by Annotation )

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

104
            $parentElement = /** @scrutinizer ignore-deprecated */ ElementHelper::rootElement($element);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
105
            if ($this->translationMethod === Field::TRANSLATION_METHOD_NONE && ($element->propagating || $parentElement->propagating)) {
106
                return;
107
            }
108
        } elseif (!empty($value) && !StringHelper::startsWith($value, 'http')) {
109
            $value = UrlHelper::siteUrl($value, null, null, $element->siteId);
110
        }
111
112
        $parentElement = ElementHelper::rootElement($element);
0 ignored issues
show
Deprecated Code introduced by
The function craft\helpers\ElementHelper::rootElement() has been deprecated: in 4.12.0. Use [[ElementInterface::getRootOwner()]] instead. ( Ignorable by Annotation )

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

112
        $parentElement = /** @scrutinizer ignore-deprecated */ ElementHelper::rootElement($element);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
113
        RetourPlugin::$plugin->redirects->removeElementRedirect($parentElement, false);
0 ignored issues
show
Bug introduced by
The method removeElementRedirect() 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

113
        RetourPlugin::$plugin->redirects->/** @scrutinizer ignore-call */ 
114
                                          removeElementRedirect($parentElement, false);

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...
114
115
        if (!empty($value)) {
116
            $redirectSrcMatch = $this->redirectSrcMatch;
117
118
            if ($this->translationMethod !== Field::TRANSLATION_METHOD_NONE) {
119
                if (!UrlHelper::isAbsoluteUrl($value)) {
120
                    $value = UrlHelper::siteUrl($value, null, null, $parentElement->siteId);
121
                    $redirectSrcMatch = 'fullurl';
122
                }
123
            }
124
125
            RetourPlugin::$plugin->redirects->enableElementRedirect($parentElement, $value, $redirectSrcMatch, $this->redirectHttpCode);
126
        }
127
128
        parent::afterElementSave($element, $isNew);
129
    }
130
131
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
132
     * @inheritdoc
133
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
134
    public function afterElementDelete(ElementInterface $element): void
135
    {
136
        if (!$element->getIsCanonical()) {
137
            return;
138
        }
139
140
        RetourPlugin::$plugin->redirects->removeElementRedirect($element, true, true);
141
        parent::afterElementDelete($element);
142
    }
143
144
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $value should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
145
     * @inheritdoc
146
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
147
    public function getTableAttributeHtml($value, ElementInterface $element): string
148
    {
149
        $decoded = Json::decodeIfJson($value);
150
        if (is_array($decoded)) {
151
            $value = $decoded['legacyUrl'] ?? '';
152
        }
153
        // Render the preview template
154
        return Craft::$app->getView()->renderTemplate(
155
            'retour/_components/fields/ShortLink_preview',
156
            [
157
                'name' => $this->handle,
158
                'value' => $value,
159
                'field' => $this,
160
            ]
161
        );
162
    }
163
164
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
165
     * @inheritdoc
166
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
167
    public function getElementValidationRules(): array
168
    {
169
        return [
170
            [
171
                function(ElementInterface $element) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
172
                    $value = $element->getFieldValue($this->handle);
173
                    $redirect = RetourPlugin::$plugin->getRedirects()->getRedirectByRedirectSrcUrl($value);
0 ignored issues
show
Bug introduced by
The method getRedirects() 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

173
                    $redirect = RetourPlugin::$plugin->/** @scrutinizer ignore-call */ getRedirects()->getRedirectByRedirectSrcUrl($value);

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...
174
                    // Handle drafts
175
                    $element = $element->getCanonical();
176
                    if ($redirect && isset($redirect['associatedElementId'])) {
177
                        if ($redirect['associatedElementId'] == 0) {
178
                            $element->addError($this->handle, Craft::t('retour', 'A Retour redirect with this Legacy URL already exists.'));
179
                        } elseif ($redirect['associatedElementId'] !== $element->id) {
180
                            $element->addError($this->handle, Craft::t('retour', 'A Short Link with this URL already exists.'));
181
                        }
182
                    }
183
                },
184
            ],
185
        ];
186
    }
187
}
188