Passed
Push — develop ( 4d6557...ba8d86 )
by Andrew
04:35
created

Recipe::createRecipeMetaJsonLd()   B

Complexity

Conditions 9
Paths 20

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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