Passed
Push — develop ( 7625f3...7e2973 )
by Andrew
06:39 queued 19s
created

Recipe::getInputHtml()   B

Complexity

Conditions 8
Paths 30

Size

Total Lines 57
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 39
c 2
b 0
f 0
nc 30
nop 2
dl 0
loc 57
rs 8.0515

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
 * Recipe plugin for Craft CMS 3.x
4
 *
5
 * A comprehensive recipe FieldType for Craft CMS that includes metric/imperial
6
 * conversion, portion calculation, and JSON-LD microdata support
7
 *
8
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
9
 * @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...
10
 */
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...
11
12
namespace nystudio107\recipe\fields;
13
14
use nystudio107\recipe\assetbundles\recipefield\RecipeFieldAsset;
15
use nystudio107\recipe\models\Recipe as RecipeModel;
16
17
use Craft;
18
use craft\base\ElementInterface;
19
use craft\base\Field;
20
use craft\elements\Asset;
21
use craft\helpers\Html;
22
use craft\helpers\Json;
23
24
use Twig\Error\LoaderError;
25
use Twig\Error\RuntimeError;
26
use Twig\Error\SyntaxError;
27
use yii\base\Exception;
28
use yii\base\InvalidConfigException;
29
use yii\db\Schema;
30
31
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
32
 * @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...
33
 * @package   Recipe
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
34
 * @since     1.0.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...
35
 */
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...
36
class Recipe extends Field
37
{
38
    // Public Properties
39
    // =========================================================================
40
41
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
42
     * @var array
43
     */
44
    public $assetSources = [];
45
46
    // Static Methods
47
    // =========================================================================
48
49
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
50
     * @inheritdoc
51
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
52
    public static function displayName(): string
53
    {
54
        return Craft::t('recipe', 'Recipe');
55
    }
56
57
    // Public Methods
58
    // =========================================================================
59
60
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
61
     * @inheritdoc
62
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
63
    public function rules()
64
    {
65
        $rules = parent::rules();
66
        $rules = array_merge($rules, [
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...
67
        ]);
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...
68
69
        return $rules;
70
    }
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @inheritdoc
74
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
75
    public function getContentColumnType(): string
76
    {
77
        return Schema::TYPE_TEXT;
78
    }
79
80
    /**
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...
81
     * @inheritdoc
82
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
83
    public function normalizeValue($value, ElementInterface $element = null)
84
    {
85
        if (is_string($value) && !empty($value)) {
86
            $value = Json::decode($value);
87
        }
88
        $model = new RecipeModel($value);
89
90
        return $model;
91
    }
92
93
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
94
     * @inheritdoc
95
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
96
    public function getSettingsHtml()
97
    {
98
        // Render the settings template
99
        return Craft::$app->getView()->renderTemplate(
100
            'recipe'
101
            .DIRECTORY_SEPARATOR
102
            .'_components'
103
            .DIRECTORY_SEPARATOR
104
            .'fields'
105
            .DIRECTORY_SEPARATOR
106
            .'Recipe_settings',
107
            [
108
                'field' => $this,
109
                'assetSources' => $this->getSourceOptions(),
110
            ]
111
        );
112
    }
113
114
    /**
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...
115
     * @inheritdoc
116
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
117
    public function getInputHtml($value, ElementInterface $element = null): string
118
    {
119
        // Register our asset bundle
120
        try {
121
            Craft::$app->getView()->registerAssetBundle(RecipeFieldAsset::class);
122
        } catch (InvalidConfigException $e) {
123
            Craft::error($e->getMessage(), __METHOD__);
124
        }
125
126
        // Get our id and namespace
127
        $id = Craft::$app->getView()->formatInputId($this->handle);
0 ignored issues
show
Bug introduced by
It seems like $this->handle can also be of type null; however, parameter $inputName of craft\web\View::formatInputId() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

127
        $id = Craft::$app->getView()->formatInputId(/** @scrutinizer ignore-type */ $this->handle);
Loading history...
128
        $nameSpacedId = Craft::$app->getView()->namespaceInputId($id);
129
130
        // Variables to pass down to our field JavaScript to let it namespace properly
131
        $jsonVars = [
132
            'id' => $id,
133
            'name' => $this->handle,
134
            'namespace' => $nameSpacedId,
135
            'prefix' => Craft::$app->getView()->namespaceInputId(''),
136
        ];
137
        $jsonVars = Json::encode($jsonVars);
138
        Craft::$app->getView()->registerJs("$('#{$nameSpacedId}-field').RecipeRecipe(".$jsonVars.");");
139
140
        // Set asset elements
141
        $elements = [];
142
        if ($value->imageId) {
143
            if (is_array($value->imageId)) {
144
                $value->imageId = $value->imageId[0];
145
            }
146
            $elements = [Craft::$app->getAssets()->getAssetById($value->imageId)];
147
        }
148
149
        // Render the input template
150
        try {
151
            return Craft::$app->getView()->renderTemplate(
152
                'recipe/_components/fields/Recipe_input',
153
                [
154
                    'name' => $this->handle,
155
                    'value' => $value,
156
                    'field' => $this,
157
                    'id' => $id,
158
                    'nameSpacedId' => $nameSpacedId,
159
                    'prefix' => Craft::$app->getView()->namespaceInputId(''),
160
                    'assetsSourceExists' => count(Craft::$app->getAssets()->findFolders()),
161
                    'elements' => $elements,
162
                    'elementType' => Asset::class,
163
                    'assetSources' => $this->assetSources,
164
                ]
165
            );
166
        } catch (LoaderError $e) {
167
            Craft::error($e->getMessage(), __METHOD__);
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return string. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
168
        } catch (RuntimeError $e) {
169
            Craft::error($e->getMessage(), __METHOD__);
170
        } catch (SyntaxError $e) {
171
            Craft::error($e->getMessage(), __METHOD__);
172
        } catch (Exception $e) {
173
            Craft::error($e->getMessage(), __METHOD__);
174
        }
175
    }
176
177
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
178
     * @inheritdoc
179
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
180
    public function getSourceOptions(): array
181
    {
182
        $sourceOptions = [];
183
184
        foreach (Asset::sources('settings') as $key => $volume) {
185
            if (!isset($volume['heading'])) {
186
                $sourceOptions[] = [
187
                    'label' => Html::encode($volume['label']),
188
                    'value' => $volume['key']
189
                ];
190
            }
191
        }
192
193
        return $sourceOptions;
194
    }
195
}
196