• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 7168486434

11 Dec 2023 01:57PM UTC coverage: 83.362% (+0.3%) from 83.077%
7168486434

push

github

ArnaudLigny
refactor: PHP 8 Exception

4 of 17 new or added lines in 8 files covered. (23.53%)

105 existing lines in 2 files now uncovered.

2866 of 3438 relevant lines covered (83.36%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.57
/src/Collection/Page/Page.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
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 Markdown 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 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 Markdown conversion. */
60
    protected $html;
61

62
    /** @var array Output by format */
63
    protected $rendered = [];
64

65
    /** @var \Cecil\Collection\Page\Collection Subpages of a section */
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 Slugify */
75
    private static $slugifier;
76

77
    public function __construct(string $id)
78
    {
79
        parent::__construct($id);
1✔
80
        $this->setVirtual(true);
1✔
81
        $this->setType(Type::PAGE->value);
1✔
82
        // default variables
83
        $this->setVariables([
1✔
84
            'title'            => 'Page Title',
1✔
85
            'date'             => new \DateTime(),
1✔
86
            'updated'          => new \DateTime(),
1✔
87
            'weight'           => null,
1✔
88
            'filepath'         => null,
1✔
89
            'published'        => true,
1✔
90
            'content_template' => 'page.content.twig',
1✔
91
        ]);
1✔
92
    }
93

94
    /**
95
     * toString magic method to prevent Twig get_attribute fatal error.
96
     *
97
     * @return string
98
     */
99
    public function __toString()
100
    {
101
        return $this->getId();
1✔
102
    }
103

104
    /**
105
     * Turns a path (string) into a slug (URI).
106
     */
107
    public static function slugify(string $path): string
108
    {
109
        if (!self::$slugifier instanceof Slugify) {
1✔
110
            self::$slugifier = Slugify::create(['regexp' => self::SLUGIFY_PATTERN]);
1✔
111
        }
112

113
        return self::$slugifier->slugify($path);
1✔
114
    }
115

116
    /**
117
     * Creates the ID from the file path.
118
     */
119
    public static function createIdFromFile(SplFileInfo $file): string
120
    {
121
        $relativePath = self::slugify(str_replace(DIRECTORY_SEPARATOR, '/', $file->getRelativePath()));
1✔
122
        $basename = self::slugify(PrefixSuffix::subPrefix($file->getBasename('.' . $file->getExtension())));
1✔
123
        // if file is "README.md", ID is "index"
124
        $basename = (string) str_ireplace('readme', 'index', $basename);
1✔
125
        // if file is section's index: "section/index.md", ID is "section"
126
        if (!empty($relativePath) && PrefixSuffix::sub($basename) == 'index') {
1✔
127
            // case of a localized section's index: "section/index.fr.md", ID is "fr/section"
128
            if (PrefixSuffix::hasSuffix($basename)) {
1✔
129
                return PrefixSuffix::getSuffix($basename) . '/' . $relativePath;
1✔
130
            }
131

132
            return $relativePath;
1✔
133
        }
134
        // localized page
135
        if (PrefixSuffix::hasSuffix($basename)) {
1✔
136
            return trim(Util::joinPath(PrefixSuffix::getSuffix($basename), $relativePath, PrefixSuffix::sub($basename)), '/');
1✔
137
        }
138

139
        return trim(Util::joinPath($relativePath, $basename), '/');
1✔
140
    }
141

142
    /**
143
     * Returns the ID of a page without language.
144
     */
145
    public function getIdWithoutLang(): string
146
    {
147
        $langPrefix = $this->getVariable('language') . '/';
1✔
148
        if ($this->hasVariable('language') && Util\Str::startsWith($this->getId(), $langPrefix)) {
1✔
149
            return substr($this->getId(), \strlen($langPrefix));
1✔
150
        }
151

152
        return $this->getId();
1✔
153
    }
154

155
    /**
156
     * Set file.
157
     */
158
    public function setFile(SplFileInfo $file): self
159
    {
160
        $this->setVirtual(false);
1✔
161
        $this->file = $file;
1✔
162

163
        /*
164
         * File path components
165
         */
166
        $fileRelativePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath());
1✔
167
        $fileExtension = $this->file->getExtension();
1✔
168
        $fileName = $this->file->getBasename('.' . $fileExtension);
1✔
169
        // case of "README" -> "index"
170
        $fileName = (string) str_ireplace('readme', 'index', $fileName);
1✔
171
        // case of "index" = home page
172
        if (empty($this->file->getRelativePath()) && PrefixSuffix::sub($fileName) == 'index') {
1✔
173
            $this->setType(Type::HOMEPAGE->value);
1✔
174
        }
175
        /*
176
         * Set protected variables
177
         */
178
        $this->setFolder($fileRelativePath); // ie: "blog"
1✔
179
        $this->setSlug($fileName); // ie: "post-1"
1✔
180
        $this->setPath($this->getFolder() . '/' . $this->getSlug()); // ie: "blog/post-1"
1✔
181
        /*
182
         * Set default variables
183
         */
184
        $this->setVariables([
1✔
185
            'title'    => PrefixSuffix::sub($fileName),
1✔
186
            'date'     => (new \DateTime())->setTimestamp($this->file->getMTime()),
1✔
187
            'updated'  => (new \DateTime())->setTimestamp($this->file->getMTime()),
1✔
188
            'filepath' => $this->file->getRelativePathname(),
1✔
189
        ]);
1✔
190
        /*
191
         * Set specific variables
192
         */
193
        // is file has a prefix?
194
        if (PrefixSuffix::hasPrefix($fileName)) {
1✔
195
            $prefix = PrefixSuffix::getPrefix($fileName);
1✔
196
            if ($prefix !== null) {
1✔
197
                // prefix is a valid date?
198
                if (Util\Date::isValid($prefix)) {
1✔
199
                    $this->setVariable('date', (string) $prefix);
1✔
200
                } else {
201
                    // prefix is an integer: used for sorting
202
                    $this->setVariable('weight', (int) $prefix);
1✔
203
                }
204
            }
205
        }
206
        // is file has a language suffix?
207
        if (PrefixSuffix::hasSuffix($fileName)) {
1✔
208
            $this->setVariable('language', PrefixSuffix::getSuffix($fileName));
1✔
209
        }
210
        // set reference between page's translations, even if it exist in only one language
211
        $this->setVariable('langref', $this->getPath());
1✔
212

213
        return $this;
1✔
214
    }
215

216
    /**
217
     * Returns file real path.
218
     */
219
    public function getFilePath(): ?string
220
    {
221
        if ($this->file === null) {
1✔
222
            return null;
×
223
        }
224

225
        return $this->file->getRealPath() === false ? null : $this->file->getRealPath();
1✔
226
    }
227

228
    /**
229
     * Parse file content.
230
     */
231
    public function parse(): self
232
    {
233
        $parser = new Parser($this->file);
1✔
234
        $parsed = $parser->parse();
1✔
235
        $this->frontmatter = $parsed->getFrontmatter();
1✔
236
        $this->body = $parsed->getBody();
1✔
237

238
        return $this;
1✔
239
    }
240

241
    /**
242
     * Get front matter.
243
     */
244
    public function getFrontmatter(): ?string
245
    {
246
        return $this->frontmatter;
1✔
247
    }
248

249
    /**
250
     * Get body as raw.
251
     */
252
    public function getBody(): ?string
253
    {
254
        return $this->body;
1✔
255
    }
256

257
    /**
258
     * Set virtual status.
259
     */
260
    public function setVirtual(bool $virtual): self
261
    {
262
        $this->virtual = $virtual;
1✔
263

264
        return $this;
1✔
265
    }
266

267
    /**
268
     * Is current page is virtual?
269
     */
270
    public function isVirtual(): bool
271
    {
272
        return $this->virtual;
1✔
273
    }
274

275
    /**
276
     * Set page type.
277
     */
278
    public function setType(string $type): self
279
    {
280
        $this->type = Type::from($type);
1✔
281

282
        return $this;
1✔
283
    }
284

285
    /**
286
     * Get page type.
287
     */
288
    public function getType(): string
289
    {
290
        return $this->type->value;
1✔
291
    }
292

293
    /**
294
     * Set path without slug.
295
     */
296
    public function setFolder(string $folder): self
297
    {
298
        $this->folder = self::slugify($folder);
1✔
299

300
        return $this;
1✔
301
    }
302

303
    /**
304
     * Get path without slug.
305
     */
306
    public function getFolder(): ?string
307
    {
308
        return $this->folder;
1✔
309
    }
310

311
    /**
312
     * Set slug.
313
     */
314
    public function setSlug(string $slug): self
315
    {
316
        if (!$this->slug) {
1✔
317
            $slug = self::slugify(PrefixSuffix::sub($slug));
1✔
318
        }
319
        // force slug and update path
320
        if ($this->slug && $this->slug != $slug) {
1✔
321
            $this->setPath($this->getFolder() . '/' . $slug);
1✔
322
        }
323
        $this->slug = $slug;
1✔
324

325
        return $this;
1✔
326
    }
327

328
    /**
329
     * Get slug.
330
     */
331
    public function getSlug(): string
332
    {
333
        return $this->slug;
1✔
334
    }
335

336
    /**
337
     * Set path.
338
     */
339
    public function setPath(string $path): self
340
    {
341
        // case of homepage
342
        if ($path == 'index') {
1✔
343
            $this->path = '';
×
344

345
            return $this;
×
346
        }
347

348
        // case of custom sections' index (ie: content/section/index.md)
349
        if (substr($path, -6) == '/index') {
1✔
350
            $path = substr($path, 0, \strlen($path) - 6);
1✔
351
        }
352
        $this->path = $path;
1✔
353

354
        // case of root pages
355
        $lastslash = strrpos($this->path, '/');
1✔
356
        if ($lastslash === false) {
1✔
357
            $this->slug = $this->path;
1✔
358

359
            return $this;
1✔
360
        }
361

362
        if (!$this->virtual && $this->getSection() === null) {
1✔
363
            $this->section = explode('/', $this->path)[0];
1✔
364
        }
365
        $this->folder = substr($this->path, 0, $lastslash);
1✔
366
        $this->slug = substr($this->path, -(\strlen($this->path) - $lastslash - 1));
1✔
367

368
        return $this;
1✔
369
    }
370

371
    /**
372
     * Get path.
373
     */
374
    public function getPath(): ?string
375
    {
376
        return $this->path;
1✔
377
    }
378

379
    /**
380
     * @see getPath()
381
     */
382
    public function getPathname(): ?string
383
    {
384
        return $this->getPath();
×
385
    }
386

387
    /**
388
     * Set section.
389
     */
390
    public function setSection(string $section): self
391
    {
392
        $this->section = $section;
1✔
393

394
        return $this;
1✔
395
    }
396

397
    /**
398
     * Get section.
399
     */
400
    public function getSection(): ?string
401
    {
402
        return !empty($this->section) ? $this->section : null;
1✔
403
    }
404

405
    /**
406
     * Unset section.
407
     */
408
    public function unSection(): self
409
    {
410
        $this->section = null;
×
411

412
        return $this;
×
413
    }
414

415
    /**
416
     * Set body as HTML.
417
     */
418
    public function setBodyHtml(string $html): self
419
    {
420
        $this->html = $html;
1✔
421

422
        return $this;
1✔
423
    }
424

425
    /**
426
     * Get body as HTML.
427
     */
428
    public function getBodyHtml(): ?string
429
    {
430
        return $this->html;
1✔
431
    }
432

433
    /**
434
     * @see getBodyHtml()
435
     */
436
    public function getContent(): ?string
437
    {
438
        return $this->getBodyHtml();
1✔
439
    }
440

441
    /**
442
     * Add rendered.
443
     */
444
    public function addRendered(array $rendered): self
445
    {
446
        $this->rendered += $rendered;
1✔
447

448
        return $this;
1✔
449
    }
450

451
    /**
452
     * Get rendered.
453
     */
454
    public function getRendered(): array
455
    {
456
        return $this->rendered;
1✔
457
    }
458

459
    /**
460
     * Set Subpages.
461
     */
462
    public function setPages(\Cecil\Collection\Page\Collection $subPages): self
463
    {
464
        $this->subPages = $subPages;
1✔
465

466
        return $this;
1✔
467
    }
468

469
    /**
470
     * Get Subpages.
471
     */
472
    public function getPages(): ?\Cecil\Collection\Page\Collection
473
    {
474
        return $this->subPages;
1✔
475
    }
476

477
    /**
478
     * Set paginator.
479
     */
480
    public function setPaginator(array $paginator): self
481
    {
482
        $this->paginator = $paginator;
1✔
483

484
        return $this;
1✔
485
    }
486

487
    /**
488
     * Get paginator.
489
     */
490
    public function getPaginator(): array
491
    {
492
        return $this->paginator;
1✔
493
    }
494

495
    /**
496
     * Paginator backward compatibility.
497
     */
498
    public function getPagination(): array
499
    {
500
        return $this->getPaginator();
×
501
    }
502

503
    /**
504
     * Set vocabulary terms.
505
     */
506
    public function setTerms(\Cecil\Collection\Taxonomy\Vocabulary $terms): self
507
    {
508
        $this->terms = $terms;
1✔
509

510
        return $this;
1✔
511
    }
512

513
    /**
514
     * Get vocabulary terms.
515
     */
516
    public function getTerms(): \Cecil\Collection\Taxonomy\Vocabulary
517
    {
518
        return $this->terms;
1✔
519
    }
520

521
    /*
522
     * Helpers to set and get variables.
523
     */
524

525
    /**
526
     * Set an array as variables.
527
     *
528
     * @throws RuntimeException
529
     */
530
    public function setVariables(array $variables): self
531
    {
532
        foreach ($variables as $key => $value) {
1✔
533
            $this->setVariable($key, $value);
1✔
534
        }
535

536
        return $this;
1✔
537
    }
538

539
    /**
540
     * Get all variables.
541
     */
542
    public function getVariables(): array
543
    {
544
        return $this->properties;
1✔
545
    }
546

547
    /**
548
     * Set a variable.
549
     *
550
     * @param string $name  Name of the variable
551
     * @param mixed  $value Value of the variable
552
     *
553
     * @throws RuntimeException
554
     */
555
    public function setVariable(string $name, $value): self
556
    {
557
        $this->filterBool($value);
1✔
558
        switch ($name) {
559
            case 'date':
1✔
560
            case 'updated':
1✔
561
            case 'lastmod':
1✔
562
                try {
563
                    $date = Util\Date::toDatetime($value);
1✔
NEW
564
                } catch (\Exception) {
×
565
                    throw new \Exception(sprintf('Expected date format for variable "%s" must be "YYYY-MM-DD" instead of "%s".', $name, (string) $value));
×
566
                }
567
                $this->offsetSet($name == 'lastmod' ? 'updated' : $name, $date);
1✔
568
                break;
1✔
569

570
            case 'schedule':
1✔
571
                /*
572
                 * publish: 2012-10-08
573
                 * expiry: 2012-10-09
574
                 */
575
                $this->offsetSet('published', false);
1✔
576
                if (\is_array($value)) {
1✔
577
                    if (\array_key_exists('publish', $value) && Util\Date::toDatetime($value['publish']) <= Util\Date::toDatetime('now')) {
1✔
578
                        $this->offsetSet('published', true);
1✔
579
                    }
580
                    if (\array_key_exists('expiry', $value) && Util\Date::toDatetime($value['expiry']) >= Util\Date::toDatetime('now')) {
1✔
581
                        $this->offsetSet('published', true);
×
582
                    }
583
                }
584
                break;
1✔
585
            case 'draft':
1✔
586
                // draft: true = published: false
587
                if ($value === true) {
1✔
588
                    $this->offsetSet('published', false);
1✔
589
                }
590
                break;
1✔
591
            case 'path':
1✔
592
            case 'slug':
1✔
593
                $slugify = self::slugify((string) $value);
1✔
594
                if ($value != $slugify) {
1✔
595
                    throw new RuntimeException(sprintf('"%s" variable should be "%s" (not "%s") in "%s".', $name, $slugify, (string) $value, $this->getId()));
×
596
                }
597
                $method = 'set' . ucfirst($name);
1✔
598
                $this->$method($value);
1✔
599
                break;
1✔
600
            default:
601
                $this->offsetSet($name, $value);
1✔
602
        }
603

604
        return $this;
1✔
605
    }
606

607
    /**
608
     * Is variable exists?
609
     *
610
     * @param string $name Name of the variable
611
     */
612
    public function hasVariable(string $name): bool
613
    {
614
        return $this->offsetExists($name);
1✔
615
    }
616

617
    /**
618
     * Get a variable.
619
     *
620
     * @param string     $name    Name of the variable
621
     * @param mixed|null $default Default value
622
     *
623
     * @return mixed|null
624
     */
625
    public function getVariable(string $name, $default = null)
626
    {
627
        if ($this->offsetExists($name)) {
1✔
628
            return $this->offsetGet($name);
1✔
629
        }
630

631
        return $default;
1✔
632
    }
633

634
    /**
635
     * Unset a variable.
636
     *
637
     * @param string $name Name of the variable
638
     */
639
    public function unVariable(string $name): self
640
    {
641
        if ($this->offsetExists($name)) {
1✔
642
            $this->offsetUnset($name);
1✔
643
        }
644

645
        return $this;
1✔
646
    }
647

648
    /**
649
     * Set front matter (only) variables.
650
     */
651
    public function setFmVariables(array $variables): self
652
    {
653
        $this->fmVariables = $variables;
1✔
654

655
        return $this;
1✔
656
    }
657

658
    /**
659
     * Get front matter variables.
660
     */
661
    public function getFmVariables(): array
662
    {
663
        return $this->fmVariables;
1✔
664
    }
665

666
    /**
667
     * Cast "boolean" string (or array of strings) to boolean.
668
     *
669
     * @param mixed $value Value to filter
670
     *
671
     * @return bool|mixed
672
     *
673
     * @see strToBool()
674
     */
675
    private function filterBool(&$value)
676
    {
677
        \Cecil\Util\Str::strToBool($value);
1✔
678
        if (\is_array($value)) {
1✔
679
            array_walk_recursive($value, '\Cecil\Util\Str::strToBool');
1✔
680
        }
681
    }
682

683
    /**
684
     * {@inheritdoc}
685
     */
686
    public function setId(string $id): self
687
    {
688
        return parent::setId($id);
1✔
689
    }
690
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc