Passed
Push — develop ( d28991...6505d7 )
by Andrew
05:02
created

Recipe::getRecipeJSONLD()   B

Complexity

Conditions 7
Paths 32

Size

Total Lines 77
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 60
nc 32
nop 0
dl 0
loc 77
rs 7.9393
c 0
b 0
f 0

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