Passed
Push — feature/config-file ( 80a3c9...c343d6 )
by Arnaud
11:33 queued 07:45
created

Page::setFile()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 53
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 16
nop 1
dl 0
loc 53
rs 8.8817
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Cecil\Collection\Page;
14
15
use Cecil\Collection\Item;
16
use Cecil\Config;
17
use Cecil\Util;
18
use Cocur\Slugify\Slugify;
19
use Symfony\Component\Finder\SplFileInfo;
20
21
/**
22
 * Class Page.
23
 */
24
class Page extends Item
25
{
26
    const SLUGIFY_PATTERN = '/(^\/|[^._a-z0-9\/]|-)+/'; // should be '/^\/|[^_a-z0-9\/]+/'
27
28
    /** @var bool True if page is not created from a Markdown file. */
29
    protected $virtual;
30
    /** @var SplFileInfo */
31
    protected $file;
32
    /** @var string Homepage, Page, Section, etc. */
33
    protected $type;
34
    /** @var string */
35
    protected $folder;
36
    /** @var string */
37
    protected $slug;
38
    /** @var string folder + slug */
39
    protected $path;
40
    /** @var string */
41
    protected $section;
42
    /** @var string */
43
    protected $frontmatter;
44
    /** @var string Body before conversion. */
45
    protected $body;
46
    /** @var string Body after Markdown conversion. */
47
    protected $html;
48
    /** @var Slugify */
49
    private static $slugifier;
50
51
    /**
52
     * @param string $id
53
     */
54
    public function __construct(string $id)
55
    {
56
        parent::__construct($id);
57
        $this->setVirtual(true);
58
        $this->setType(Type::PAGE);
59
        // default variables
60
        $this->setVariables([
61
            'title'            => 'Page Title',
62
            'date'             => new \DateTime(),
63
            'updated'          => new \DateTime(),
64
            'weight'           => null,
65
            'filepath'         => null,
66
            'published'        => true,
67
            'content_template' => 'page.content.twig',
68
        ]);
69
    }
70
71
    /**
72
     * Turns a path (string) into a slug (URI).
73
     *
74
     * @param string $path
75
     *
76
     * @return string
77
     */
78
    public static function slugify(string $path): string
79
    {
80
        if (!self::$slugifier instanceof Slugify) {
81
            self::$slugifier = Slugify::create(['regexp' => self::SLUGIFY_PATTERN]);
82
        }
83
84
        return self::$slugifier->slugify($path);
85
    }
86
87
    /**
88
     * Creates the ID from the file.
89
     *
90
     * @param SplFileInfo $file
91
     *
92
     * @return string
93
     */
94
    public static function createId(SplFileInfo $file): string
95
    {
96
        $relativepath = self::slugify(str_replace(DIRECTORY_SEPARATOR, '/', $file->getRelativePath()));
97
        $basename = self::slugify(PrefixSuffix::subPrefix($file->getBasename('.'.$file->getExtension())));
98
99
        // case of "README" -> index
100
        if (strtolower($basename) == 'readme') {
101
            $basename = 'index';
102
        }
103
104
        // case of section's index: "section/index" -> "section"
105
        if (!empty($relativepath) && $basename == 'index') {
106
            return $relativepath;
107
        }
108
109
        return trim(Util::joinPath($relativepath, $basename), '/');
110
    }
111
112
    /**
113
     * Set file.
114
     *
115
     * @param SplFileInfo $file
116
     *
117
     * @return self
118
     */
119
    public function setFile(SplFileInfo $file): self
120
    {
121
        $this->setVirtual(false);
122
        $this->file = $file;
123
124
        /*
125
         * File path components
126
         */
127
        $fileRelativePath = str_replace(DIRECTORY_SEPARATOR, '/', $this->file->getRelativePath());
128
        $fileExtension = $this->file->getExtension();
129
        $fileName = $this->file->getBasename('.'.$fileExtension);
130
        // case of "README" -> index
131
        if (strtolower($fileName) == 'readme') {
132
            $fileName = 'index';
133
        }
134
        /*
135
         * Set protected variables
136
         */
137
        $this->setFolder($fileRelativePath); // ie: "blog"
138
        $this->setSlug($fileName); // ie: "post-1"
139
        $this->setPath($this->getFolder().'/'.$this->getSlug()); // ie: "blog/post-1"
140
        /*
141
         * Set default variables
142
         */
143
        $this->setVariables([
144
            'title'    => PrefixSuffix::sub($fileName),
145
            'date'     => (new \DateTime())->setTimestamp($this->file->getCTime()),
146
            'updated'  => (new \DateTime())->setTimestamp($this->file->getMTime()),
147
            'filepath' => $this->file->getRelativePathname(),
148
        ]);
149
        /*
150
         * Set specific variables
151
         */
152
        // is file has a prefix?
153
        if (PrefixSuffix::hasPrefix($fileName)) {
154
            $prefix = PrefixSuffix::getPrefix($fileName);
155
            if ($prefix !== null) {
156
                // prefix is a valid date?
157
                if (Util::isDateValid($prefix)) {
158
                    $this->setVariable('date', (string) $prefix);
159
                } else {
160
                    // prefix is an integer: used for sorting
161
                    $this->setVariable('weight', (int) $prefix);
162
                }
163
            }
164
        }
165
        // is file has a suffix?
166
        if (PrefixSuffix::hasSuffix($fileName)) {
167
            $this->setVariable('language', PrefixSuffix::getSuffix($fileName));
168
        }
169
        $this->setVariable('langref', PrefixSuffix::sub($fileName));
170
171
        return $this;
172
    }
173
174
    /**
175
     * Parse file content.
176
     *
177
     * @return self
178
     */
179
    public function parse(): self
180
    {
181
        $parser = new Parser($this->file);
182
        $parsed = $parser->parse();
183
        $this->frontmatter = $parsed->getFrontmatter();
184
        $this->body = $parsed->getBody();
185
186
        return $this;
187
    }
188
189
    /**
190
     * Get frontmatter.
191
     *
192
     * @return string|null
193
     */
194
    public function getFrontmatter(): ?string
195
    {
196
        return $this->frontmatter;
197
    }
198
199
    /**
200
     * Get body as raw.
201
     *
202
     * @return string
203
     */
204
    public function getBody(): ?string
205
    {
206
        return $this->body;
207
    }
208
209
    /**
210
     * Set virtual status.
211
     *
212
     * @param bool $virtual
213
     *
214
     * @return self
215
     */
216
    public function setVirtual(bool $virtual): self
217
    {
218
        $this->virtual = $virtual;
219
220
        return $this;
221
    }
222
223
    /**
224
     * Is current page is virtual?
225
     *
226
     * @return bool
227
     */
228
    public function isVirtual(): bool
229
    {
230
        return $this->virtual;
231
    }
232
233
    /**
234
     * Set page type.
235
     *
236
     * @param string $type
237
     *
238
     * @return self
239
     */
240
    public function setType(string $type): self
241
    {
242
        $this->type = new Type($type);
243
244
        return $this;
245
    }
246
247
    /**
248
     * Get page type.
249
     *
250
     * @return string
251
     */
252
    public function getType(): string
253
    {
254
        return (string) $this->type;
255
    }
256
257
    /**
258
     * Set path without slug.
259
     *
260
     * @param string $folder
261
     *
262
     * @return self
263
     */
264
    public function setFolder(string $folder): self
265
    {
266
        $this->folder = self::slugify($folder);
267
268
        return $this;
269
    }
270
271
    /**
272
     * Get path without slug.
273
     *
274
     * @return string|null
275
     */
276
    public function getFolder(): ?string
277
    {
278
        return $this->folder;
279
    }
280
281
    /**
282
     * Set slug.
283
     *
284
     * @param string $slug
285
     *
286
     * @return self
287
     */
288
    public function setSlug(string $slug): self
289
    {
290
        if (!$this->slug) {
291
            $slug = self::slugify(PrefixSuffix::sub($slug));
292
        }
293
        // force slug and update path
294
        if ($this->slug && $this->slug != $slug) {
295
            $this->setPath($this->getFolder().'/'.$slug);
296
        }
297
        $this->slug = $slug;
298
299
        return $this;
300
    }
301
302
    /**
303
     * Get slug.
304
     *
305
     * @return string
306
     */
307
    public function getSlug(): string
308
    {
309
        return $this->slug;
310
    }
311
312
    /**
313
     * Set path.
314
     *
315
     * @param string $path
316
     *
317
     * @return self
318
     */
319
    public function setPath(string $path): self
320
    {
321
        $path = self::slugify(PrefixSuffix::sub($path));
322
323
        // special case: homepage
324
        if ($path == 'index') {
325
            $this->path = '';
326
327
            return $this;
328
        }
329
330
        // special case: custom section index (ie: content/section/index.md)
331
        if (substr($path, -6) == '/index') {
332
            $path = substr($path, 0, strlen($path) - 6);
333
        }
334
        $this->path = $path;
335
336
        // explode path by slash
337
        $lastslash = strrpos($this->path, '/');
338
        if ($lastslash === false) {
339
            $this->section = null;
340
            $this->folder = null;
341
            $this->slug = $this->path;
342
343
            return $this;
344
        }
345
        if (!$this->virtual) {
346
            $this->section = explode('/', $this->path)[0];
347
        }
348
        $this->folder = substr($this->path, 0, $lastslash);
349
        $this->slug = substr($this->path, -(strlen($this->path) - $lastslash - 1));
350
351
        return $this;
352
    }
353
354
    /**
355
     * Get path.
356
     *
357
     * @return string|null
358
     */
359
    public function getPath(): ?string
360
    {
361
        return $this->path;
362
    }
363
364
    /**
365
     * @see getPath()
366
     *
367
     * @return string|null
368
     */
369
    public function getPathname(): ?string
370
    {
371
        return $this->getPath();
372
    }
373
374
    /**
375
     * Set section.
376
     *
377
     * @param string $section
378
     *
379
     * @return self
380
     */
381
    public function setSection(string $section): self
382
    {
383
        $this->section = $section;
384
385
        return $this;
386
    }
387
388
    /**
389
     * Get section.
390
     *
391
     * @return string|null
392
     */
393
    public function getSection(): ?string
394
    {
395
        return $this->section;
396
    }
397
398
    /**
399
     * Set body as HTML.
400
     *
401
     * @param string $html
402
     *
403
     * @return self
404
     */
405
    public function setBodyHtml(string $html): self
406
    {
407
        $this->html = $html;
408
409
        return $this;
410
    }
411
412
    /**
413
     * Get body as HTML.
414
     *
415
     * @return string|null
416
     */
417
    public function getBodyHtml(): ?string
418
    {
419
        return $this->html;
420
    }
421
422
    /**
423
     * @see getBodyHtml()
424
     *
425
     * @return string|null
426
     */
427
    public function getContent(): ?string
428
    {
429
        return $this->getBodyHtml();
430
    }
431
432
    /**
433
     * Returns the path to the output (rendered) file.
434
     *
435
     * Use cases:
436
     * - default: path + suffix + extension (ie: blog/post-1/index.html)
437
     * - subpath: path + subpath + suffix + extension (ie: blog/post-1/amp/index.html)
438
     * - ugly: path + extension (ie: 404.html, sitemap.xml, robots.txt)
439
     * - path only (ie: _redirects)
440
     * - i18n: language + path + suffix + extension (ie: fr/blog/page/index.html)
441
     *
442
     * @param string      $format
443
     * @param Config|null $config
444
     *
445
     * @return string
446
     */
447
    public function getOutputFile(string $format, Config $config = null): string
448
    {
449
        $path = $this->getPath();
450
        $subpath = '';
451
        $suffix = '/index';
452
        $extension = 'html';
453
        $uglyurl = (bool) $this->getVariable('uglyurl');
454
        $language = $this->getVariable('language');
455
456
        // site config
457
        if ($config) {
458
            $subpath = (string) $config->getOutputFormatProperty($format, 'subpath');
459
            $suffix = (string) $config->getOutputFormatProperty($format, 'suffix');
460
            $extension = (string) $config->getOutputFormatProperty($format, 'extension');
461
        }
462
463
        // if ugly URL: not suffix
464
        if ($uglyurl) {
465
            $suffix = null;
466
        }
467
        // formatting strings
468
        if ($subpath) {
469
            $subpath = \sprintf('/%s', ltrim($subpath, '/'));
470
        }
471
        if ($suffix) {
472
            $suffix = \sprintf('/%s', ltrim($suffix, '/'));
473
        }
474
        if ($extension) {
475
            $extension = \sprintf('.%s', $extension);
476
        }
477
        if ($language !== null) {
478
            $language = \sprintf('%s/', $language);
479
        }
480
        // homepage special case: path = 'index'
481
        if (empty($path) && empty($suffix)) {
482
            $path = 'index';
483
        }
484
485
        return $language.$path.$subpath.$suffix.$extension;
486
    }
487
488
    /**
489
     * Returns the public URL.
490
     *
491
     * @param string      $format
492
     * @param Config|null $config
493
     *
494
     * @return string
495
     */
496
    public function getUrl(string $format = 'html', Config $config = null): string
497
    {
498
        $uglyurl = $this->getVariable('uglyurl') ? true : false;
499
        $output = $this->getOutputFile($format, $config);
500
501
        if (!$uglyurl) {
502
            $output = str_replace('index.html', '', $output);
503
        }
504
505
        return $output;
506
    }
507
508
    /*
509
     * Helpers to set and get variables.
510
     */
511
512
    /**
513
     * Set an array as variables.
514
     *
515
     * @param array $variables
516
     *
517
     * @throws \Exception
518
     *
519
     * @return self
520
     */
521
    public function setVariables(array $variables): self
522
    {
523
        foreach ($variables as $key => $value) {
524
            $this->setVariable($key, $value);
525
        }
526
527
        return $this;
528
    }
529
530
    /**
531
     * Get all variables.
532
     *
533
     * @return array
534
     */
535
    public function getVariables(): array
536
    {
537
        return $this->properties;
538
    }
539
540
    /**
541
     * Set a variable.
542
     *
543
     * @param $name
544
     * @param $value
545
     *
546
     * @throws \Exception
547
     *
548
     * @return self
549
     */
550
    public function setVariable($name, $value): self
551
    {
552
        if (is_bool($value)) {
553
            $value = $value ?: 0;
554
        }
555
        switch ($name) {
556
            case 'date':
557
                try {
558
                    $date = Util::dateToDatetime($value);
559
                } catch (\Exception $e) {
560
                    throw new \Exception(sprintf(
561
                        'Expected date format (ie: "2012-10-08") for "date" in "%s" instead of "%s"',
562
                        $this->getId(),
563
                        $value
564
                    ));
565
                }
566
                $this->offsetSet('date', $date);
567
                break;
568
            case 'draft':
569
                if ($value === true) {
570
                    $this->offsetSet('published', false);
571
                }
572
                break;
573
            case 'path':
574
            case 'slug':
575
                $slugify = self::slugify($value);
576
                if ($value != $slugify) {
577
                    throw new \Exception(sprintf(
578
                        '"%s" variable should be "%s" (not "%s") in "%s"',
579
                        $name,
580
                        $slugify,
581
                        $value,
582
                        $this->getId()
583
                    ));
584
                }
585
                /** @see setPath() */
586
                /** @see setSlug() */
587
                $method = 'set'.\ucfirst($name);
588
                $this->$method($value);
589
                break;
590
            default:
591
                $this->offsetSet($name, $value);
592
        }
593
594
        return $this;
595
    }
596
597
    /**
598
     * Is variable exists?
599
     *
600
     * @param string $name
601
     *
602
     * @return bool
603
     */
604
    public function hasVariable(string $name): bool
605
    {
606
        return $this->offsetExists($name);
607
    }
608
609
    /**
610
     * Get a variable.
611
     *
612
     * @param string $name
613
     *
614
     * @return mixed|null
615
     */
616
    public function getVariable(string $name)
617
    {
618
        if ($this->offsetExists($name)) {
619
            return $this->offsetGet($name);
620
        }
621
    }
622
623
    /**
624
     * Unset a variable.
625
     *
626
     * @param string $name
627
     *
628
     * @return self
629
     */
630
    public function unVariable(string $name): self
631
    {
632
        if ($this->offsetExists($name)) {
633
            $this->offsetUnset($name);
634
        }
635
636
        return $this;
637
    }
638
}
639