NutritionApiController::actionGenerate()   B
last analyzed

Complexity

Conditions 11
Paths 18

Size

Total Lines 80
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
cc 11
eloc 42
c 8
b 0
f 0
nc 18
nop 0
dl 0
loc 80
rs 7.3166

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
 * 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 @license tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
11
12
namespace nystudio107\recipe\console\controllers;
13
14
use Craft;
15
use craft\console\Controller;
16
use craft\elements\Entry;
17
use craft\helpers\Console;
18
use nystudio107\recipe\models\Settings;
19
use nystudio107\recipe\Recipe;
20
use yii\console\ExitCode;
21
use yii\helpers\BaseConsole;
22
23
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
24
 * @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...
25
 * @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...
26
 * @since     1.3.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...
27
 */
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...
28
class NutritionApiController extends Controller
29
{
30
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
31
     * @var ?string The handle of the section.
32
     */
33
    public ?string $section = null;
34
35
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
36
     * @var ?string The handle of the recipe field.
37
     */
38
    public ?string $field = null;
39
40
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $actionID should have a doc-comment as per coding-style.
Loading history...
41
     * @inheritdoc
42
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
43
    public function options($actionID): array
44
    {
45
        $options = parent::options($actionID);
46
        $options[] = 'section';
47
        $options[] = 'field';
48
49
        return $options;
50
    }
51
52
    /**
53
     * Generates nutritional information for all entries in a section provided using --section.
54
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
55
    public function actionGenerate(): int
56
    {
57
        /** @var Settings $settings */
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...
58
        $settings = Recipe::$plugin->getSettings();
0 ignored issues
show
Bug introduced by
The method getSettings() 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

58
        /** @scrutinizer ignore-call */ 
59
        $settings = Recipe::$plugin->getSettings();

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...
59
        if (!$settings->hasApiCredentials()) {
60
            $this->stderr(Craft::t('recipe', 'API credentials do not exist in plugin settings.') . PHP_EOL, BaseConsole::FG_RED);
61
62
            return ExitCode::OK;
63
        }
64
65
        if ($this->section === null) {
66
            $this->stderr(Craft::t('recipe', 'A section handle must be provided using --section.') . PHP_EOL, BaseConsole::FG_RED);
67
68
            return ExitCode::OK;
69
        }
70
71
        if ($this->field === null) {
72
            $this->stderr(Craft::t('recipe', 'A field handle must be provided using --field.') . PHP_EOL, BaseConsole::FG_RED);
73
74
            return ExitCode::OK;
75
        }
76
77
        $entries = Entry::find()->section($this->section)->all();
78
79
        if (empty($entries)) {
80
            $this->stderr(Craft::t('recipe', 'No entries found in the section with handle `{handle}`.', ['handle' => $this->section]) . PHP_EOL, BaseConsole::FG_RED);
81
82
            return ExitCode::OK;
83
        }
84
85
        $total = count($entries);
86
        $count = 0;
87
        $failed = 0;
88
89
        $this->stdout(Craft::t('recipe', 'Generating nutritional information for {count} entries...', ['count' => $total]) . PHP_EOL, BaseConsole::FG_YELLOW);
90
91
        Console::startProgress($count, $total, '', 0.8);
92
93
        foreach ($entries as $entry) {
94
            $field = $entry->{$this->field};
95
            $ingredients = $field->ingredients;
96
97
            foreach ($ingredients as $key => $value) {
98
                $ingredients[$key] = implode(' ', $value);
99
            }
100
101
            $nutritionalInfo = Recipe::$plugin->nutritionApi->getNutritionalInfo($ingredients, $field->serves);
102
103
            if (empty($nutritionalInfo['error'])) {
104
                $recipe = $entry->{$this->field};
105
106
                foreach ($nutritionalInfo as $fieldHandle => $value) {
107
                    $recipe[$fieldHandle] = $value;
108
                }
109
110
                $entry->setFieldValue($this->field, $recipe);
111
112
                if (!Craft::$app->getElements()->saveElement($entry)) {
113
                    ++$failed;
114
                }
115
            } else {
116
                ++$failed;
117
            }
118
119
            ++$count;
120
121
            Console::updateProgress($count, $total);
122
        }
123
124
        Console::endProgress();
125
126
        $succeeded = $count - $failed;
127
128
        $this->stdout(Craft::t('recipe', 'Successfully generated nutritional information for {count} entries.', ['count' => $succeeded]) . PHP_EOL, BaseConsole::FG_GREEN);
129
130
        if ($failed > 0) {
131
            $this->stderr(Craft::t('recipe', 'Failed to generate nutritional information for {count} entries.', ['count' => $failed]) . PHP_EOL, BaseConsole::FG_RED);
132
        }
133
134
        return ExitCode::OK;
135
    }
136
}
137