Test Failed
Pull Request — master (#1704)
by Arnaud
05:37
created

Page::setTerms()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Collection\Page;
15
16
use Cecil\Collection\Item;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Util;
19
use Cocur\Slugify\Slugify;
20
use Symfony\Component\Finder\SplFileInfo;
21
22
/**
23
 * Class Page.
24
 */
25
class Page extends Item
26
{
27
    public const SLUGIFY_PATTERN = '/(^\/|[^._a-z0-9\/]|-)+/'; // should be '/^\/|[^_a-z0-9\/]+/'
28
29
    /** @var bool True if page is not created from a file. */
30
    protected $virtual;
31
32
    /** @var SplFileInfo */
33
    protected $file;
34
35
    /** @var Type Type */
36
    protected $type;
37
38
    /** @var string */
39
    protected $folder;
40
41
    /** @var string */
42
    protected $slug;
43
44
    /** @var string path = folder + slug. */
45
    protected $path;
46
47
    /** @var string */
48
    protected $section;
49
50
    /** @var string */
51
    protected $frontmatter;
52
53
    /** @var array Front matter before conversion. */
54
    protected $fmVariables = [];
55
56
    /** @var string Body before conversion. */
57
    protected $body;
58
59
    /** @var string Body after conversion. */
60
    protected $html;
61
62
    /** @var array Output, by format */
63
    protected $rendered = [];
64
65
    /** @var Collection Subpages of a list page. */
66
    protected $subPages;
67
68
    /** @var array */
69
    protected $paginator = [];
70
71
    /** @var \Cecil\Collection\Taxonomy\Vocabulary Terms of a vocabulary. */
72
    protected $terms;
73
74
    /** @var self Parent page of a PAGE page or a SECTION page */
75
    protected $parent;
76
77 1
    /** @var Slugify */
78
    private static $slugifier;
79 1
80 1
    public function __construct(string $id)
81 1
    {
82
        parent::__construct($id);
83 1
        $this->setVirtual(true);
84 1
        $this->setType(Type::PAGE->value);
85 1
        // default variables
86 1
        $this->setVariables([
87 1
            'title'            => 'Page Title',
88 1
            'date'             => new \DateTime(),
89 1
            'updated'          => new \DateTime(),
90 1
            'weight'           => null,
91 1
            'filepath'         => null,
92
            'published'        => true,
93
            'content_template' => 'page.content.twig',
94
        ]);
95
    }
96
97
    /**
98
     * toString magic method to prevent Twig get_attribute fatal error.
99 1
     *
100
     * @return string
101 1
     */
102
    public function __toString()
103
    {
104
        return $this->getId();
105
    }
106
107 1
    /**
108
     * Turns a path (string) into a slug (URI).
109 1
     */
110 1
    public static function slugify(string $path): string
111
    {
112
        if (!self::$slugifier instanceof Slugify) {
113 1
            self::$slugifier = Slugify::create(['regexp' => self::SLUGIFY_PATTERN]);
114
        }
115
116
        return self::$slugifier->slugify($path);
117
    }
118
119 1
    /**
120
     * Creates the ID from the file (path).
121 1
     */
122 1
    public static function createIdFromFile(SplFileInfo $file): string
123
    {
124 1
        $fileComponents = self::getFileComponents($file);
125
126 1
        $fileComponents['path'];
127
        $fileComponents['name'];
128 1
        $fileComponents['ext'];
129 1
130
131
        $relativePath = self::slugify($fileComponents['path']);
132 1
        $basename = self::slugify(PrefixSuffix::subPrefix($file->getBasename('.' . $file->getExtension())));
133
        // if file is "README.md", ID is "index"
134
        $basename = (string) str_ireplace('readme', 'index', $basename);
135 1
        // if file is section's index: "section/index.md", ID is "section"
136 1
        if (!empty($relativePath) && PrefixSuffix::sub($basename) == 'index') {
137
            // case of a localized section's index: "section/index.fr.md", ID is "fr/section"
138
            if (PrefixSuffix::hasSuffix($basename)) {
139 1
                return PrefixSuffix::getSuffix($basename) . '/' . $relativePath;
140
            }
141
142
            return $relativePath;
143
        }
144
        // localized page
145 1
        if (PrefixSuffix::hasSuffix($basename)) {
146
            return trim(Util::joinPath(PrefixSuffix::getSuffix($basename), $relativePath, PrefixSuffix::sub($basename)), '/');
147 1
        }
148 1
149 1
        return trim(Util::joinPath($relativePath, $basename), '/');
150
    }
151
152 1
    /**
153
     * Returns the ID of a page without language.
154
     */
155
    public function getIdWithoutLang(): string
156
    {
157
        $langPrefix = $this->getVariable('language') . '/';
158 1
        if ($this->hasVariable('language') && Util\Str::startsWith($this->getId(), $langPrefix)) {
159
            return substr($this->getId(), \strlen($langPrefix));
160 1
        }
161 1
162
        return $this->getId();
163
    }
164
165
    /**
166 1
     * Set file.
167 1
     */
168 1
    public function setFile(SplFileInfo $file): self
169
    {
170 1
        $this->file = $file;
171
        $this->setVirtual(false);
172 1
173 1
        /*
174
         * File path components
175
         */
176
        $fileRelativePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath());
177
        $fileExtension = $this->file->getExtension();
178 1
        $fileName = $this->file->getBasename('.' . $fileExtension);
179 1
        // renames "README" to "index"
180 1
        $fileName = (string) str_ireplace('readme', 'index', $fileName);
181 1
        // case of "index" = home page
182 1
        if (empty($this->file->getRelativePath()) && PrefixSuffix::sub($fileName) == 'index') {
183 1
            $this->setType(Type::HOMEPAGE->value);
184 1
        }
185 1
        /*
186 1
         * Set page properties and variables
187
         */
188
        $this->setFolder($fileRelativePath);
189
        $this->setSlug($fileName);
190
        $this->setPath($this->getFolder() . '/' . $this->getSlug());
191 1
        $this->setVariables([
192 1
            'title'    => PrefixSuffix::sub($fileName),
193 1
            'date'     => (new \DateTime())->setTimestamp($this->file->getMTime()),
194
            'updated'  => (new \DateTime())->setTimestamp($this->file->getMTime()),
195 1
            'filepath' => $this->file->getRelativePathname(),
196 1
        ]);
197
        // is a section?
198
        if (PrefixSuffix::sub($fileName) == 'index') {
199 1
            $this->setType(Type::SECTION);
0 ignored issues
show
Bug introduced by
Cecil\Collection\Page\Type::SECTION of type Cecil\Collection\Page\Type is incompatible with the type string expected by parameter $type of Cecil\Collection\Page\Page::setType(). ( Ignorable by Annotation )

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

199
            $this->setType(/** @scrutinizer ignore-type */ Type::SECTION);
Loading history...
200
            $this->setVariable('title', ucfirst(explode('/', $fileRelativePath)[\count(explode('/', $fileRelativePath)) - 1]));
201
            // is the home page?
202
            if (empty($this->getFolder())) {
203
                $this->setType(Type::HOMEPAGE);
204 1
                $this->setVariable('title', 'Homepage');
205 1
            }
206
        }
207
        // is file has a prefix?
208 1
        if (PrefixSuffix::hasPrefix($fileName)) {
209
            $prefix = PrefixSuffix::getPrefix($fileName);
210 1
            if ($prefix !== null) {
211
                // prefix is a valid date?
212
                if (Util\Date::isValid($prefix)) {
213
                    $this->setVariable('date', (string) $prefix);
214
                } else {
215
                    // prefix is an integer: used for sorting
216 1
                    $this->setVariable('weight', (int) $prefix);
217
                }
218 1
            }
219
        }
220
        // is file has a language suffix?
221
        if (PrefixSuffix::hasSuffix($fileName)) {
222 1
            $this->setVariable('language', PrefixSuffix::getSuffix($fileName));
223
        }
224
        // set reference between page's translations, even if it exist in only one language
225
        $this->setVariable('langref', $this->getPath());
226
227
        return $this;
228 1
    }
229
230 1
    /**
231 1
     * Returns file real path.
232 1
     */
233 1
    public function getFilePath(): ?string
234
    {
235 1
        if ($this->file === null) {
236
            return null;
237
        }
238
239
        return $this->file->getRealPath() === false ? null : $this->file->getRealPath();
240
    }
241 1
242
    /**
243 1
     * Parse file content.
244
     */
245
    public function parse(): self
246
    {
247
        $parser = new Parser($this->file);
248
        $parsed = $parser->parse();
249 1
        $this->frontmatter = $parsed->getFrontmatter();
250
        $this->body = $parsed->getBody();
251 1
252
        return $this;
253
    }
254
255
    /**
256
     * Get front matter.
257 1
     */
258
    public function getFrontmatter(): ?string
259 1
    {
260
        return $this->frontmatter;
261 1
    }
262
263
    /**
264
     * Get body as raw.
265
     */
266
    public function getBody(): ?string
267 1
    {
268
        return $this->body;
269 1
    }
270
271
    /**
272
     * Set virtual status.
273
     */
274
    public function setVirtual(bool $virtual): self
275 1
    {
276
        $this->virtual = $virtual;
277 1
278
        return $this;
279 1
    }
280
281
    /**
282
     * Is current page is virtual?
283
     */
284
    public function isVirtual(): bool
285 1
    {
286
        return $this->virtual;
287 1
    }
288
289
    /**
290
     * Set page type.
291
     */
292
    public function setType(string $type): self
293 1
    {
294
        $this->type = Type::from($type);
295 1
296
        return $this;
297 1
    }
298
299
    /**
300
     * Get page type.
301
     */
302
    public function getType(): string
303 1
    {
304
        return $this->type->value;
305 1
    }
306
307
    /**
308
     * Set path without slug.
309
     */
310
    public function setFolder(string $folder): self
311 1
    {
312
        $this->folder = self::slugify($folder);
313 1
314 1
        return $this;
315
    }
316
317 1
    /**
318 1
     * Get path without slug.
319
     */
320 1
    public function getFolder(): ?string
321
    {
322 1
        return $this->folder;
323
    }
324
325
    /**
326
     * Set slug.
327
     */
328 1
    public function setSlug(string $slug): self
329
    {
330 1
        if (!$this->slug) {
331
            $slug = self::slugify(PrefixSuffix::sub($slug));
332
        }
333
        // force slug and update path
334
        if ($this->slug && $this->slug != $slug) {
335
            $this->setPath($this->getFolder() . '/' . $slug);
336 1
        }
337
        $this->slug = $slug;
338 1
339
        return $this;
340
    }
341 1
342 1
    /**
343
     * Get slug.
344 1
     */
345
    public function getSlug(): string
346
    {
347
        return $this->slug;
348 1
    }
349 1
350
    /**
351 1
     * Set path.
352
     */
353 1
    public function setPath(string $path): self
354
    {
355
        $path = trim($path, '/');
356 1
357 1
        // case of homepage
358
        if ($path == 'index') {
359 1
            $this->path = '';
360
361
            return $this;
362
        }
363 1
364 1
        // case of custom sections' index (ie: section/index.md -> section)
365
        if (substr($path, -6) == '/index') {
366
            $this->path = substr($path, 0, \strlen($path) - 6);
367 1
        }
368 1
369
        $lastslash = strrpos($this->path, '/');
370 1
371
        // case of root/top-level pages
372
        if ($lastslash === false) {
373
            $this->slug = $this->path;
374
375
            return $this;
376 1
        }
377
378 1
        // case of sections' pages: set section
379
        if (!$this->virtual && $this->getSection() === null) {
380
            $this->section = explode('/', $this->path)[0];
381
        }
382
        // set/update folder and slug
383
        $this->folder = substr($this->path, 0, $lastslash);
384
        $this->slug = substr($this->path, -(\strlen($this->path) - $lastslash - 1));
385
386
        return $this;
387
    }
388
389
    /**
390
     * Get path.
391
     */
392 1
    public function getPath(): ?string
393
    {
394 1
        return $this->path;
395
    }
396 1
397
    /**
398
     * @see getPath()
399
     */
400
    public function getPathname(): ?string
401
    {
402 1
        return $this->getPath();
403
    }
404 1
405
    /**
406
     * Set section.
407
     */
408
    public function setSection(string $section): self
409
    {
410
        $this->section = $section;
411
412
        return $this;
413
    }
414
415
    /**
416
     * Get section.
417
     */
418
    public function getSection(): ?string
419
    {
420 1
        return !empty($this->section) ? $this->section : null;
421
    }
422 1
423
    /**
424 1
     * Unset section.
425
     */
426
    public function unSection(): self
427
    {
428
        $this->section = null;
429
430 1
        return $this;
431
    }
432 1
433
    /**
434
     * Set body as HTML.
435
     */
436
    public function setBodyHtml(string $html): self
437
    {
438 1
        $this->html = $html;
439
440 1
        return $this;
441
    }
442
443
    /**
444
     * Get body as HTML.
445
     */
446 1
    public function getBodyHtml(): ?string
447
    {
448 1
        return $this->html;
449
    }
450 1
451
    /**
452
     * @see getBodyHtml()
453
     */
454
    public function getContent(): ?string
455
    {
456 1
        return $this->getBodyHtml();
457
    }
458 1
459
    /**
460
     * Add rendered.
461
     */
462
    public function addRendered(array $rendered): self
463
    {
464 1
        $this->rendered += $rendered;
465
466 1
        return $this;
467
    }
468 1
469
    /**
470
     * Get rendered.
471
     */
472
    public function getRendered(): array
473
    {
474 1
        return $this->rendered;
475
    }
476 1
477
    /**
478
     * Set Subpages.
479
     */
480
    public function setPages(\Cecil\Collection\Page\Collection $subPages): self
481
    {
482 1
        $this->subPages = $subPages;
483
484 1
        return $this;
485
    }
486 1
487
    /**
488
     * Get Subpages.
489
     */
490
    public function getPages(): ?\Cecil\Collection\Page\Collection
491
    {
492 1
        return $this->subPages;
493
    }
494 1
495
    /**
496
     * Set paginator.
497
     */
498
    public function setPaginator(array $paginator): self
499
    {
500
        $this->paginator = $paginator;
501
502
        return $this;
503
    }
504
505
    /**
506
     * Get paginator.
507
     */
508 1
    public function getPaginator(): array
509
    {
510 1
        return $this->paginator;
511
    }
512 1
513
    /**
514
     * Paginator backward compatibility.
515
     */
516
    public function getPagination(): array
517
    {
518 1
        return $this->getPaginator();
519
    }
520 1
521
    /**
522
     * Set vocabulary terms.
523
     */
524
    public function setTerms(\Cecil\Collection\Taxonomy\Vocabulary $terms): self
525
    {
526
        $this->terms = $terms;
527
528
        return $this;
529
    }
530
531
    /**
532 1
     * Get vocabulary terms.
533
     */
534 1
    public function getTerms(): \Cecil\Collection\Taxonomy\Vocabulary
535 1
    {
536
        return $this->terms;
537
    }
538 1
539
    /*
540
     * Helpers to set and get variables.
541
     */
542
543
    /**
544 1
     * Set an array as variables.
545
     *
546 1
     * @throws RuntimeException
547
     */
548
    public function setVariables(array $variables): self
549
    {
550
        foreach ($variables as $key => $value) {
551
            $this->setVariable($key, $value);
552
        }
553
554
        return $this;
555
    }
556
557 1
    /**
558
     * Get all variables.
559 1
     */
560
    public function getVariables(): array
561 1
    {
562 1
        return $this->properties;
563 1
    }
564
565 1
    /**
566
     * Set a variable.
567
     *
568
     * @param string $name  Name of the variable
569 1
     * @param mixed  $value Value of the variable
570 1
     *
571
     * @throws RuntimeException
572 1
     */
573
    public function setVariable(string $name, $value): self
574
    {
575
        $this->filterBool($value);
576
        switch ($name) {
577 1
            case 'date':
578 1
            case 'updated':
579 1
            case 'lastmod':
580 1
                try {
581
                    $date = Util\Date::toDatetime($value);
582 1
                } catch (\Exception) {
583
                    throw new \Exception(sprintf('The value of "%s" is not a valid date: "%s".', $name, var_export($value, true)));
584
                }
585
                $this->offsetSet($name == 'lastmod' ? 'updated' : $name, $date);
586 1
                break;
587 1
588
            case 'schedule':
589 1
                /*
590 1
                 * publish: 2012-10-08
591
                 * expiry: 2012-10-09
592 1
                 */
593 1
                $this->offsetSet('published', false);
594 1
                if (\is_array($value)) {
595 1
                    if (\array_key_exists('publish', $value) && Util\Date::toDatetime($value['publish']) <= Util\Date::toDatetime('now')) {
596 1
                        $this->offsetSet('published', true);
597
                    }
598
                    if (\array_key_exists('expiry', $value) && Util\Date::toDatetime($value['expiry']) >= Util\Date::toDatetime('now')) {
599 1
                        $this->offsetSet('published', true);
600 1
                    }
601 1
                }
602
                break;
603 1
            case 'draft':
604
                // draft: true = published: false
605
                if ($value === true) {
606 1
                    $this->offsetSet('published', false);
607
                }
608
                break;
609
            case 'path':
610
            case 'slug':
611
                $slugify = self::slugify((string) $value);
612
                if ($value != $slugify) {
613
                    throw new RuntimeException(sprintf('"%s" variable should be "%s" (not "%s") in "%s".', $name, $slugify, (string) $value, $this->getId()));
614 1
                }
615
                $method = 'set' . ucfirst($name);
616 1
                $this->$method($value);
617
                break;
618
            default:
619
                $this->offsetSet($name, $value);
620
        }
621
622
        return $this;
623
    }
624
625
    /**
626
     * Is variable exists?
627 1
     *
628
     * @param string $name Name of the variable
629 1
     */
630 1
    public function hasVariable(string $name): bool
631
    {
632
        return $this->offsetExists($name);
633 1
    }
634
635
    /**
636
     * Get a variable.
637
     *
638
     * @param string     $name    Name of the variable
639
     * @param mixed|null $default Default value
640
     *
641 1
     * @return mixed|null
642
     */
643 1
    public function getVariable(string $name, $default = null)
644 1
    {
645
        if ($this->offsetExists($name)) {
646
            return $this->offsetGet($name);
647 1
        }
648
649
        return $default;
650
    }
651
652
    /**
653 1
     * Unset a variable.
654
     *
655 1
     * @param string $name Name of the variable
656
     */
657 1
    public function unVariable(string $name): self
658
    {
659
        if ($this->offsetExists($name)) {
660
            $this->offsetUnset($name);
661
        }
662
663 1
        return $this;
664
    }
665 1
666
    /**
667
     * Set front matter (only) variables.
668
     */
669
    public function setFmVariables(array $variables): self
670
    {
671
        $this->fmVariables = $variables;
672
673
        return $this;
674
    }
675
676
    /**
677 1
     * Get front matter variables.
678
     */
679 1
    public function getFmVariables(): array
680 1
    {
681 1
        return $this->fmVariables;
682
    }
683
684
    /**
685
     * {@inheritdoc}
686
     */
687
    public function setId(string $id): self
688 1
    {
689
        return parent::setId($id);
690 1
    }
691
692
    /**
693
     * Set parent page.
694
     */
695
    public function setParent(self $page): self
696
    {
697
        if ($page->getId() != $this->getId()) {
698
            $this->parent = $page;
699
        }
700
701
        return $this;
702
    }
703
704
    /**
705
     * Returns parent page if exists.
706
     */
707
    public function getParent(): ?self
708
    {
709
        return $this->parent;
710
    }
711
712
    /**
713
     * Cast "boolean" string (or array of strings) to boolean.
714
     *
715
     * @param mixed $value Value to filter
716
     *
717
     * @return bool|mixed
718
     *
719
     * @see strToBool()
720
     */
721
    private function filterBool(&$value)
722
    {
723
        \Cecil\Util\Str::strToBool($value);
724
        if (\is_array($value)) {
725
            array_walk_recursive($value, '\Cecil\Util\Str::strToBool');
726
        }
727
    }
728
729
    /**
730
     * Get file components.
731
     *
732
     * [
733
     *   path => relative path,
734
     *   name => name,
735
     *   ext  => extension,
736
     * ]
737
     */
738
    private static function getFileComponents(SplFileInfo $file): array
739
    {
740
        return [
741
            'path' => str_replace(DIRECTORY_SEPARATOR, '/', $file->getRelativePath()),
742
            'name' => (string) str_ireplace('readme', 'index', $file->getBasename('.' . $file->getExtension())),
743
            'ext'  => $file->getExtension(),
744
        ];
745
    }
746
}
747