Page::getFilePath()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 0
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
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
 * Page class.
24
 *
25
 * Represents a page in the collection, which can be created from a file or be virtual.
26
 * Provides methods to manage page properties, variables, and rendering.
27
 */
28
class Page extends Item
29
{
30
    public const SLUGIFY_PATTERN = '/(^\/|[^._a-z0-9\/]|-)+/'; // should be '/^\/|[^_a-z0-9\/]+/'
31
32
    /** @var bool True if page is not created from a file. */
33
    protected $virtual;
34
35
    /** @var SplFileInfo */
36
    protected $file;
37
38
    /** @var Type Type */
39
    protected $type;
40
41
    /** @var string */
42
    protected $folder;
43
44
    /** @var string */
45
    protected $slug;
46
47
    /** @var string path = folder + slug. */
48
    protected $path;
49
50
    /** @var string */
51
    protected $section;
52
53
    /** @var string */
54
    protected $frontmatter;
55
56
    /** @var array Front matter before conversion. */
57
    protected $fmVariables = [];
58
59
    /** @var string Body before conversion. */
60
    protected $body;
61
62
    /** @var string Body after conversion. */
63
    protected $html;
64
65
    /** @var array Output, by format. */
66
    protected $rendered = [];
67
68
    /** @var Collection pages list. */
69
    protected $pages;
70
71
    /** @var array */
72
    protected $paginator = [];
73
74
    /** @var \Cecil\Collection\Taxonomy\Vocabulary Terms of a vocabulary. */
75
    protected $terms;
76
77 1
    /** @var Slugify */
78
    private static $slugifier;
79 1
80 1
    public function __construct(mixed $id)
81 1
    {
82
        if (!\is_string($id) && !$id instanceof SplFileInfo) {
83 1
            throw new RuntimeException('Create a page with a string ID or a SplFileInfo.');
84 1
        }
85 1
86 1
        // default properties
87 1
        $this->setVirtual(true);
88 1
        $this->setType(Type::PAGE->value);
89 1
        $this->setVariables([
90 1
            'title'            => 'Page Title',
91 1
            'date'             => new \DateTime(),
92
            'updated'          => new \DateTime(),
93
            'weight'           => null,
94
            'filepath'         => null,
95
            'published'        => true,
96
            'content_template' => 'page.content.twig',
97
        ]);
98
99 1
        if ($id instanceof SplFileInfo) {
100
            $file = $id;
101 1
            $this->setFile($file);
102
            $id = self::createIdFromFile($file);
103
        }
104
105
        parent::__construct($id);
106
    }
107 1
108
    /**
109 1
     * {@inheritdoc}
110 1
     */
111
    public function setId(string $id): self
112
    {
113 1
        return parent::setId($id);
114
    }
115
116
    /**
117
     * toString magic method to prevent Twig get_attribute fatal error.
118
     *
119 1
     * @return string
120
     */
121 1
    public function __toString()
122 1
    {
123
        return $this->getId();
124 1
    }
125
126 1
    /**
127
     * Turns a path (string) into a slug (URI).
128 1
     */
129 1
    public static function slugify(string $path): string
130
    {
131
        if (!self::$slugifier instanceof Slugify) {
132 1
            self::$slugifier = Slugify::create([
133
                'regexp' => self::SLUGIFY_PATTERN,
134
            ]);
135 1
        }
136 1
137
        // Use the Chinese ruleset only when the path contains Chinese (Han) characters.
138
        $options = [];
139 1
        if (preg_match('/\p{Han}/u', $path)) {
140
            $options['ruleset'] = 'chinese';
141
        }
142
        return self::$slugifier->slugify($path, $options);
143
    }
144
145 1
    /**
146
     * Returns the ID of a page without language.
147 1
     */
148 1
    public function getIdWithoutLang(): string
149 1
    {
150
        $langPrefix = $this->getVariable('language') . '/';
151
        if ($this->hasVariable('language') && Util\Str::startsWith($this->getId(), $langPrefix)) {
152 1
            return substr($this->getId(), \strlen($langPrefix));
153
        }
154
155
        return $this->getId();
156
    }
157
158 1
    /**
159
     * Set file.
160 1
     */
161 1
    public function setFile(SplFileInfo $file): self
162
    {
163
        $this->file = $file;
164
        $this->setVirtual(false);
165
166 1
        /*
167 1
         * File path components
168 1
         */
169
        $fileRelativePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath());
170 1
        $fileExtension = $this->file->getExtension();
171
        $fileName = $this->file->getBasename('.' . $fileExtension);
172 1
        // renames "README" to "index"
173 1
        $fileName = strtolower($fileName) == 'readme' ? 'index' : $fileName;
174
        // case of "index" = home page
175
        if (empty($this->file->getRelativePath()) && PrefixSuffix::sub($fileName) == 'index') {
176
            $this->setType(Type::HOMEPAGE->value);
177
        }
178 1
        /*
179 1
         * Set page properties and variables
180 1
         */
181 1
        $this->setFolder($fileRelativePath);
182 1
        $this->setSlug($fileName);
183 1
        $this->setPath($this->getFolder() . '/' . $this->getSlug());
184 1
        $this->setVariables([
185 1
            'title'    => PrefixSuffix::sub($fileName),
186 1
            'date'     => (new \DateTime())->setTimestamp($this->file->getMTime()),
187
            'updated'  => (new \DateTime())->setTimestamp($this->file->getMTime()),
188
            'filepath' => $this->file->getRelativePathname(),
189
        ]);
190
        /*
191 1
         * Set specific variables
192 1
         */
193 1
        // is file has a prefix?
194
        if (PrefixSuffix::hasPrefix($fileName)) {
195 1
            $prefix = PrefixSuffix::getPrefix($fileName);
196 1
            if ($prefix !== null) {
197
                // prefix is an integer: used for sorting
198
                if (is_numeric($prefix)) {
199 1
                    $this->setVariable('weight', (int) $prefix);
200
                }
201
                // prefix is a valid date?
202
                if (Util\Date::isValid($prefix)) {
203
                    $this->setVariable('date', (string) $prefix);
204 1
                }
205 1
            }
206
        }
207
        // is file has a language suffix?
208 1
        if (PrefixSuffix::hasSuffix($fileName)) {
209
            $this->setVariable('language', PrefixSuffix::getSuffix($fileName));
210 1
        }
211
        // set reference between page's translations, even if it exist in only one language
212
        $this->setVariable('langref', $this->getPath());
213
214
        return $this;
215
    }
216 1
217
    /**
218 1
     * Returns file name, with extension.
219
     */
220
    public function getFileName(): ?string
221
    {
222 1
        if ($this->file === null) {
223
            return null;
224
        }
225
226
        return $this->file->getBasename();
227
    }
228 1
229
    /**
230 1
     * Returns file real path.
231 1
     */
232 1
    public function getFilePath(): ?string
233 1
    {
234
        if ($this->file === null) {
235 1
            return null;
236
        }
237
238
        return $this->file->getRealPath() === false ? null : $this->file->getRealPath();
239
    }
240
241 1
    /**
242
     * Parse file content.
243 1
     */
244
    public function parse(): self
245
    {
246
        $parser = new Parser($this->file);
247
        $parsed = $parser->parse();
248
        $this->frontmatter = $parsed->getFrontmatter();
249 1
        $this->body = $parsed->getBody();
250
251 1
        return $this;
252
    }
253
254
    /**
255
     * Get front matter.
256
     */
257 1
    public function getFrontmatter(): ?string
258
    {
259 1
        return $this->frontmatter;
260
    }
261 1
262
    /**
263
     * Get body as raw.
264
     */
265
    public function getBody(): ?string
266
    {
267 1
        return $this->body;
268
    }
269 1
270
    /**
271
     * Set virtual status.
272
     */
273
    public function setVirtual(bool $virtual): self
274
    {
275 1
        $this->virtual = $virtual;
276
277 1
        return $this;
278
    }
279 1
280
    /**
281
     * Is current page is virtual?
282
     */
283
    public function isVirtual(): bool
284
    {
285 1
        return $this->virtual;
286
    }
287 1
288
    /**
289
     * Set page type.
290
     */
291
    public function setType(string $type): self
292
    {
293 1
        $this->type = Type::from($type);
294
295 1
        return $this;
296
    }
297 1
298
    /**
299
     * Get page type.
300
     */
301
    public function getType(): string
302
    {
303 1
        return $this->type->value;
304
    }
305 1
306
    /**
307
     * Set path without slug.
308
     */
309
    public function setFolder(string $folder): self
310
    {
311 1
        $this->folder = self::slugify($folder);
312
313 1
        return $this;
314 1
    }
315
316
    /**
317 1
     * Get path without slug.
318 1
     */
319
    public function getFolder(): ?string
320 1
    {
321
        return $this->folder;
322 1
    }
323
324
    /**
325
     * Set slug.
326
     */
327
    public function setSlug(string $slug): self
328 1
    {
329
        if (!$this->slug) {
330 1
            $slug = self::slugify(PrefixSuffix::sub($slug));
331
        }
332
        // force slug and update path
333
        if ($this->slug && $this->slug != $slug) {
334
            $this->setPath($this->getFolder() . '/' . $slug);
335
        }
336 1
        $this->slug = $slug;
337
338 1
        return $this;
339
    }
340
341 1
    /**
342 1
     * Get slug.
343
     */
344 1
    public function getSlug(): string
345
    {
346
        return $this->slug;
347
    }
348 1
349 1
    /**
350
     * Set path.
351 1
     */
352
    public function setPath(string $path): self
353 1
    {
354
        $path = trim($path, '/');
355
356 1
        // case of homepage
357 1
        if ($path == 'index') {
358
            $this->path = '';
359 1
360
            return $this;
361
        }
362
363 1
        // case of custom sections' index (ie: section/index.md -> section)
364 1
        if (substr($path, -6) == '/index') {
365
            $path = substr($path, 0, \strlen($path) - 6);
366
        }
367 1
        $this->path = $path;
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 pages list.
479
     */
480
    public function setPages(Collection $pages): self
481
    {
482 1
        $this->pages = $pages;
483
484 1
        return $this;
485
    }
486 1
487
    /**
488
     * Get pages list.
489
     */
490
    public function getPages(): ?Collection
491
    {
492 1
        return $this->pages;
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
     * Creates a page ID from a file (based on path).
686
     */
687
    private static function createIdFromFile(SplFileInfo $file): string
688 1
    {
689
        $relativePath = self::slugify(str_replace(DIRECTORY_SEPARATOR, '/', $file->getRelativePath()));
690 1
        $basename = self::slugify(PrefixSuffix::subPrefix($file->getBasename('.' . $file->getExtension())));
691
        // if file is "README.md", ID is "index"
692
        $basename = strtolower($basename) == 'readme' ? 'index' : $basename;
693
        // if file is section's index: "section/index.md", ID is "section"
694
        if (!empty($relativePath) && PrefixSuffix::sub($basename) == 'index') {
695
            // case of a localized section's index: "section/index.fr.md", ID is "fr/section"
696
            if (PrefixSuffix::hasSuffix($basename)) {
697
                return PrefixSuffix::getSuffix($basename) . '/' . $relativePath;
698
            }
699
700
            return $relativePath;
701
        }
702
        // localized page
703
        if (PrefixSuffix::hasSuffix($basename)) {
704
            return trim(Util::joinPath(/** @scrutinizer ignore-type */ PrefixSuffix::getSuffix($basename), $relativePath, PrefixSuffix::sub($basename)), '/');
705
        }
706
707
        return trim(Util::joinPath($relativePath, $basename), '/');
708
    }
709
710
    /**
711
     * Cast "boolean" string (or array of strings) to boolean.
712
     *
713
     * @param mixed $value Value to filter
714
     *
715
     * @return bool|mixed
716
     *
717
     * @see strToBool()
718
     */
719
    private function filterBool(&$value)
720
    {
721
        \Cecil\Util\Str::strToBool($value);
722
        if (\is_array($value)) {
723
            array_walk_recursive($value, '\Cecil\Util\Str::strToBool');
724
        }
725
    }
726
}
727