Builder::getPages()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 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;
15
16
use Cecil\Collection\Page\Collection as PagesCollection;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Generator\GeneratorManager;
19
use Cecil\Logger\PrintLogger;
20
use Psr\Log\LoggerAwareInterface;
21
use Psr\Log\LoggerInterface;
22
use Symfony\Component\Finder\Finder;
23
24
/**
25
 * The main Cecil builder class.
26
 *
27
 * This class is responsible for building the website by processing various steps,
28
 * managing configuration, and handling content, data, static files, pages, assets,
29
 * menus, taxonomies, and rendering.
30
 * It also provides methods for logging, debugging, and managing build metrics.
31
 *
32
 * ```php
33
 * $config = [
34
 *   'title'   => "My website",
35
 *   'baseurl' => 'https://domain.tld/',
36
 * ];
37
 * Builder::create($config)->build();
38
 * ```
39
 */
40
class Builder implements LoggerAwareInterface
41
{
42
    public const VERSION = '8.x-dev';
43
    public const VERBOSITY_QUIET = -1;
44
    public const VERBOSITY_NORMAL = 0;
45
    public const VERBOSITY_VERBOSE = 1;
46
    public const VERBOSITY_DEBUG = 2;
47
    /**
48
     * Default options for the build process.
49
     * These options can be overridden when calling the build() method.
50
     * - 'drafts': if true, builds drafts too (default: false)
51
     * - 'dry-run': if true, generated files are not saved (default: false)
52
     * - 'page': if specified, only this page is processed (default: '')
53
     * - 'render-subset': limits the render step to a specific subset (default: '')
54
     * @var array<string, bool|string>
55
     * @see \Cecil\Builder::build()
56
     */
57
    public const OPTIONS = [
58
        'drafts'  => false,
59
        'dry-run' => false,
60
        'page'    => '',
61
        'render-subset' => '',
62
    ];
63
    /**
64
     * Steps processed by build(), in order.
65
     * These steps are executed sequentially to build the website.
66
     * Each step is a class that implements the StepInterface.
67
     * @var array<string>
68
     * @see \Cecil\Step\StepInterface
69
     */
70
    public const STEPS = [
71
        'Cecil\Step\Pages\Load',
72
        'Cecil\Step\Data\Load',
73
        'Cecil\Step\StaticFiles\Load',
74
        'Cecil\Step\Pages\Create',
75
        'Cecil\Step\Pages\Convert',
76
        'Cecil\Step\Taxonomies\Create',
77
        'Cecil\Step\Pages\Generate',
78
        'Cecil\Step\Menus\Create',
79
        'Cecil\Step\StaticFiles\Copy',
80
        'Cecil\Step\Pages\Render',
81
        'Cecil\Step\Pages\Save',
82
        'Cecil\Step\Assets\Save',
83
        'Cecil\Step\Optimize\Html',
84
        'Cecil\Step\Optimize\Css',
85
        'Cecil\Step\Optimize\Js',
86
        'Cecil\Step\Optimize\Images',
87
    ];
88
89
    /**
90
     * Configuration object.
91
     * This object holds all the configuration settings for the build process.
92
     * It can be set to an array or a Config instance.
93
     * @var Config|array|null
94
     * @see \Cecil\Config
95
     */
96
    protected $config;
97
    /**
98
     * Logger instance.
99
     * This logger is used to log messages during the build process.
100
     * It can be set to any PSR-3 compliant logger.
101
     * @var LoggerInterface
102
     * @see \Psr\Log\LoggerInterface
103
     * */
104
    protected $logger;
105
    /**
106
     * Debug mode state.
107
     * If true, debug messages are logged.
108
     * @var bool
109
     */
110
    protected $debug = false;
111
    /**
112
     * Build options.
113
     * These options can be passed to the build() method to customize the build process.
114
     * @var array
115
     * @see \Cecil\Builder::OPTIONS
116
     * @see \Cecil\Builder::build()
117
     */
118
    protected $options = [];
119
    /**
120
     * Content files collection.
121
     * This is a Finder instance that collects all the content files (pages, posts, etc.) from the source directory.
122
     * @var Finder
123
     */
124
    protected $content;
125
    /**
126
     * Data collection.
127
     * This is an associative array that holds data loaded from YAML files in the data directory.
128
     * @var array
129
     */
130
    protected $data = [];
131
    /**
132
     * Static files collection.
133
     * This is an associative array that holds static files (like images, CSS, JS) that are copied to the destination directory.
134
     * @var array
135
     */
136
    protected $static = [];
137
    /**
138
     * Pages collection.
139
     * This is a collection of pages that have been processed and are ready for rendering.
140
     * It is an instance of PagesCollection, which is a custom collection class for managing pages.
141
     * @var PagesCollection
142
     */
143
    protected $pages;
144
    /**
145
     * Assets path collection.
146
     * This is an array that holds paths to assets (like CSS, JS, images) that are used in the build process.
147
     * It is used to keep track of assets that need to be processed or copied.
148
     * It can be set to an array of paths or updated with new asset paths.
149
     * @var array
150
     */
151
    protected $assets = [];
152
    /**
153
     * Menus collection.
154
     * This is an associative array that holds menus for different languages.
155
     * Each key is a language code, and the value is a Collection\Menu\Collection instance
156
     * that contains the menu items for that language.
157
     * It is used to manage navigation menus across different languages in the website.
158
     * @var array
159
     * @see \Cecil\Collection\Menu\Collection
160
     */
161
    protected $menus;
162
    /**
163
     * Taxonomies collection.
164
     * This is an associative array that holds taxonomies for different languages.
165
     * Each key is a language code, and the value is a Collection\Taxonomy\Collection instance
166
     * that contains the taxonomy terms for that language.
167
     * It is used to manage taxonomies (like categories, tags) across different languages in the website.
168
     * @var array
169
     * @see \Cecil\Collection\Taxonomy\Collection
170
     */
171
    protected $taxonomies;
172
    /**
173
     * Renderer.
174
     * This is an instance of Renderer\Twig that is responsible for rendering pages.
175
     * It handles the rendering of templates and the application of data to those templates.
176
     * @var Renderer\Twig
177
     */
178
    protected $renderer;
179
    /**
180
     * Generators manager.
181
     * This is an instance of GeneratorManager that manages all the generators used in the build process.
182
     * Generators are used to create dynamic content or perform specific tasks during the build.
183
     * It allows for the registration and execution of various generators that can extend the functionality of the build process.
184
     * @var GeneratorManager
185
     */
186
    protected $generatorManager;
187
    /**
188
     * Application version.
189
     * @var string
190
     */
191
    protected static $version;
192
    /**
193
     * Build metrics.
194
     * This array holds metrics about the build process, such as duration and memory usage for each step.
195
     * It is used to track the performance of the build and can be useful for debugging and optimization.
196
     * @var array
197
     */
198
    protected $metrics = [];
199
    /**
200
     * Current build ID.
201
     * This is a unique identifier for the current build process.
202
     * It is generated based on the current date and time when the build starts.
203
     * It can be used to track builds, especially in environments where multiple builds may occur.
204
     * @var string
205
     * @see \Cecil\Builder::build()
206
     */
207
    protected $buildId;
208
209
    /**
210
     * @param Config|array|null    $config
211
     * @param LoggerInterface|null $logger
212
     */
213
    public function __construct($config = null, ?LoggerInterface $logger = null)
214
    {
215
        // init and set config
216
        $this->config = new Config();
217
        if ($config !== null) {
218
            $this->setConfig($config);
219
        }
220
        // debug mode?
221
        if (getenv('CECIL_DEBUG') == 'true' || $this->getConfig()->isEnabled('debug')) {
222
            $this->debug = true;
223
        }
224
        // set logger
225
        if ($logger === null) {
226
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
227
        }
228
        $this->setLogger($logger);
229
    }
230
231
    /**
232
     * Creates a new Builder instance.
233
     */
234
    public static function create(): self
235
    {
236
        $class = new \ReflectionClass(\get_called_class());
237
238
        return $class->newInstanceArgs(\func_get_args());
239
    }
240
241
    /**
242
     * Builds a new website.
243
     * This method processes the build steps in order, collects content, data, static files,
244
     * generates pages, renders them, and saves the output to the destination directory.
245
     * It also collects metrics about the build process, such as duration and memory usage.
246
     * @param array<self::OPTIONS> $options
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<self::OPTIONS> at position 2 could not be parsed: Expected '>' at position 2, but found 'self'.
Loading history...
247
     * @see \Cecil\Builder::OPTIONS
248
     */
249
    public function build(array $options): self
250
    {
251
        // set start script time and memory usage
252
        $startTime = microtime(true);
253
        $startMemory = memory_get_usage();
254
255
        // checks soft errors
256
        $this->checkErrors();
257
258
        // merge options with defaults
259
        $this->options = array_merge(self::OPTIONS, $options);
260
261
        // set build ID
262
        $this->buildId = date('YmdHis');
263
264
        // process each step
265
        $steps = [];
266
        // init...
267
        foreach (self::STEPS as $step) {
268
            $stepObject = new $step($this);
269
            $stepObject->init($this->options);
270
            if ($stepObject->canProcess()) {
271
                $steps[] = $stepObject;
272
            }
273
        }
274
        // ...and process
275
        $stepNumber = 0;
276
        $stepsTotal = \count($steps);
277
        foreach ($steps as $step) {
278
            $stepNumber++;
279
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
280
            $stepStartTime = microtime(true);
281
            $stepStartMemory = memory_get_usage();
282
            $step->process();
283
            // step duration and memory usage
284
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
285
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $stepStartTime);
286
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
287
            $this->getLogger()->info(\sprintf(
288
                '%s done in %s (%s)',
289
                $this->metrics['steps'][$stepNumber]['name'],
290
                $this->metrics['steps'][$stepNumber]['duration'],
291
                $this->metrics['steps'][$stepNumber]['memory']
292
            ));
293
        }
294
        // build duration and memory usage
295
        $this->metrics['total']['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $startTime);
296
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
297
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
298
299
        return $this;
300
    }
301
302
    /**
303
     * Returns current build ID.
304
     */
305
    public function getBuildId(): string
306
    {
307
        return $this->buildId;
308
    }
309
310
    /**
311
     * Set configuration.
312
     */
313
    public function setConfig(array|Config $config): self
314
    {
315
        if (\is_array($config)) {
316
            $config = new Config($config);
317
        }
318
        if ($this->config !== $config) {
319
            $this->config = $config;
320
        }
321
322
        // import themes configuration
323
        $this->importThemesConfig();
324
        // autoloads local extensions
325
        Util::autoload($this, 'extensions');
326
327
        return $this;
328
    }
329
330
    /**
331
     * Returns configuration.
332
     */
333
    public function getConfig(): Config
334
    {
335
        if ($this->config === null) {
336
            $this->config = new Config();
337
        }
338
339
        return $this->config;
340
    }
341
342
    /**
343
     * Config::setSourceDir() alias.
344
     */
345
    public function setSourceDir(string $sourceDir): self
346
    {
347
        $this->getConfig()->setSourceDir($sourceDir);
348
        // import themes configuration
349
        $this->importThemesConfig();
350
351
        return $this;
352
    }
353
354
    /**
355
     * Config::setDestinationDir() alias.
356
     */
357
    public function setDestinationDir(string $destinationDir): self
358
    {
359
        $this->getConfig()->setDestinationDir($destinationDir);
360
361
        return $this;
362
    }
363
364
    /**
365
     * Import themes configuration.
366
     */
367
    public function importThemesConfig(): void
368
    {
369
        foreach ((array) $this->getConfig()->get('theme') as $theme) {
370
            $this->getConfig()->import(
371
                Config::loadFile(Util::joinFile($this->getConfig()->getThemesPath(), $theme, 'config.yml'), true),
372
                Config::IMPORT_PRESERVE
373
            );
374
        }
375
    }
376
377
    /**
378
     * {@inheritdoc}
379
     */
380
    public function setLogger(LoggerInterface $logger): void
381
    {
382
        $this->logger = $logger;
383
    }
384
385
    /**
386
     * Returns the logger instance.
387
     */
388
    public function getLogger(): LoggerInterface
389
    {
390
        return $this->logger;
391
    }
392
393
    /**
394
     * Returns debug mode state.
395
     */
396
    public function isDebug(): bool
397
    {
398
        return (bool) $this->debug;
399
    }
400
401
    /**
402
     * Returns build options.
403
     */
404
    public function getBuildOptions(): array
405
    {
406
        return $this->options;
407
    }
408
409
    /**
410
     * Set collected pages files.
411
     */
412
    public function setPagesFiles(Finder $content): void
413
    {
414
        $this->content = $content;
415
    }
416
417
    /**
418
     * Returns pages files.
419
     */
420
    public function getPagesFiles(): ?Finder
421
    {
422
        return $this->content;
423
    }
424
425
    /**
426
     * Set collected data.
427
     */
428
    public function setData(array $data): void
429
    {
430
        $this->data = $data;
431
    }
432
433
    /**
434
     * Returns data collection.
435
     */
436
    public function getData(?string $language = null): array
437
    {
438
        if ($language) {
439
            if (empty($this->data[$language])) {
440
                // fallback to default language
441
                return $this->data[$this->getConfig()->getLanguageDefault()];
442
            }
443
444
            return $this->data[$language];
445
        }
446
447
        return $this->data;
448
    }
449
450
    /**
451
     * Set collected static files.
452
     */
453
    public function setStatic(array $static): void
454
    {
455
        $this->static = $static;
456
    }
457
458
    /**
459
     * Returns static files collection.
460
     */
461
    public function getStatic(): array
462
    {
463
        return $this->static;
464
    }
465
466
    /**
467
     * Set/update Pages collection.
468
     */
469
    public function setPages(PagesCollection $pages): void
470
    {
471
        $this->pages = $pages;
472
    }
473
474
    /**
475
     * Returns pages collection.
476
     */
477
    public function getPages(): ?PagesCollection
478
    {
479
        return $this->pages;
480
    }
481
482
    /**
483
     * Set assets path list.
484
     */
485
    public function setAssets(array $assets): void
486
    {
487
        $this->assets = $assets;
488
    }
489
490
    /**
491
     * Add an asset path to assets list.
492
     */
493
    public function addAsset(string $path): void
494
    {
495
        if (!\in_array($path, $this->assets, true)) {
496
            $this->assets[] = $path;
497
        }
498
    }
499
500
    /**
501
     * Returns list of assets path.
502
     */
503
    public function getAssets(): array
504
    {
505
        return $this->assets;
506
    }
507
508
    /**
509
     * Set menus collection.
510
     */
511
    public function setMenus(array $menus): void
512
    {
513
        $this->menus = $menus;
514
    }
515
516
    /**
517
     * Returns all menus, for a language.
518
     */
519
    public function getMenus(string $language): Collection\Menu\Collection
520
    {
521
        return $this->menus[$language];
522
    }
523
524
    /**
525
     * Set taxonomies collection.
526
     */
527
    public function setTaxonomies(array $taxonomies): void
528
    {
529
        $this->taxonomies = $taxonomies;
530
    }
531
532
    /**
533
     * Returns taxonomies collection, for a language.
534
     */
535
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
536
    {
537
        return $this->taxonomies[$language];
538
    }
539
540
    /**
541
     * Set renderer object.
542
     */
543
    public function setRenderer(Renderer\Twig $renderer): void
544
    {
545
        $this->renderer = $renderer;
546
    }
547
548
    /**
549
     * Returns Renderer object.
550
     */
551
    public function getRenderer(): Renderer\Twig
552
    {
553
        return $this->renderer;
554
    }
555
556
    /**
557
     * Returns metrics array.
558
     */
559
    public function getMetrics(): array
560
    {
561
        return $this->metrics;
562
    }
563
564
    /**
565
     * Returns application version.
566
     *
567
     * @throws RuntimeException
568
     */
569
    public static function getVersion(): string
570
    {
571
        if (!isset(self::$version)) {
572
            try {
573
                $filePath = Util\File::getRealPath('VERSION');
574
                $version = Util\File::fileGetContents($filePath);
575
                if ($version === false) {
576
                    throw new RuntimeException(\sprintf('Can\'t read content of "%s".', $filePath));
577
                }
578
                self::$version = trim($version);
579
            } catch (\Exception) {
580
                self::$version = self::VERSION;
581
            }
582
        }
583
584
        return self::$version;
585
    }
586
587
    /**
588
     * Log soft errors.
589
     */
590
    protected function checkErrors(): void
591
    {
592
        // baseurl is required in production
593
        if (empty(trim((string) $this->getConfig()->get('baseurl'), '/'))) {
594
            $this->getLogger()->error('`baseurl` configuration key is required in production.');
595
        }
596
    }
597
}
598