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

Cecilapp / Cecil / 14087422519

26 Mar 2025 03:37PM UTC coverage: 82.954%. First build
14087422519

Pull #2144

github

web-flow
Merge c26c9dea3 into eed522174
Pull Request #2144: refactor: configuration options logic

97 of 111 new or added lines in 20 files covered. (87.39%)

2988 of 3602 relevant lines covered (82.95%)

0.83 hits per line

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

90.53
/src/Builder.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;
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
 * Class Builder.
26
 */
27
class Builder implements LoggerAwareInterface
28
{
29
    public const VERSION = '8.x-dev';
30
    public const VERBOSITY_QUIET = -1;
31
    public const VERBOSITY_NORMAL = 0;
32
    public const VERBOSITY_VERBOSE = 1;
33
    public const VERBOSITY_DEBUG = 2;
34

35
    /**
36
     * @var array Steps processed by build().
37
     */
38
    protected $steps = [
39
        'Cecil\Step\Pages\Load',
40
        'Cecil\Step\Data\Load',
41
        'Cecil\Step\StaticFiles\Load',
42
        'Cecil\Step\Pages\Create',
43
        'Cecil\Step\Pages\Convert',
44
        'Cecil\Step\Taxonomies\Create',
45
        'Cecil\Step\Pages\Generate',
46
        'Cecil\Step\Menus\Create',
47
        'Cecil\Step\StaticFiles\Copy',
48
        'Cecil\Step\Pages\Render',
49
        'Cecil\Step\Pages\Save',
50
        'Cecil\Step\Assets\Save',
51
        'Cecil\Step\Optimize\Html',
52
        'Cecil\Step\Optimize\Css',
53
        'Cecil\Step\Optimize\Js',
54
        'Cecil\Step\Optimize\Images',
55
    ];
56

57
    /** @var Config Configuration. */
58
    protected $config;
59

60
    /** @var LoggerInterface Logger. */
61
    protected $logger;
62

63
    /** @var bool Debug mode. */
64
    protected $debug = false;
65

66
    /** @var array Build options. */
67
    protected $options;
68

69
    /** @var Finder Content iterator. */
70
    protected $content;
71

72
    /** @var array Data collection. */
73
    protected $data = [];
74

75
    /** @var array Static files collection. */
76
    protected $static = [];
77

78
    /** @var PagesCollection Pages collection. */
79
    protected $pages;
80

81
    /** @var array Assets path collection */
82
    protected $assets = [];
83

84
    /** @var array Menus collection. */
85
    protected $menus;
86

87
    /** @var array Taxonomies collection. */
88
    protected $taxonomies;
89

90
    /** @var Renderer\RendererInterface Renderer. */
91
    protected $renderer;
92

93
    /** @var GeneratorManager Generators manager. */
94
    protected $generatorManager;
95

96
    /** @var string Application version. */
97
    protected static $version;
98

99
    /** @var array Build metrics. */
100
    protected $metrics = [];
101

102
    /**
103
     * @param Config|array|null    $config
104
     * @param LoggerInterface|null $logger
105
     */
106
    public function __construct($config = null, ?LoggerInterface $logger = null)
107
    {
108
        // set config?
109
        if ($config !== null) {
1✔
110
            $this->setConfig($config);
1✔
111
        }
112
        // debug mode?
113
        if (getenv('CECIL_DEBUG') == 'true' || $this->getConfig()->isEnabled('debug')) {
1✔
114
            $this->debug = true;
1✔
115
        }
116
        // set logger
117
        if ($logger === null) {
1✔
118
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
×
119
        }
120
        $this->setLogger($logger);
1✔
121
        // autoloads local extensions
122
        Util::autoload($this, 'extensions');
1✔
123
    }
124

125
    /**
126
     * Creates a new Builder instance.
127
     */
128
    public static function create(): self
129
    {
130
        $class = new \ReflectionClass(\get_called_class());
1✔
131

132
        return $class->newInstanceArgs(\func_get_args());
1✔
133
    }
134

135
    /**
136
     * Builds a new website.
137
     */
138
    public function build(array $options): self
139
    {
140
        // set start script time and memory usage
141
        $startTime = microtime(true);
1✔
142
        $startMemory = memory_get_usage();
1✔
143

144
        // log configuration errors
145
        $this->logConfigError();
1✔
146

147
        // prepare options
148
        $this->options = array_merge([
1✔
149
            'drafts'  => false, // build drafts or not
1✔
150
            'dry-run' => false, // if dry-run is true, generated files are not saved
1✔
151
            'page'    => '',    // specific page to build
1✔
152
        ], $options);
1✔
153

154
        // process each step
155
        $steps = [];
1✔
156
        // init...
157
        foreach ($this->steps as $step) {
1✔
158
            /** @var Step\StepInterface $stepObject */
159
            $stepObject = new $step($this);
1✔
160
            $stepObject->init($this->options);
1✔
161
            if ($stepObject->canProcess()) {
1✔
162
                $steps[] = $stepObject;
1✔
163
            }
164
        }
165
        // ...and process!
166
        $stepNumber = 0;
1✔
167
        $stepsTotal = \count($steps);
1✔
168
        foreach ($steps as $step) {
1✔
169
            $stepNumber++;
1✔
170
            /** @var Step\StepInterface $step */
171
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
1✔
172
            $stepStartTime = microtime(true);
1✔
173
            $stepStartMemory = memory_get_usage();
1✔
174
            $step->process();
1✔
175
            // step duration and memory usage
176
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
1✔
177
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime((float) $stepStartTime);
1✔
178
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
1✔
179
            $this->getLogger()->info(\sprintf(
1✔
180
                '%s done in %s (%s)',
1✔
181
                $this->metrics['steps'][$stepNumber]['name'],
1✔
182
                $this->metrics['steps'][$stepNumber]['duration'],
1✔
183
                $this->metrics['steps'][$stepNumber]['memory']
1✔
184
            ));
1✔
185
        }
186
        // build duration and memory usage
187
        $this->metrics['total']['duration'] = Util::convertMicrotime($startTime);
1✔
188
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
1✔
189
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
1✔
190

191
        return $this;
1✔
192
    }
193

194
    /**
195
     * Set configuration.
196
     */
197
    public function setConfig(array|Config $config): self
198
    {
199
        if (!$config instanceof Config) {
1✔
200
            $config = new Config($config);
1✔
201
        }
202
        if ($this->config !== $config) {
1✔
203
            $this->config = $config;
1✔
204
        }
205

206
        return $this;
1✔
207
    }
208

209
    /**
210
     * Returns configuration.
211
     */
212
    public function getConfig(): Config
213
    {
214
        if ($this->config === null) {
1✔
NEW
215
            $this->config = new Config();
×
216
        }
217

218
        return $this->config;
1✔
219
    }
220

221
    /**
222
     * Config::setSourceDir() alias.
223
     */
224
    public function setSourceDir(string $sourceDir): self
225
    {
226
        $this->config->setSourceDir($sourceDir);
1✔
227

228
        return $this;
1✔
229
    }
230

231
    /**
232
     * Config::setDestinationDir() alias.
233
     */
234
    public function setDestinationDir(string $destinationDir): self
235
    {
236
        $this->config->setDestinationDir($destinationDir);
1✔
237

238
        return $this;
1✔
239
    }
240

241
    /**
242
     * {@inheritdoc}
243
     */
244
    public function setLogger(LoggerInterface $logger): void
245
    {
246
        $this->logger = $logger;
1✔
247
    }
248

249
    /**
250
     * Returns the logger instance.
251
     */
252
    public function getLogger(): LoggerInterface
253
    {
254
        return $this->logger;
1✔
255
    }
256

257
    /**
258
     * Returns debug mode state.
259
     */
260
    public function isDebug(): bool
261
    {
262
        return (bool) $this->debug;
1✔
263
    }
264

265
    /**
266
     * Returns build options.
267
     */
268
    public function getBuildOptions(): array
269
    {
270
        return $this->options;
1✔
271
    }
272

273
    /**
274
     * Set collected pages files.
275
     */
276
    public function setPagesFiles(Finder $content): void
277
    {
278
        $this->content = $content;
1✔
279
    }
280

281
    /**
282
     * Returns pages files.
283
     */
284
    public function getPagesFiles(): ?Finder
285
    {
286
        return $this->content;
1✔
287
    }
288

289
    /**
290
     * Set collected data.
291
     */
292
    public function setData(array $data): void
293
    {
294
        $this->data = $data;
1✔
295
    }
296

297
    /**
298
     * Returns data collection.
299
     */
300
    public function getData(?string $language = null): ?array
301
    {
302
        if ($language) {
1✔
303
            if (empty($this->data[$language])) {
1✔
304
                // fallback to default language
305
                return $this->data[$this->config->getLanguageDefault()];
1✔
306
            }
307

308
            return $this->data[$language];
1✔
309
        }
310

311
        return $this->data;
1✔
312
    }
313

314
    /**
315
     * Set collected static files.
316
     */
317
    public function setStatic(array $static): void
318
    {
319
        $this->static = $static;
1✔
320
    }
321

322
    /**
323
     * Returns static files collection.
324
     */
325
    public function getStatic(): array
326
    {
327
        return $this->static;
1✔
328
    }
329

330
    /**
331
     * Set/update Pages collection.
332
     */
333
    public function setPages(PagesCollection $pages): void
334
    {
335
        $this->pages = $pages;
1✔
336
    }
337

338
    /**
339
     * Returns pages collection.
340
     */
341
    public function getPages(): ?PagesCollection
342
    {
343
        return $this->pages;
1✔
344
    }
345

346
    /**
347
     * Set assets path collection.
348
     */
349
    public function setAssets(array $assets): void
350
    {
351
        $this->assets = $assets;
×
352
    }
353

354
    /**
355
     * Add an asset path to assets collection.
356
     */
357
    public function addAsset(string $path): void
358
    {
359
        if (!\in_array($path, $this->assets, true)) {
1✔
360
            $this->assets[] = $path;
1✔
361
        }
362
    }
363

364
    /**
365
     * Returns list of assets path.
366
     */
367
    public function getAssets(): ?array
368
    {
369
        return $this->assets;
1✔
370
    }
371

372
    /**
373
     * Set menus collection.
374
     */
375
    public function setMenus(array $menus): void
376
    {
377
        $this->menus = $menus;
1✔
378
    }
379

380
    /**
381
     * Returns all menus, for a language.
382
     */
383
    public function getMenus(string $language): Collection\Menu\Collection
384
    {
385
        return $this->menus[$language];
1✔
386
    }
387

388
    /**
389
     * Set taxonomies collection.
390
     */
391
    public function setTaxonomies(array $taxonomies): void
392
    {
393
        $this->taxonomies = $taxonomies;
1✔
394
    }
395

396
    /**
397
     * Returns taxonomies collection, for a language.
398
     */
399
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
400
    {
401
        return $this->taxonomies[$language];
1✔
402
    }
403

404
    /**
405
     * Set renderer object.
406
     */
407
    public function setRenderer(Renderer\RendererInterface $renderer): void
408
    {
409
        $this->renderer = $renderer;
1✔
410
    }
411

412
    /**
413
     * Returns Renderer object.
414
     */
415
    public function getRenderer(): Renderer\RendererInterface
416
    {
417
        return $this->renderer;
1✔
418
    }
419

420
    /**
421
     * Returns metrics array.
422
     */
423
    public function getMetrics(): array
424
    {
425
        return $this->metrics;
×
426
    }
427

428
    /**
429
     * Returns application version.
430
     *
431
     * @throws RuntimeException
432
     */
433
    public static function getVersion(): string
434
    {
435
        if (!isset(self::$version)) {
1✔
436
            try {
437
                $filePath = Util\File::getRealPath('VERSION');
1✔
438
                $version = Util\File::fileGetContents($filePath);
×
439
                if ($version === false) {
×
440
                    throw new RuntimeException(\sprintf('Can\'t read content of "%s".', $filePath));
×
441
                }
442
                self::$version = trim($version);
×
443
            } catch (\Exception) {
1✔
444
                self::$version = self::VERSION;
1✔
445
            }
446
        }
447

448
        return self::$version;
1✔
449
    }
450

451
    /**
452
     * Log configuration errors.
453
     */
454
    protected function logConfigError(): void
455
    {
456
        // warning about baseurl
457
        if (empty(trim((string) $this->config->get('baseurl'), '/'))) {
1✔
458
            $this->getLogger()->warning('`baseurl` configuration key is required in production.');
×
459
        }
460
    }
461
}
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