Passed
Push — develop ( f5931a...6d1d9b )
by Andrew
04:37
created

Recipe::getEquipment()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 2
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
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\models;
13
14
use nystudio107\recipe\helpers\Json;
15
use nystudio107\recipe\helpers\PluginTemplate;
16
use nystudio107\seomatic\Seomatic;
0 ignored issues
show
Bug introduced by
The type nystudio107\seomatic\Seomatic 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...
17
use nystudio107\seomatic\models\MetaJsonLd;
0 ignored issues
show
Bug introduced by
The type nystudio107\seomatic\models\MetaJsonLd 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...
18
19
use Craft;
20
use craft\base\Model;
21
use craft\helpers\StringHelper;
22
use craft\helpers\Template;
23
use craft\validators\ArrayValidator;
24
25
use Twig\Markup;
26
27
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
28
 * @author    nystudio107
0 ignored issues
show
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...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
29
 * @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...
30
 * @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...
31
 */
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...
32
class Recipe extends Model
33
{
34
    // Constants
35
    // =========================================================================
36
37
    const SEOMATIC_PLUGIN_HANDLE = 'seomatic';
38
    const MAIN_ENTITY_KEY = 'mainEntityOfPage';
39
40
    const US_RDA = [
41
        'calories' => 2000,
42
        'carbohydrateContent' => 275,
43
        'cholesterolContent' => 300,
44
        'fatContent' => 78,
45
        'fiberContent' => 28,
46
        'proteinContent' => 50,
47
        'saturatedFatContent' => 20,
48
        'sodiumContent' => 2300,
49
        'sugarContent' => 50,
50
    ];
51
52
    // Mapping to convert any of the incorrect plural values
53
    const NORMALIZE_PLURALS = [
54
        'tsps' => 'tsp',
55
        'tbsps' => 'tbsp',
56
        'flozs' => 'floz',
57
        'cups' => 'cups',
58
        'ozs' => 'oz',
59
        'lbs' => 'lb',
60
        'mls' => 'ml',
61
        'ls' => 'l',
62
        'mgs' => 'mg',
63
        'gs' => 'g',
64
        'kg' => 'kg',
65
    ];
66
67
    // Public Properties
68
    // =========================================================================
69
70
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
71
     * @var string
72
     */
73
    public $name;
74
75
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
76
     * @var string
77
     */
78
    public $description;
79
80
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
81
     * @var string
82
     */
83
    public $skill = 'intermediate';
84
85
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
86
     * @var int
87
     */
88
    public $serves = 1;
89
90
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
91
     * @var array
92
     */
93
    public $ingredients = [];
94
95
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
96
     * @var array
97
     */
98
    public $directions = [];
99
100
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
101
     * @var array
102
     */
103
    public $equipment = [];
104
105
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
106
     * @var int
107
     */
108
    public $imageId = 0;
109
110
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
111
     * @var int
112
     */
113
    public $prepTime;
114
115
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
116
     * @var int
117
     */
118
    public $cookTime;
119
120
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
121
     * @var int
122
     */
123
    public $totalTime;
124
125
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
126
     * @var array
127
     */
128
    public $ratings = [];
129
130
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
131
     * @var string
132
     */
133
    public $servingSize;
134
135
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
136
     * @var int
137
     */
138
    public $calories;
139
140
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
141
     * @var int
142
     */
143
    public $carbohydrateContent;
144
145
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
146
     * @var int
147
     */
148
    public $cholesterolContent;
149
150
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
151
     * @var int
152
     */
153
    public $fatContent;
154
155
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
156
     * @var int
157
     */
158
    public $fiberContent;
159
160
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
161
     * @var int
162
     */
163
    public $proteinContent;
164
165
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
166
     * @var int
167
     */
168
    public $saturatedFatContent;
169
170
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
171
     * @var int
172
     */
173
    public $sodiumContent;
174
175
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
176
     * @var int
177
     */
178
    public $sugarContent;
179
180
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
181
     * @var int
182
     */
183
    public $transFatContent;
184
185
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
186
     * @var int
187
     */
188
    public $unsaturatedFatContent;
189
190
    // Public Methods
191
    // =========================================================================
192
193
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
194
     * @inheritdoc
195
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
196
    public function init()
197
    {
198
        parent::init();
199
        // Fix any of the incorrect plural values
200
        if (!empty($this->ingredients)) {
201
            foreach ($this->ingredients as &$row) {
202
                if (!empty($row['units']) && !empty(self::NORMALIZE_PLURALS[$row['units']])) {
203
                    $row['units'] = self::NORMALIZE_PLURALS[$row['units']];
204
                }
205
            }
206
            unset($row);
207
        }
208
    }
209
210
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
211
     * @inheritdoc
212
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
213
    public function rules()
214
    {
215
        return [
216
            ['name', 'string'],
217
            ['name', 'default', 'value' => ''],
218
            ['description', 'string'],
219
            ['skill', 'string'],
220
            ['serves', 'integer'],
221
            ['imageId', 'integer'],
222
            ['prepTime', 'integer'],
223
            ['cookTime', 'integer'],
224
            ['totalTime', 'integer'],
225
            ['servingSize', 'string'],
226
            ['calories', 'integer'],
227
            ['carbohydrateContent', 'integer'],
228
            ['cholesterolContent', 'integer'],
229
            ['fatContent', 'integer'],
230
            ['fiberContent', 'integer'],
231
            ['proteinContent', 'integer'],
232
            ['saturatedFatContent', 'integer'],
233
            ['sodiumContent', 'integer'],
234
            ['sugarContent', 'integer'],
235
            ['transFatContent', 'integer'],
236
            ['unsaturatedFatContent', 'integer'],
237
            [
238
                [
239
                    'ingredients',
240
                    'directions',
241
                    'equipment',
242
                ],
243
                ArrayValidator::class,
244
            ],
245
246
        ];
247
    }
248
249
    /**
250
     * Return the JSON-LD Structured Data for this recipe
251
     *
252
     * @return array
253
     */
254
    public function getRecipeJSONLD(): array
255
    {
256
        $recipeJSONLD = [
257
            'context' => 'http://schema.org',
258
            'type' => 'Recipe',
259
            'name' => $this->name,
260
            'image' => $this->getImageUrl(),
261
            'description' => $this->description,
262
            'recipeYield' => $this->serves,
263
            'recipeIngredient' => $this->getIngredients('imperial', 0, false),
264
            'recipeInstructions' => $this->getDirections(false),
265
            'tool' => $this->getEquipment(false),
266
        ];
267
        $recipeJSONLD = array_filter($recipeJSONLD);
268
269
        $nutrition = [
270
            'type' => 'NutritionInformation',
271
            'servingSize' => $this->servingSize,
272
            'calories' => $this->calories,
273
            'carbohydrateContent' => $this->carbohydrateContent,
274
            'cholesterolContent' => $this->cholesterolContent,
275
            'fatContent' => $this->fatContent,
276
            'fiberContent' => $this->fiberContent,
277
            'proteinContent' => $this->proteinContent,
278
            'saturatedFatContent' => $this->saturatedFatContent,
279
            'sodiumContent' => $this->sodiumContent,
280
            'sugarContent' => $this->sugarContent,
281
            'transFatContent' => $this->transFatContent,
282
            'unsaturatedFatContent' => $this->unsaturatedFatContent,
283
        ];
284
        $nutrition = array_filter($nutrition);
285
        $recipeJSONLD['nutrition'] = $nutrition;
286
        if (count($recipeJSONLD['nutrition']) === 1) {
287
            unset($recipeJSONLD['nutrition']);
288
        }
289
        $aggregateRating = $this->getAggregateRating();
290
        if ($aggregateRating) {
291
            $aggregateRatings = [
292
                'type' => 'AggregateRating',
293
                'ratingCount' => $this->getRatingsCount(),
294
                'bestRating' => '5',
295
                'worstRating' => '1',
296
                'ratingValue' => $aggregateRating,
297
            ];
298
            $aggregateRatings = array_filter($aggregateRatings);
299
            $recipeJSONLD['aggregateRating'] = $aggregateRatings;
300
301
            $reviews = [];
302
            foreach ($this->ratings as $rating) {
303
                $review = [
304
                    'type' => 'Review',
305
                    'author' => $rating['author'],
306
                    'name' => $this->name . ' ' . Craft::t('recipe', 'Review'),
307
                    'description' => $rating['review'],
308
                    'reviewRating' => [
309
                        'type' => 'Rating',
310
                        'bestRating' => '5',
311
                        'worstRating' => '1',
312
                        'ratingValue' => $rating['rating'],
313
                    ],
314
                ];
315
                $reviews[] = $review;
316
            }
317
            $reviews = array_filter($reviews);
318
            $recipeJSONLD['review'] = $reviews;
319
        }
320
321
        if ($this->prepTime) {
322
            $recipeJSONLD['prepTime'] = 'PT' . $this->prepTime . 'M';
323
        }
324
        if ($this->cookTime) {
325
            $recipeJSONLD['cookTime'] = 'PT' . $this->cookTime . 'M';
326
        }
327
        if ($this->totalTime) {
328
            $recipeJSONLD['totalTime'] = 'PT' . $this->totalTime . 'M';
329
        }
330
331
        return $recipeJSONLD;
332
    }
333
334
    /**
335
     * Create the SEOmatic MetaJsonLd object for this recipe
336
     *
337
     * @param bool $add
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Doc comment for parameter $add does not match actual variable name $key
Loading history...
338
     * @param null $key
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $key is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Doc comment for parameter $key does not match actual variable name $add
Loading history...
339
     * @return null|MetaJsonLd
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
340
     */
341
    public function createRecipeMetaJsonLd($key = null, bool $add = true)
342
    {
343
        $result = null;
344
        if (Craft::$app->getPlugins()->getPlugin(self::SEOMATIC_PLUGIN_HANDLE)) {
345
            $seomatic = Seomatic::getInstance();
346
            if ($seomatic !== null) {
347
                $recipeJson = $this->getRecipeJSONLD();
348
                // If we're adding the MetaJsonLd to the container, and no key is provided, give it a random key
349
                if ($add && $key === null) {
350
                    try {
351
                        $key = StringHelper::UUID();
352
                    } catch (\Exception $e) {
353
                        // That's okay
354
                    }
355
                }
356
                if ($key !== null) {
357
                    $recipeJson['key'] = $key;
358
                }
359
                // If the key is `mainEntityOfPage` add in the URL
360
                if ($key === self::MAIN_ENTITY_KEY) {
361
                    $mainEntity = Seomatic::$plugin->jsonLd->get(self::MAIN_ENTITY_KEY);
362
                    if ($mainEntity) {
363
                        $recipeJson[self::MAIN_ENTITY_KEY] = $mainEntity[self::MAIN_ENTITY_KEY];
364
                    }
365
                }
366
367
                $result = Seomatic::$plugin->jsonLd->create(
368
                    $recipeJson,
369
                    $add
370
                );
371
            }
372
        }
373
374
        return $result;
375
    }
376
377
    /**
378
     * Render the JSON-LD Structured Data for this recipe
379
     *
380
     * @param bool $raw
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
381
     *
382
     * @return string|\Twig_Markup
383
     */
384
    public function renderRecipeJSONLD($raw = true)
385
    {
386
        return $this->renderJsonLd($this->getRecipeJSONLD(), $raw);
387
    }
388
389
    /**
390
     * Get the URL to the recipe's image
391
     *
392
     * @param null $transform
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $transform is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
393
     *
394
     * @return null|string
395
     */
396
    public function getImageUrl($transform = null)
397
    {
398
        $result = '';
399
        if (isset($this->imageId) && $this->imageId) {
400
            $image = Craft::$app->getAssets()->getAssetById($this->imageId[0]);
401
            if ($image) {
402
                $result = $image->getUrl($transform);
403
            }
404
        }
405
406
        return $result;
407
    }
408
409
    /**
410
     * Render the Nutrition Facts template
411
     *
412
     * @param array $rda
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
413
     * @return Markup
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
414
     */
415
    public function renderNutritionFacts(array $rda = self::US_RDA): Markup {
0 ignored issues
show
Coding Style introduced by
Opening brace should be on a new line
Loading history...
416
        return PluginTemplate::renderPluginTemplate(
417
            'recipe-nutrition-facts',
418
            [
419
                'value' => $this,
420
                'rda' => $rda,
421
            ]
422
        );
423
    }
424
425
    /**
426
     * Get all of the ingredients for this recipe
427
     *
428
     * @param string $outputUnits
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
429
     * @param int    $serving
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
430
     * @param bool   $raw
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
431
     *
432
     * @return array
433
     */
434
    public function getIngredients($outputUnits = 'imperial', $serving = 0, $raw = true): array
435
    {
436
        $result = [];
437
438
        if (!empty($this->ingredients)) {
439
            foreach ($this->ingredients as $row) {
440
                $convertedUnits = '';
441
                $ingredient = '';
442
                if ($row['quantity']) {
443
                    // Multiply the quantity by how many servings we want
444
                    $multiplier = 1;
445
                    if ($serving > 0) {
446
                        $multiplier = $serving / $this->serves;
447
                    }
448
                    $quantity = $row['quantity'] * $multiplier;
449
                    $originalQuantity = $quantity;
450
451
                    // Do the imperial->metric units conversion
452
                    if ($outputUnits === 'imperial') {
453
                        switch ($row['units']) {
454
                            case 'ml':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
455
                                $convertedUnits = 'tsp';
456
                                $quantity *= 0.2;
457
                                break;
458
                            case 'l':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
459
                                $convertedUnits = 'cups';
460
                                $quantity *= 4.2;
461
                                break;
462
                            case 'mg':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
463
                                $convertedUnits = 'oz';
464
                                $quantity *= 0.000035274;
465
                                break;
466
                            case 'g':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
467
                                $convertedUnits = 'oz';
468
                                $quantity *= 0.035274;
469
                                break;
470
                            case 'kg':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
471
                                $convertedUnits = 'lb';
472
                                $quantity *= 2.2046226218;
473
                                break;
474
                        }
475
                    }
476
                    // Do the metric->imperial units conversion
477
                    if ($outputUnits === 'metric') {
478
                        switch ($row['units']) {
479
                            case 'tsp':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
480
                                $convertedUnits = 'ml';
481
                                $quantity *= 4.929;
482
                                break;
483
                            case 'tbsp':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
484
                                $convertedUnits = 'ml';
485
                                $quantity *= 14.787;
486
                                break;
487
                            case 'floz':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
488
                                $convertedUnits = 'ml';
489
                                $quantity *= 29.574;
490
                                break;
491
                            case 'cups':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
492
                                $convertedUnits = 'l';
493
                                $quantity *= 0.236588;
494
                                break;
495
                            case 'oz':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
496
                                $convertedUnits = 'g';
497
                                $quantity *= 28.3495;
498
                                break;
499
                            case 'lb':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
500
                                $convertedUnits = 'kg';
501
                                $quantity *= 0.45359237;
502
                                break;
503
                        }
504
505
                        $quantity = round($quantity, 1);
506
                    }
507
508
                    // Convert units to nice fractions
509
                    $quantity = $this->convertToFractions($quantity);
510
511
                    $ingredient .= $quantity;
512
513
                    if ($row['units']) {
514
                        $units = $row['units'];
515
                        if ($convertedUnits) {
516
                            $units = $convertedUnits;
517
                        }
518
                        if ($originalQuantity <= 1) {
519
                            $units = rtrim($units);
520
                            $units = rtrim($units, 's');
521
                        }
522
                        $ingredient .= ' ' . $units;
523
                    }
524
                }
525
                if ($row['ingredient']) {
526
                    $ingredient .= ' ' . $row['ingredient'];
527
                }
528
                if ($raw) {
529
                    $ingredient = Template::raw($ingredient);
530
                }
531
                $result[] = $ingredient;
532
            }
533
        }
534
535
        return $result;
536
    }
537
538
    /**
539
     * Convert decimal numbers into fractions
540
     *
541
     * @param $quantity
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
542
     *
543
     * @return string
544
     */
545
    private function convertToFractions($quantity)
0 ignored issues
show
Coding Style introduced by
Private method name "Recipe::convertToFractions" must be prefixed with an underscore
Loading history...
546
    {
547
        $whole = floor($quantity);
548
        // Round the mantissa so we can do a floating point comparison without
549
        // weirdness, per: https://www.php.net/manual/en/language.types.float.php#113703
550
        $fraction = round($quantity - $whole, 3);
551
        switch ($fraction) {
552
            case 0:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
553
                $fraction = '';
554
                break;
555
            case 0.25:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
556
                $fraction = ' &frac14;';
557
                break;
558
            case 0.33:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
559
                $fraction = ' &frac13;';
560
                break;
561
            case 0.66:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
562
                $fraction = ' &frac23;';
563
                break;
564
            case 0.165:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
565
                $fraction = ' &frac16;';
566
                break;
567
            case 0.5:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
568
                $fraction = ' &frac12;';
569
                break;
570
            case 0.75:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
571
                $fraction = ' &frac34;';
572
                break;
573
            case 0.125:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
574
                $fraction = ' &#x215B;';
575
                break;
576
            case 0.375:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
577
                $fraction = ' &#x215C;';
578
                break;
579
            case 0.625:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
580
                $fraction = ' &#x215D;';
581
                break;
582
            case 0.875:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
583
                $fraction = ' &#x215E;';
584
                break;
585
            default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
586
                $precision = 1;
587
                $pnum = round($fraction, $precision);
588
                $denominator = 10 ** $precision;
589
                $numerator = $pnum * $denominator;
590
                $fraction = ' <sup>'
591
                    .$numerator
592
                    . '</sup>&frasl;<sub>'
593
                    .$denominator
594
                    . '</sub>';
595
                break;
596
        }
597
        if ($whole == 0) {
598
            $whole = '';
599
        }
600
601
        return $whole.$fraction;
602
    }
603
604
    /**
605
     * Get all of the directions for this recipe
606
     *
607
     * @param bool $raw
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
608
     *
609
     * @return array
610
     */
611
    public function getDirections($raw = true)
612
    {
613
        $result = [];
614
        if (!empty($this->directions)) {
615
            foreach ($this->directions as $row) {
616
                $direction = $row['direction'];
617
                if ($raw) {
618
                    $direction = Template::raw($direction);
619
                }
620
                $result[] = $direction;
621
            }
622
        }
623
624
        return $result;
625
    }
626
627
    /**
628
     * Get all of the equipment for this recipe
629
     *
630
     * @param bool $raw
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
631
     *
632
     * @return array
633
     */
634
    public function getEquipment($raw = true)
635
    {
636
        $result = [];
637
        if (!empty($this->equipment)) {
638
            foreach ($this->equipment as $row) {
639
                $equipment = $row['equipment'];
640
                if ($raw) {
641
                    $equipment = Template::raw(equipment);
0 ignored issues
show
Bug introduced by
The constant nystudio107\recipe\models\equipment was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
642
                }
643
                $result[] = $equipment;
644
            }
645
        }
646
647
        return $result;
648
    }
649
650
    /**
651
     * Get the aggregate rating from all of the ratings
652
     *
653
     * @return float|int|string
654
     */
655
    public function getAggregateRating()
656
    {
657
        $result = 0;
658
        $total = 0;
659
        if (isset($this->ratings) && !empty($this->ratings)) {
660
            foreach ($this->ratings as $row) {
661
                $result += $row['rating'];
662
                $total++;
663
            }
664
            $result /= $total;
665
        } else {
666
            $result = '';
667
        }
668
669
        return $result;
670
    }
671
672
    /**
673
     * Get the total number of ratings
674
     *
675
     * @return int
676
     */
677
    public function getRatingsCount(): int
678
    {
679
        return count($this->ratings);
680
    }
681
682
    // Private Methods
683
    // =========================================================================
684
685
    /**
686
     * Renders a JSON-LD representation of the schema
687
     *
688
     * @param      $json
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 6
Loading history...
689
     * @param bool $raw
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
690
     *
691
     * @return string|\Twig_Markup
692
     */
693
    private function renderJsonLd($json, $raw = true)
0 ignored issues
show
Coding Style introduced by
Private method name "Recipe::renderJsonLd" must be prefixed with an underscore
Loading history...
694
    {
695
        $linebreak = '';
696
697
        // If `devMode` is enabled, make the JSON-LD human-readable
698
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
699
            $linebreak = PHP_EOL;
700
        }
701
702
        // Render the resulting JSON-LD
703
        $result = '<script type="application/ld+json">'
704
            .$linebreak
705
            .Json::encode($json)
706
            .$linebreak
707
            .'</script>';
708
709
        if ($raw === true) {
710
            $result = Template::raw($result);
711
        }
712
713
        return $result;
714
    }
715
}
716