Passed
Push — master ( 44febc...419a20 )
by Arnaud
05:45
created

Builder   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 557
Duplicated Lines 0 %

Test Coverage

Coverage 91.79%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 144
c 6
b 1
f 0
dl 0
loc 557
ccs 123
cts 134
cp 0.9179
rs 7.92
wmc 51

33 Methods

Rating   Name   Duplication   Size   Complexity  
A getConfig() 0 7 2
A setDestinationDir() 0 5 1
A build() 0 53 4
A setSourceDir() 0 7 1
A __construct() 0 16 5
A getBuildId() 0 3 1
A setConfig() 0 15 3
A create() 0 5 1
A setMenus() 0 3 1
A getRenderer() 0 3 1
A getData() 0 12 3
A setPages() 0 3 1
A setTaxonomies() 0 3 1
A addAsset() 0 4 2
A setRenderer() 0 3 1
A getPages() 0 3 1
A getLogger() 0 3 1
A getAssets() 0 3 1
A getVersion() 0 16 4
A getMetrics() 0 3 1
A getMenus() 0 3 1
A setAssets() 0 3 1
A setPagesFiles() 0 3 1
A checkErrors() 0 5 2
A getStatic() 0 3 1
A getBuildOptions() 0 3 1
A setStatic() 0 3 1
A setLogger() 0 3 1
A isDebug() 0 3 1
A setData() 0 3 1
A getPagesFiles() 0 3 1
A importThemesConfig() 0 6 2
A getTaxonomies() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Builder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Builder, and based on these observations, apply Extract Interface, too.

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
class Builder implements LoggerAwareInterface
33
{
34
    public const VERSION = '8.x-dev';
35
    public const VERBOSITY_QUIET = -1;
36
    public const VERBOSITY_NORMAL = 0;
37
    public const VERBOSITY_VERBOSE = 1;
38
    public const VERBOSITY_DEBUG = 2;
39
    /**
40
     * Default options for the build process.
41
     * These options can be overridden when calling the build() method.
42
     * - 'drafts': if true, builds drafts too (default: false)
43
     * - 'dry-run': if true, generated files are not saved (default: false)
44
     * - 'page': if specified, only this page is processed (default: '')
45
     * - 'render-subset': limits the render step to a specific subset (default: '')
46
     * @var array<string, bool|string>
47
     * @see \Cecil\Builder::build()
48
     */
49
    public const OPTIONS = [
50
        'drafts'  => false,
51
        'dry-run' => false,
52
        'page'    => '',
53
        'render-subset' => '',
54
    ];
55
56
    /**
57
     * Steps processed by build(), in order.
58
     * These steps are executed sequentially to build the website.
59
     * Each step is a class that implements the StepInterface.
60
     * @var array<string>
61
     * @see \Cecil\Step\StepInterface
62
     */
63
    protected $steps = [
64
        'Cecil\Step\Pages\Load',
65
        'Cecil\Step\Data\Load',
66
        'Cecil\Step\StaticFiles\Load',
67
        'Cecil\Step\Pages\Create',
68
        'Cecil\Step\Pages\Convert',
69
        'Cecil\Step\Taxonomies\Create',
70
        'Cecil\Step\Pages\Generate',
71
        'Cecil\Step\Menus\Create',
72
        'Cecil\Step\StaticFiles\Copy',
73
        'Cecil\Step\Pages\Render',
74
        'Cecil\Step\Pages\Save',
75
        'Cecil\Step\Assets\Save',
76
        'Cecil\Step\Optimize\Html',
77
        'Cecil\Step\Optimize\Css',
78
        'Cecil\Step\Optimize\Js',
79
        'Cecil\Step\Optimize\Images',
80
    ];
81
    /**
82
     * Configuration object.
83
     * This object holds all the configuration settings for the build process.
84
     * It can be set to an array or a Config instance.
85
     * @var Config|array|null
86
     * @see \Cecil\Config
87
     */
88
    protected $config;
89
    /**
90
     * Logger instance.
91
     * This logger is used to log messages during the build process.
92
     * It can be set to any PSR-3 compliant logger.
93
     * @var LoggerInterface
94
     * @see \Psr\Log\LoggerInterface
95
     * */
96
    protected $logger;
97
    /**
98
     * Debug mode state.
99
     * If true, debug messages are logged.
100
     * @var bool
101
     */
102
    protected $debug = false;
103
    /**
104
     * Build options.
105
     * These options can be passed to the build() method to customize the build process.
106
     * @var array
107
     * @see \Cecil\Builder::OPTIONS
108
     * @see \Cecil\Builder::build()
109
     */
110
    protected $options = [];
111
    /**
112
     * Content files collection.
113
     * This is a Finder instance that collects all the content files (pages, posts, etc.) from the source directory.
114
     * @var Finder
115
     */
116
    protected $content;
117
    /**
118
     * Data collection.
119
     * This is an associative array that holds data loaded from YAML files in the data directory.
120
     * @var array
121
     */
122
    protected $data = [];
123
    /**
124
     * Static files collection.
125
     * This is an associative array that holds static files (like images, CSS, JS) that are copied to the destination directory.
126
     * @var array
127
     */
128
    protected $static = [];
129
    /**
130
     * Pages collection.
131
     * This is a collection of pages that have been processed and are ready for rendering.
132
     * It is an instance of PagesCollection, which is a custom collection class for managing pages.
133
     * @var PagesCollection
134
     */
135
    protected $pages;
136
    /**
137
     * Assets path collection.
138
     * This is an array that holds paths to assets (like CSS, JS, images) that are used in the build process.
139
     * It is used to keep track of assets that need to be processed or copied.
140
     * It can be set to an array of paths or updated with new asset paths.
141
     * @var array
142
     */
143
    protected $assets = [];
144
    /**
145
     * Menus collection.
146
     * This is an associative array that holds menus for different languages.
147
     * Each key is a language code, and the value is a Collection\Menu\Collection instance
148
     * that contains the menu items for that language.
149
     * It is used to manage navigation menus across different languages in the website.
150
     * @var array
151
     * @see \Cecil\Collection\Menu\Collection
152
     */
153
    protected $menus;
154
    /**
155
     * Taxonomies collection.
156
     * This is an associative array that holds taxonomies for different languages.
157
     * Each key is a language code, and the value is a Collection\Taxonomy\Collection instance
158
     * that contains the taxonomy terms for that language.
159
     * It is used to manage taxonomies (like categories, tags) across different languages in the website.
160
     * @var array
161
     * @see \Cecil\Collection\Taxonomy\Collection
162
     */
163
    protected $taxonomies;
164
    /**
165
     * Renderer.
166
     * This is an instance of Renderer\RendererInterface that is responsible for rendering pages.
167
     * It handles the rendering of templates and the application of data to those templates.
168
     * @var Renderer\RendererInterface
169
     */
170
    protected $renderer;
171
    /**
172
     * Generators manager.
173
     * This is an instance of GeneratorManager that manages all the generators used in the build process.
174
     * Generators are used to create dynamic content or perform specific tasks during the build.
175
     * It allows for the registration and execution of various generators that can extend the functionality of the build process.
176
     * @var GeneratorManager
177
     */
178
    protected $generatorManager;
179
    /**
180
     * Application version.
181
     * @var string
182
     */
183
    protected static $version;
184
    /**
185
     * Build metrics.
186
     * This array holds metrics about the build process, such as duration and memory usage for each step.
187
     * It is used to track the performance of the build and can be useful for debugging and optimization.
188
     * @var array
189
     */
190
    protected $metrics = [];
191
    /**
192
     * Current build ID.
193
     * This is a unique identifier for the current build process.
194
     * It is generated based on the current date and time when the build starts.
195
     * It can be used to track builds, especially in environments where multiple builds may occur.
196
     * @var string
197
     * @see \Cecil\Builder::build()
198
     */
199
    protected $buildId;
200
201
    /**
202
     * @param Config|array|null    $config
203
     * @param LoggerInterface|null $logger
204
     */
205 1
    public function __construct($config = null, ?LoggerInterface $logger = null)
206
    {
207
        // init and set config
208 1
        $this->config = new Config();
209 1
        if ($config !== null) {
210 1
            $this->setConfig($config);
211
        }
212
        // debug mode?
213 1
        if (getenv('CECIL_DEBUG') == 'true' || $this->getConfig()->isEnabled('debug')) {
214 1
            $this->debug = true;
215
        }
216
        // set logger
217 1
        if ($logger === null) {
218
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
219
        }
220 1
        $this->setLogger($logger);
221
    }
222
223
    /**
224
     * Creates a new Builder instance.
225
     */
226 1
    public static function create(): self
227
    {
228 1
        $class = new \ReflectionClass(\get_called_class());
229
230 1
        return $class->newInstanceArgs(\func_get_args());
231
    }
232
233
    /**
234
     * Builds a new website.
235
     * This method processes the build steps in order, collects content, data, static files,
236
     * generates pages, renders them, and saves the output to the destination directory.
237
     * It also collects metrics about the build process, such as duration and memory usage.
238
     * @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...
239
     * @see \Cecil\Builder::OPTIONS
240
     */
241 1
    public function build(array $options): self
242
    {
243
        // set start script time and memory usage
244 1
        $startTime = microtime(true);
245 1
        $startMemory = memory_get_usage();
246
247
        // checks soft errors
248 1
        $this->checkErrors();
249
250
        // merge options with defaults
251 1
        $this->options = array_merge(self::OPTIONS, $options);
252
253
        // set build ID
254 1
        $this->buildId = date('YmdHis');
255
256
        // process each step
257 1
        $steps = [];
258
        // init...
259 1
        foreach ($this->steps as $step) {
260
            /** @var Step\StepInterface $stepObject */
261 1
            $stepObject = new $step($this);
262 1
            $stepObject->init($this->options);
263 1
            if ($stepObject->canProcess()) {
264 1
                $steps[] = $stepObject;
265
            }
266
        }
267
        // ...and process
268 1
        $stepNumber = 0;
269 1
        $stepsTotal = \count($steps);
270 1
        foreach ($steps as $step) {
271 1
            $stepNumber++;
272
            /** @var Step\StepInterface $step */
273 1
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
274 1
            $stepStartTime = microtime(true);
275 1
            $stepStartMemory = memory_get_usage();
276 1
            $step->process();
277
            // step duration and memory usage
278 1
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
279 1
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime((float) $stepStartTime);
280 1
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
281 1
            $this->getLogger()->info(\sprintf(
282 1
                '%s done in %s (%s)',
283 1
                $this->metrics['steps'][$stepNumber]['name'],
284 1
                $this->metrics['steps'][$stepNumber]['duration'],
285 1
                $this->metrics['steps'][$stepNumber]['memory']
286 1
            ));
287
        }
288
        // build duration and memory usage
289 1
        $this->metrics['total']['duration'] = Util::convertMicrotime($startTime);
0 ignored issues
show
Bug introduced by
It seems like $startTime can also be of type string; however, parameter $start of Cecil\Util::convertMicrotime() does only seem to accept double, 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

289
        $this->metrics['total']['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $startTime);
Loading history...
290 1
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
291 1
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
292
293 1
        return $this;
294
    }
295
296
    /**
297
     * Returns current build ID.
298
     */
299 1
    public function getBuildId(): string
300
    {
301 1
        return $this->buildId;
302
    }
303
304
    /**
305
     * Set configuration.
306
     */
307 1
    public function setConfig(array|Config $config): self
308
    {
309 1
        if (\is_array($config)) {
310 1
            $config = new Config($config);
311
        }
312 1
        if ($this->config !== $config) {
313 1
            $this->config = $config;
314
        }
315
316
        // import themes configuration
317 1
        $this->importThemesConfig();
318
        // autoloads local extensions
319 1
        Util::autoload($this, 'extensions');
320
321 1
        return $this;
322
    }
323
324
    /**
325
     * Returns configuration.
326
     */
327 1
    public function getConfig(): Config
328
    {
329 1
        if ($this->config === null) {
330
            $this->config = new Config();
331
        }
332
333 1
        return $this->config;
334
    }
335
336
    /**
337
     * Config::setSourceDir() alias.
338
     */
339 1
    public function setSourceDir(string $sourceDir): self
340
    {
341 1
        $this->getConfig()->setSourceDir($sourceDir);
342
        // import themes configuration
343 1
        $this->importThemesConfig();
344
345 1
        return $this;
346
    }
347
348
    /**
349
     * Config::setDestinationDir() alias.
350
     */
351 1
    public function setDestinationDir(string $destinationDir): self
352
    {
353 1
        $this->getConfig()->setDestinationDir($destinationDir);
354
355 1
        return $this;
356
    }
357
358
    /**
359
     * Import themes configuration.
360
     */
361 1
    public function importThemesConfig(): void
362
    {
363 1
        foreach ((array) $this->getConfig()->get('theme') as $theme) {
364 1
            $this->getConfig()->import(
365 1
                Config::loadFile(Util::joinFile($this->getConfig()->getThemesPath(), $theme, 'config.yml'), true),
366 1
                Config::PRESERVE
367 1
            );
368
        }
369
    }
370
371
    /**
372
     * {@inheritdoc}
373
     */
374 1
    public function setLogger(LoggerInterface $logger): void
375
    {
376 1
        $this->logger = $logger;
377
    }
378
379
    /**
380
     * Returns the logger instance.
381
     */
382 1
    public function getLogger(): LoggerInterface
383
    {
384 1
        return $this->logger;
385
    }
386
387
    /**
388
     * Returns debug mode state.
389
     */
390 1
    public function isDebug(): bool
391
    {
392 1
        return (bool) $this->debug;
393
    }
394
395
    /**
396
     * Returns build options.
397
     */
398 1
    public function getBuildOptions(): array
399
    {
400 1
        return $this->options;
401
    }
402
403
    /**
404
     * Set collected pages files.
405
     */
406 1
    public function setPagesFiles(Finder $content): void
407
    {
408 1
        $this->content = $content;
409
    }
410
411
    /**
412
     * Returns pages files.
413
     */
414 1
    public function getPagesFiles(): ?Finder
415
    {
416 1
        return $this->content;
417
    }
418
419
    /**
420
     * Set collected data.
421
     */
422 1
    public function setData(array $data): void
423
    {
424 1
        $this->data = $data;
425
    }
426
427
    /**
428
     * Returns data collection.
429
     */
430 1
    public function getData(?string $language = null): array
431
    {
432 1
        if ($language) {
433 1
            if (empty($this->data[$language])) {
434
                // fallback to default language
435 1
                return $this->data[$this->getConfig()->getLanguageDefault()];
436
            }
437
438 1
            return $this->data[$language];
439
        }
440
441 1
        return $this->data;
442
    }
443
444
    /**
445
     * Set collected static files.
446
     */
447 1
    public function setStatic(array $static): void
448
    {
449 1
        $this->static = $static;
450
    }
451
452
    /**
453
     * Returns static files collection.
454
     */
455 1
    public function getStatic(): array
456
    {
457 1
        return $this->static;
458
    }
459
460
    /**
461
     * Set/update Pages collection.
462
     */
463 1
    public function setPages(PagesCollection $pages): void
464
    {
465 1
        $this->pages = $pages;
466
    }
467
468
    /**
469
     * Returns pages collection.
470
     */
471 1
    public function getPages(): ?PagesCollection
472
    {
473 1
        return $this->pages;
474
    }
475
476
    /**
477
     * Set assets path list.
478
     */
479
    public function setAssets(array $assets): void
480
    {
481
        $this->assets = $assets;
482
    }
483
484
    /**
485
     * Add an asset path to assets list.
486
     */
487 1
    public function addAsset(string $path): void
488
    {
489 1
        if (!\in_array($path, $this->assets, true)) {
490 1
            $this->assets[] = $path;
491
        }
492
    }
493
494
    /**
495
     * Returns list of assets path.
496
     */
497 1
    public function getAssets(): array
498
    {
499 1
        return $this->assets;
500
    }
501
502
    /**
503
     * Set menus collection.
504
     */
505 1
    public function setMenus(array $menus): void
506
    {
507 1
        $this->menus = $menus;
508
    }
509
510
    /**
511
     * Returns all menus, for a language.
512
     */
513 1
    public function getMenus(string $language): Collection\Menu\Collection
514
    {
515 1
        return $this->menus[$language];
516
    }
517
518
    /**
519
     * Set taxonomies collection.
520
     */
521 1
    public function setTaxonomies(array $taxonomies): void
522
    {
523 1
        $this->taxonomies = $taxonomies;
524
    }
525
526
    /**
527
     * Returns taxonomies collection, for a language.
528
     */
529 1
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
530
    {
531 1
        return $this->taxonomies[$language];
532
    }
533
534
    /**
535
     * Set renderer object.
536
     */
537 1
    public function setRenderer(Renderer\RendererInterface $renderer): void
538
    {
539 1
        $this->renderer = $renderer;
540
    }
541
542
    /**
543
     * Returns Renderer object.
544
     */
545 1
    public function getRenderer(): Renderer\RendererInterface
546
    {
547 1
        return $this->renderer;
548
    }
549
550
    /**
551
     * Returns metrics array.
552
     */
553
    public function getMetrics(): array
554
    {
555
        return $this->metrics;
556
    }
557
558
    /**
559
     * Returns application version.
560
     *
561
     * @throws RuntimeException
562
     */
563 1
    public static function getVersion(): string
564
    {
565 1
        if (!isset(self::$version)) {
566
            try {
567 1
                $filePath = Util\File::getRealPath('VERSION');
568
                $version = Util\File::fileGetContents($filePath);
569
                if ($version === false) {
570
                    throw new RuntimeException(\sprintf('Can\'t read content of "%s".', $filePath));
571
                }
572
                self::$version = trim($version);
573 1
            } catch (\Exception) {
574 1
                self::$version = self::VERSION;
575
            }
576
        }
577
578 1
        return self::$version;
579
    }
580
581
    /**
582
     * Log soft errors.
583
     */
584 1
    protected function checkErrors(): void
585
    {
586
        // baseurl is required in production
587 1
        if (empty(trim((string) $this->getConfig()->get('baseurl'), '/'))) {
588
            $this->getLogger()->error('`baseurl` configuration key is required in production.');
589
        }
590
    }
591
}
592