Passed
Push — develop ( 19391e...30063e )
by Andrew
07:28
created

NutritionApi::getNutritionalInfo()   B

Complexity

Conditions 7
Paths 21

Size

Total Lines 55
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 19
Bugs 0 Features 0
Metric Value
cc 7
eloc 37
c 19
b 0
f 0
nc 21
nop 2
dl 0
loc 55
rs 8.3946

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
Missing @category tag in file comment
Loading history...
Coding Style introduced by
PHP version not specified
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\services;
13
14
use Craft;
15
use craft\base\Component;
16
use Exception;
17
use nystudio107\recipe\Recipe;
18
19
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
20
 * @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
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
21
 * @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...
22
 * @since     1.3.0
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
23
 */
0 ignored issues
show
Coding Style introduced by
Missing @link tag in class comment
Loading history...
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
24
class NutritionApi extends Component
25
{
26
    /**
27
     * Returns nutritional information about a recipe.
28
     *
29
     * @param array $ingredients
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
30
     * @param int|null $serves
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
31
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
32
     */
33
    public function getNutritionalInfo(array $ingredients, int $serves = null): array
34
    {
35
        if (Recipe::$plugin->settings->hasApiCredentials() === false) {
36
            return [];
37
        }
38
39
        $url = 'https://api.edamam.com/api/nutrition-details'
40
            .'?app_id='.Craft::parseEnv(Recipe::$plugin->settings->apiApplicationId)
41
            .'&app_key='.Craft::parseEnv(Recipe::$plugin->settings->apiApplicationKey);
42
43
        $data = [
44
            'ingr' => $ingredients,
45
        ];
46
47
        if ($serves) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $serves of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
48
            $data['yield'] = $serves;
49
        }
50
51
        try {
52
            $response = Craft::createGuzzleClient()->post($url, ['json' => $data]);
53
54
            $result = json_decode($response->getBody());
55
56
            $yield = $result->yield ?: 1;
57
58
            return [
59
                'servingSize' => round($result->totalWeight / $yield, 0).' grams',
60
                'calories' => round($result->totalNutrients->ENERC_KCAL->quantity / $yield, 0),
61
                'carbohydrateContent' => round($result->totalNutrients->CHOCDF->quantity / $yield, 1),
62
                'cholesterolContent' => round($result->totalNutrients->CHOLE->quantity / $yield, 1),
63
                'fatContent' => round($result->totalNutrients->FAT->quantity / $yield, 1),
64
                'fiberContent' => round($result->totalNutrients->FIBTG->quantity / $yield, 1),
65
                'proteinContent' => round($result->totalNutrients->PROCNT->quantity / $yield, 1),
66
                'saturatedFatContent' => round($result->totalNutrients->FASAT->quantity / $yield, 1),
67
                'sodiumContent' => round($result->totalNutrients->NA->quantity / $yield, 1),
68
                'sugarContent' => round($result->totalNutrients->SUGAR->quantity / $yield, 1),
69
                'transFatContent' => round($result->totalNutrients->FATRN->quantity / $yield, 1),
70
                'unsaturatedFatContent' => round(($result->totalNutrients->FAMS->quantity + $result->totalNutrients->FAPU->quantity) / $yield, 1),
71
            ];
72
        }
73
        catch (Exception $exception) {
74
            $message = 'Error fetching nutritional information from API. ';
75
76
            switch ($exception->getCode()) {
77
                case 401:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
78
                    $message .= 'Please verify your API credentials.';
79
                    break;
80
                case 555:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
81
                    $message .= 'One or more ingredients could not be recognized.';
82
                    break;
83
            }
84
85
            Craft::error($message.$exception->getMessage(), __METHOD__);
86
87
            return ['error' => $message];
88
        }
89
    }
90
}
91