Page::getPaginator()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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
    /** @var Slugify */
78
    private static $slugifier;
79
80 1
    public function __construct(mixed $id)
81
    {
82 1
        if (!\is_string($id) && !$id instanceof SplFileInfo) {
83
            throw new RuntimeException('Create a page with a string ID or a SplFileInfo.');
84
        }
85
86
        // set default properties and variables
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 1
            'updated'          => new \DateTime(),
93 1
            'weight'           => null,
94 1
            'filepath'         => null,
95 1
            'published'        => true,
96 1
            'content_template' => 'page.content.twig',
97 1
        ]);
98
99
        // if file, create ID from its pathname
100 1
        if ($id instanceof SplFileInfo) {
101 1
            $file = $id;
102 1
            $this->setFile($file);
103 1
            $id = self::createIdFromFile($file);
104
        }
105
106 1
        parent::__construct($id);
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112 1
    public function setId(string $id): self
113
    {
114 1
        return parent::setId($id);
115
    }
116
117
    /**
118
     * toString magic method to prevent Twig get_attribute fatal error.
119
     *
120
     * @return string
121
     */
122 1
    public function __toString()
123
    {
124 1
        return $this->getId();
125
    }
126
127
    /**
128
     * Turns a path (string) into a slug (URI).
129
     */
130 1
    public static function slugify(string $path): string
131
    {
132 1
        if (!self::$slugifier instanceof Slugify) {
133 1
            self::$slugifier = Slugify::create(['regexp' => self::SLUGIFY_PATTERN]);
134
        }
135
136 1
        return self::$slugifier->slugify($path);
137
    }
138
139
    /**
140
     * Returns the ID of a page without language.
141
     */
142 1
    public function getIdWithoutLang(): string
143
    {
144 1
        $langPrefix = $this->getVariable('language') . '/';
145 1
        if ($this->hasVariable('language') && Util\Str::startsWith($this->getId(), $langPrefix)) {
146 1
            return substr($this->getId(), \strlen($langPrefix));
147
        }
148
149 1
        return $this->getId();
150
    }
151
152
    /**
153
     * Set file.
154
     */
155 1
    public function setFile(SplFileInfo $file): self
156
    {
157 1
        $this->file = $file;
158
159 1
        $relativePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath());
160 1
        $filename = $this->file->getFilenameWithoutExtension();
161
        // renames "README" to "index"
162 1
        $filename = strtolower(PrefixSuffix::sub($filename)) == 'readme' ? 'index' : $filename;
163
164
        // set properties
165 1
        $this->setVirtual(false);
166 1
        $this->setFolder($relativePath);
167 1
        $this->setSlug($filename);
168 1
        $this->setPath($this->getFolder() . '/' . $this->getSlug());
169
        // if "index" : type = section or homepage
170 1
        if (PrefixSuffix::sub($filename) == 'index') {
171
            // section by default
172 1
            $this->setType(Type::SECTION->value);
173
            // homepage
174 1
            if (empty($this->file->getRelativePath())) {
175 1
                $this->setType(Type::HOMEPAGE->value);
176
            }
177
        }
178
        // set variables
179 1
        $this->setVariables([
180 1
            'title'    => PrefixSuffix::sub($filename),
181 1
            'date'     => (new \DateTime())->setTimestamp($this->file->getMTime()),
182 1
            'updated'  => (new \DateTime())->setTimestamp($this->file->getMTime()),
183 1
            'filepath' => $this->file->getRelativePathname(),
184 1
        ]);
185
        // if prefix : set weight or date
186 1
        if (PrefixSuffix::hasPrefix($filename)) {
187 1
            $prefix = PrefixSuffix::getPrefix($filename);
188 1
            if ($prefix !== null) {
189
                // prefix is an integer: weight (used for sorting)
190 1
                if (is_numeric($prefix)) {
191 1
                    $this->setVariable('weight', (int) $prefix);
192
                }
193
                // prefix is a valid date?
194 1
                if (Util\Date::isValid($prefix)) {
195 1
                    $this->setVariable('date', (string) $prefix);
196
                }
197
            }
198
        }
199
        // if suffix : set language
200 1
        if (PrefixSuffix::hasSuffix($filename)) {
201 1
            $this->setVariable('language', PrefixSuffix::getSuffix($filename));
202
        }
203
        // set reference between page's translations (even if it exist in only one language)
204 1
        $this->setVariable('langref', $this->getPath());
205
206 1
        return $this;
207
    }
208
209
    /**
210
     * Returns file name, with extension.
211
     */
212
    public function getFileName(): ?string
213
    {
214
        if ($this->file === null) {
215
            return null;
216
        }
217
218
        return $this->file->getBasename();
219
    }
220
221
    /**
222
     * Returns file real path.
223
     */
224 1
    public function getFilePath(): ?string
225
    {
226 1
        if ($this->file === null) {
227
            return null;
228
        }
229
230 1
        return $this->file->getRealPath() === false ? null : $this->file->getRealPath();
231
    }
232
233
    /**
234
     * Parse file content.
235
     */
236 1
    public function parse(): self
237
    {
238 1
        $parser = new Parser($this->file);
239 1
        $parsed = $parser->parse();
240 1
        $this->frontmatter = $parsed->getFrontmatter();
241 1
        $this->body = $parsed->getBody();
242
243 1
        return $this;
244
    }
245
246
    /**
247
     * Get front matter.
248
     */
249 1
    public function getFrontmatter(): ?string
250
    {
251 1
        return $this->frontmatter;
252
    }
253
254
    /**
255
     * Get body as raw.
256
     */
257 1
    public function getBody(): ?string
258
    {
259 1
        return $this->body;
260
    }
261
262
    /**
263
     * Set virtual status.
264
     */
265 1
    public function setVirtual(bool $virtual): self
266
    {
267 1
        $this->virtual = $virtual;
268
269 1
        return $this;
270
    }
271
272
    /**
273
     * Is current page is virtual?
274
     */
275 1
    public function isVirtual(): bool
276
    {
277 1
        return $this->virtual;
278
    }
279
280
    /**
281
     * Set page type.
282
     */
283 1
    public function setType(string $type): self
284
    {
285 1
        $this->type = Type::from($type);
286
287 1
        return $this;
288
    }
289
290
    /**
291
     * Get page type.
292
     */
293 1
    public function getType(): string
294
    {
295 1
        return $this->type->value;
296
    }
297
298
    /**
299
     * Set path without slug.
300
     */
301 1
    public function setFolder(string $folder): self
302
    {
303 1
        $this->folder = self::slugify($folder);
304
305 1
        return $this;
306
    }
307
308
    /**
309
     * Get path without slug.
310
     */
311 1
    public function getFolder(): ?string
312
    {
313 1
        return $this->folder;
314
    }
315
316
    /**
317
     * Set slug.
318
     */
319 1
    public function setSlug(string $slug): self
320
    {
321 1
        if (!$this->slug) {
322 1
            $slug = self::slugify(PrefixSuffix::sub($slug));
323
        }
324
        // force slug and update path
325 1
        if ($this->slug && $this->slug != $slug) {
326 1
            $this->setPath($this->getFolder() . '/' . $slug);
327
        }
328 1
        $this->slug = $slug;
329
330 1
        return $this;
331
    }
332
333
    /**
334
     * Get slug.
335
     */
336 1
    public function getSlug(): string
337
    {
338 1
        return $this->slug;
339
    }
340
341
    /**
342
     * Set path.
343
     */
344 1
    public function setPath(string $path): self
345
    {
346 1
        $path = trim($path, '/');
347
348
        // homepage : path is empty
349 1
        if ($path == 'index') {
350 1
            $this->path = '';
351
352 1
            return $this;
353
        }
354
355
        // section/index : path = section
356 1
        if (substr($path, -6) == '/index') {
357 1
            $path = substr($path, 0, \strlen($path) - 6);
358
        }
359 1
        $this->path = $path;
360
361 1
        $lastslash = strrpos($this->path, '/');
362
363
        // top-level pages : slug = path
364 1
        if ($lastslash === false) {
365 1
            $this->slug = $this->path;
366
367 1
            return $this;
368
        }
369
370
        // set section
371 1
        if (!$this->virtual && $this->getSection() === null) {
372 1
            $this->section = explode('/', $this->path)[0];
373
        }
374
        // set/update folder and slug
375 1
        $this->folder = substr($this->path, 0, $lastslash);
376 1
        $this->slug = substr($this->path, -(\strlen($this->path) - $lastslash - 1));
377
378 1
        return $this;
379
    }
380
381
    /**
382
     * Get path.
383
     */
384 1
    public function getPath(): ?string
385
    {
386 1
        return $this->path;
387
    }
388
389
    /**
390
     * @see getPath()
391
     */
392
    public function getPathname(): ?string
393
    {
394
        return $this->getPath();
395
    }
396
397
    /**
398
     * Set section.
399
     */
400 1
    public function setSection(string $section): self
401
    {
402 1
        $this->section = $section;
403
404 1
        return $this;
405
    }
406
407
    /**
408
     * Get section.
409
     */
410 1
    public function getSection(): ?string
411
    {
412 1
        return !empty($this->section) ? $this->section : null;
413
    }
414
415
    /**
416
     * Unset section.
417
     */
418
    public function unSection(): self
419
    {
420
        $this->section = null;
421
422
        return $this;
423
    }
424
425
    /**
426
     * Set body as HTML.
427
     */
428 1
    public function setBodyHtml(string $html): self
429
    {
430 1
        $this->html = $html;
431
432 1
        return $this;
433
    }
434
435
    /**
436
     * Get body as HTML.
437
     */
438 1
    public function getBodyHtml(): ?string
439
    {
440 1
        return $this->html;
441
    }
442
443
    /**
444
     * @see getBodyHtml()
445
     */
446 1
    public function getContent(): ?string
447
    {
448 1
        return $this->getBodyHtml();
449
    }
450
451
    /**
452
     * Add rendered.
453
     */
454 1
    public function addRendered(array $rendered): self
455
    {
456 1
        $this->rendered += $rendered;
457
458 1
        return $this;
459
    }
460
461
    /**
462
     * Get rendered.
463
     */
464 1
    public function getRendered(): array
465
    {
466 1
        return $this->rendered;
467
    }
468
469
    /**
470
     * Set pages list.
471
     */
472 1
    public function setPages(Collection $pages): self
473
    {
474 1
        $this->pages = $pages;
475
476 1
        return $this;
477
    }
478
479
    /**
480
     * Get pages list.
481
     */
482 1
    public function getPages(): ?Collection
483
    {
484 1
        return $this->pages;
485
    }
486
487
    /**
488
     * Set paginator.
489
     */
490 1
    public function setPaginator(array $paginator): self
491
    {
492 1
        $this->paginator = $paginator;
493
494 1
        return $this;
495
    }
496
497
    /**
498
     * Get paginator.
499
     */
500 1
    public function getPaginator(): array
501
    {
502 1
        return $this->paginator;
503
    }
504
505
    /**
506
     * Paginator backward compatibility.
507
     */
508
    public function getPagination(): array
509
    {
510
        return $this->getPaginator();
511
    }
512
513
    /**
514
     * Set vocabulary terms.
515
     */
516 1
    public function setTerms(\Cecil\Collection\Taxonomy\Vocabulary $terms): self
517
    {
518 1
        $this->terms = $terms;
519
520 1
        return $this;
521
    }
522
523
    /**
524
     * Get vocabulary terms.
525
     */
526 1
    public function getTerms(): \Cecil\Collection\Taxonomy\Vocabulary
527
    {
528 1
        return $this->terms;
529
    }
530
531
    /*
532
     * Helpers to set and get variables.
533
     */
534
535
    /**
536
     * Set an array as variables.
537
     *
538
     * @throws RuntimeException
539
     */
540 1
    public function setVariables(array $variables): self
541
    {
542 1
        foreach ($variables as $key => $value) {
543 1
            $this->setVariable($key, $value);
544
        }
545
546 1
        return $this;
547
    }
548
549
    /**
550
     * Get all variables.
551
     */
552 1
    public function getVariables(): array
553
    {
554 1
        return $this->properties;
555
    }
556
557
    /**
558
     * Set a variable.
559
     *
560
     * @param string $name  Name of the variable
561
     * @param mixed  $value Value of the variable
562
     *
563
     * @throws RuntimeException
564
     */
565 1
    public function setVariable(string $name, $value): self
566
    {
567 1
        $this->filterBool($value);
568
        switch ($name) {
569 1
            case 'date':
570 1
            case 'updated':
571 1
            case 'lastmod':
572
                try {
573 1
                    $date = Util\Date::toDatetime($value);
574
                } catch (\Exception) {
575
                    throw new \Exception(\sprintf('The value of "%s" is not a valid date: "%s".', $name, var_export($value, true)));
576
                }
577 1
                $this->offsetSet($name == 'lastmod' ? 'updated' : $name, $date);
578 1
                break;
579
580 1
            case 'schedule':
581
                /*
582
                 * publish: 2012-10-08
583
                 * expiry: 2012-10-09
584
                 */
585 1
                $this->offsetSet('published', false);
586 1
                if (\is_array($value)) {
587 1
                    if (\array_key_exists('publish', $value) && Util\Date::toDatetime($value['publish']) <= Util\Date::toDatetime('now')) {
588 1
                        $this->offsetSet('published', true);
589
                    }
590 1
                    if (\array_key_exists('expiry', $value) && Util\Date::toDatetime($value['expiry']) >= Util\Date::toDatetime('now')) {
591
                        $this->offsetSet('published', true);
592
                    }
593
                }
594 1
                break;
595 1
            case 'draft':
596
                // draft: true = published: false
597 1
                if ($value === true) {
598 1
                    $this->offsetSet('published', false);
599
                }
600 1
                break;
601 1
            case 'path':
602 1
            case 'slug':
603 1
                $slugify = self::slugify((string) $value);
604 1
                if ($value != $slugify) {
605
                    throw new RuntimeException(\sprintf('"%s" variable should be "%s" (not "%s") in "%s".', $name, $slugify, (string) $value, $this->getId()));
606
                }
607 1
                $method = 'set' . ucfirst($name);
608 1
                $this->$method($value);
609 1
                break;
610
            default:
611 1
                $this->offsetSet($name, $value);
612
        }
613
614 1
        return $this;
615
    }
616
617
    /**
618
     * Is variable exists?
619
     *
620
     * @param string $name Name of the variable
621
     */
622 1
    public function hasVariable(string $name): bool
623
    {
624 1
        return $this->offsetExists($name);
625
    }
626
627
    /**
628
     * Get a variable.
629
     *
630
     * @param string     $name    Name of the variable
631
     * @param mixed|null $default Default value
632
     *
633
     * @return mixed|null
634
     */
635 1
    public function getVariable(string $name, $default = null)
636
    {
637 1
        if ($this->offsetExists($name)) {
638 1
            return $this->offsetGet($name);
639
        }
640
641 1
        return $default;
642
    }
643
644
    /**
645
     * Unset a variable.
646
     *
647
     * @param string $name Name of the variable
648
     */
649 1
    public function unVariable(string $name): self
650
    {
651 1
        if ($this->offsetExists($name)) {
652 1
            $this->offsetUnset($name);
653
        }
654
655 1
        return $this;
656
    }
657
658
    /**
659
     * Set front matter (only) variables.
660
     */
661 1
    public function setFmVariables(array $variables): self
662
    {
663 1
        $this->fmVariables = $variables;
664
665 1
        return $this;
666
    }
667
668
    /**
669
     * Get front matter variables.
670
     */
671 1
    public function getFmVariables(): array
672
    {
673 1
        return $this->fmVariables;
674
    }
675
676
    /**
677
     * Creates a page ID from a file (based on path).
678
     */
679 1
    private static function createIdFromFile(SplFileInfo $file): string
680
    {
681 1
        $relativePath = self::slugify(str_replace(DIRECTORY_SEPARATOR, '/', $file->getRelativePath()));
682 1
        $filename = self::slugify(PrefixSuffix::subPrefix($file->getFilenameWithoutExtension()));
683
        // if file is "README.md", ID is "index"
684 1
        $filename = strtolower($filename) == 'readme' ? 'index' : $filename;
685
        // if file is section's index (ie: if file is "section/index.md", ID is "section")
686 1
        if (!empty($relativePath) && PrefixSuffix::sub($filename) == 'index') {
687
            // localized section (ie: if file is "section/index.fr.md", ID is "fr/section")
688 1
            if (PrefixSuffix::hasSuffix($filename)) {
689 1
                return PrefixSuffix::getSuffix($filename) . '/' . $relativePath;
690
            }
691
692 1
            return $relativePath;
693
        }
694
        // localized page (ie: if file is "page.fr.md", ID is "fr/page")
695 1
        if (PrefixSuffix::hasSuffix($filename)) {
696 1
            return trim(Util::joinPath(PrefixSuffix::getSuffix($filename), $relativePath, PrefixSuffix::sub($filename)), '/');
0 ignored issues
show
Bug introduced by
It seems like Cecil\Collection\Page\Pr...x::getSuffix($filename) can also be of type null; however, parameter $path of Cecil\Util::joinPath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

696
            return trim(Util::joinPath(/** @scrutinizer ignore-type */ PrefixSuffix::getSuffix($filename), $relativePath, PrefixSuffix::sub($filename)), '/');
Loading history...
697
        }
698
699 1
        return trim(Util::joinPath($relativePath, $filename), '/');
700
    }
701
702
    /**
703
     * Cast "boolean" string (or array of strings) to boolean.
704
     *
705
     * @param mixed $value Value to filter
706
     *
707
     * @return bool|mixed
708
     *
709
     * @see strToBool()
710
     */
711 1
    private function filterBool(&$value)
712
    {
713 1
        \Cecil\Util\Str::strToBool($value);
714 1
        if (\is_array($value)) {
715 1
            array_walk_recursive($value, '\Cecil\Util\Str::strToBool');
716
        }
717
    }
718
}
719