Issues (446)

src/services/NutritionApi.php (28 issues)

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
The tag in position 1 should be the @copyright tag
Loading history...
9
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
@copyright tag must contain a year and the name of the copyright holder
Loading history...
10
 */
0 ignored issues
show
PHP version not specified
Loading history...
Missing @category tag in file comment
Loading history...
Missing @package tag in file comment
Loading history...
Missing @author tag in file comment
Loading history...
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\models\Settings;
18
use nystudio107\recipe\Recipe;
19
20
/**
0 ignored issues
show
Missing short description in doc comment
Loading history...
21
 * @author    nystudio107
0 ignored issues
show
The tag in position 1 should be the @package tag
Loading history...
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
22
 * @package   Recipe
0 ignored issues
show
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
23
 * @since     1.3.0
0 ignored issues
show
The tag in position 3 should be the @author tag
Loading history...
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
24
 */
0 ignored issues
show
Missing @category tag in class comment
Loading history...
Missing @license tag in class comment
Loading history...
Missing @link tag in class comment
Loading history...
25
class NutritionApi extends Component
26
{
27
    /**
0 ignored issues
show
Parameter $ingredients should have a doc-comment as per coding-style.
Loading history...
28
     * Returns nutritional information about a recipe.
29
     *
30
     * @param int|null $serves
0 ignored issues
show
Missing parameter comment
Loading history...
Doc comment for parameter $serves does not match actual variable name $ingredients
Loading history...
31
     */
0 ignored issues
show
Missing @return tag in function comment
Loading history...
32
    public function getNutritionalInfo(array $ingredients, int $serves = null): array
33
    {
34
        /** @var Settings $settings */
0 ignored issues
show
The open comment tag must be the only content on the line
Loading history...
Missing short description in doc comment
Loading history...
The close comment tag must be the only content on the line
Loading history...
35
        $settings = Recipe::$plugin->getSettings();
0 ignored issues
show
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

35
        /** @scrutinizer ignore-call */ 
36
        $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...
36
        if (!$settings->hasApiCredentials()) {
37
            return [];
38
        }
39
40
        $url = 'https://api.edamam.com/api/nutrition-details'
41
            . '?app_id=' . Craft::parseEnv($settings->apiApplicationId)
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

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

41
            . '?app_id=' . /** @scrutinizer ignore-deprecated */ Craft::parseEnv($settings->apiApplicationId)

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...
42
            . '&app_key=' . Craft::parseEnv($settings->apiApplicationKey);
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

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

42
            . '&app_key=' . /** @scrutinizer ignore-deprecated */ Craft::parseEnv($settings->apiApplicationKey);

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...
43
44
        $data = [
45
            'ingr' => $ingredients,
46
        ];
47
48
        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...
49
            $data['yield'] = $serves;
50
        }
51
52
        try {
53
            $response = Craft::createGuzzleClient()->post($url, ['json' => $data]);
54
55
            $result = json_decode($response->getBody(), null, 512, JSON_THROW_ON_ERROR);
56
57
            $yield = $result->yield ?: 1;
58
59
            return [
60
                'servingSize' => round($result->totalWeight ?? 0 / $yield, 0) . ' grams',
61
                'calories' => round($result->totalNutrients->ENERC_KCAL->quantity ?? 0 / $yield, 0),
62
                'carbohydrateContent' => round($result->totalNutrients->CHOCDF->quantity ?? 0 / $yield, 1),
63
                'cholesterolContent' => round($result->totalNutrients->CHOLE->quantity ?? 0 / $yield, 1),
64
                'fatContent' => round($result->totalNutrients->FAT->quantity ?? 0 / $yield, 1),
65
                'fiberContent' => round($result->totalNutrients->FIBTG->quantity ?? 0 / $yield, 1),
66
                'proteinContent' => round($result->totalNutrients->PROCNT->quantity ?? 0 / $yield, 1),
67
                'saturatedFatContent' => round($result->totalNutrients->FASAT->quantity ?? 0 / $yield, 1),
68
                'sodiumContent' => round($result->totalNutrients->NA->quantity ?? 0 / $yield, 1),
69
                'sugarContent' => round($result->totalNutrients->SUGAR->quantity ?? 0 / $yield, 1),
70
                'transFatContent' => round($result->totalNutrients->FATRN->quantity ?? 0 / $yield, 1),
71
                'unsaturatedFatContent' => round((($result->totalNutrients->FAMS->quantity ?? 0) + ($result->totalNutrients->FAPU->quantity ?? 0)) / $yield, 1),
72
            ];
73
        } catch (Exception $exception) {
74
            $message = 'Error fetching nutritional information from API. ';
75
76
            if ($exception->getCode() == 401) {
77
                $message .= 'Please verify your API credentials.';
78
            } elseif ($exception->getCode() == 555) {
79
                $message .= 'One or more ingredients could not be recognized.';
80
            }
81
82
            Craft::error($message . $exception->getMessage(), __METHOD__);
83
84
            return ['error' => $message];
85
        }
86
    }
87
}
88