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

Cecilapp / Cecil / 15378730251

01 Jun 2025 07:40PM UTC coverage: 82.96% (-0.008%) from 82.968%
15378730251

Pull #2172

github

web-flow
Merge 4363b00d6 into efdff3105
Pull Request #2172: Build Command : Allow to render a specific path

13 of 15 new or added lines in 3 files covered. (86.67%)

15 existing lines in 2 files now uncovered.

3072 of 3703 relevant lines covered (82.96%)

0.83 hits per line

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

91.26
/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
    /** @var string curent build ID */
103
    protected $buildId;
104

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

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

134
        return $class->newInstanceArgs(\func_get_args());
1✔
135
    }
136

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

146
        // checks soft errors
147
        $this->checkErrors();
1✔
148

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

157
        // set build ID
158
        $this->buildId = date('YmdHis');
1✔
159

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

197
        return $this;
1✔
198
    }
199

200
    /**
201
     * Returns current build ID.
202
     */
203
    public function getBuilId(): string
204
    {
205
        return $this->buildId;
1✔
206
    }
207

208
    /**
209
     * Set configuration.
210
     */
211
    public function setConfig(array|Config $config): self
212
    {
213
        if (\is_array($config)) {
1✔
214
            $config = new Config($config);
1✔
215
        }
216
        if ($this->config !== $config) {
1✔
217
            $this->config = $config;
1✔
218
        }
219

220
        // import themes configuration
221
        $this->importThemesConfig();
1✔
222
        // autoloads local extensions
223
        Util::autoload($this, 'extensions');
1✔
224

225
        return $this;
1✔
226
    }
227

228
    /**
229
     * Returns configuration.
230
     */
231
    public function getConfig(): Config
232
    {
233
        if ($this->config === null) {
1✔
UNCOV
234
            $this->config = new Config();
×
235
        }
236

237
        return $this->config;
1✔
238
    }
239

240
    /**
241
     * Config::setSourceDir() alias.
242
     */
243
    public function setSourceDir(string $sourceDir): self
244
    {
245
        $this->getConfig()->setSourceDir($sourceDir);
1✔
246
        // import themes configuration
247
        $this->importThemesConfig();
1✔
248

249
        return $this;
1✔
250
    }
251

252
    /**
253
     * Config::setDestinationDir() alias.
254
     */
255
    public function setDestinationDir(string $destinationDir): self
256
    {
257
        $this->getConfig()->setDestinationDir($destinationDir);
1✔
258

259
        return $this;
1✔
260
    }
261

262
    /**
263
     * Import themes configuration.
264
     */
265
    public function importThemesConfig(): void
266
    {
267
        foreach ((array) $this->config->get('theme') as $theme) {
1✔
268
            $this->config->import(Config::loadFile(Util::joinFile($this->config->getThemesPath(), $theme, 'config.yml'), true), Config::PRESERVE);
1✔
269
        }
270
    }
271

272
    /**
273
     * {@inheritdoc}
274
     */
275
    public function setLogger(LoggerInterface $logger): void
276
    {
277
        $this->logger = $logger;
1✔
278
    }
279

280
    /**
281
     * Returns the logger instance.
282
     */
283
    public function getLogger(): LoggerInterface
284
    {
285
        return $this->logger;
1✔
286
    }
287

288
    /**
289
     * Returns debug mode state.
290
     */
291
    public function isDebug(): bool
292
    {
293
        return (bool) $this->debug;
1✔
294
    }
295

296
    /**
297
     * Returns build options.
298
     */
299
    public function getBuildOptions(): array
300
    {
301
        return $this->options;
1✔
302
    }
303

304
    /**
305
     * Set collected pages files.
306
     */
307
    public function setPagesFiles(Finder $content): void
308
    {
309
        $this->content = $content;
1✔
310
    }
311

312
    /**
313
     * Returns pages files.
314
     */
315
    public function getPagesFiles(): ?Finder
316
    {
317
        return $this->content;
1✔
318
    }
319

320
    /**
321
     * Set collected data.
322
     */
323
    public function setData(array $data): void
324
    {
325
        $this->data = $data;
1✔
326
    }
327

328
    /**
329
     * Returns data collection.
330
     */
331
    public function getData(?string $language = null): array
332
    {
333
        if ($language) {
1✔
334
            if (empty($this->data[$language])) {
1✔
335
                // fallback to default language
336
                return $this->data[$this->config->getLanguageDefault()];
1✔
337
            }
338

339
            return $this->data[$language];
1✔
340
        }
341

342
        return $this->data;
1✔
343
    }
344

345
    /**
346
     * Set collected static files.
347
     */
348
    public function setStatic(array $static): void
349
    {
350
        $this->static = $static;
1✔
351
    }
352

353
    /**
354
     * Returns static files collection.
355
     */
356
    public function getStatic(): array
357
    {
358
        return $this->static;
1✔
359
    }
360

361
    /**
362
     * Set/update Pages collection.
363
     */
364
    public function setPages(PagesCollection $pages): void
365
    {
366
        $this->pages = $pages;
1✔
367
    }
368

369
    /**
370
     * Returns pages collection.
371
     */
372
    public function getPages(): ?PagesCollection
373
    {
374
        return $this->pages;
1✔
375
    }
376

377
    /**
378
     * Set assets path list.
379
     */
380
    public function setAssets(array $assets): void
381
    {
UNCOV
382
        $this->assets = $assets;
×
383
    }
384

385
    /**
386
     * Add an asset path to assets list.
387
     */
388
    public function addAsset(string $path): void
389
    {
390
        if (!\in_array($path, $this->assets, true)) {
1✔
391
            $this->assets[] = $path;
1✔
392
        }
393
    }
394

395
    /**
396
     * Returns list of assets path.
397
     */
398
    public function getAssets(): array
399
    {
400
        return $this->assets;
1✔
401
    }
402

403
    /**
404
     * Set menus collection.
405
     */
406
    public function setMenus(array $menus): void
407
    {
408
        $this->menus = $menus;
1✔
409
    }
410

411
    /**
412
     * Returns all menus, for a language.
413
     */
414
    public function getMenus(string $language): Collection\Menu\Collection
415
    {
416
        return $this->menus[$language];
1✔
417
    }
418

419
    /**
420
     * Set taxonomies collection.
421
     */
422
    public function setTaxonomies(array $taxonomies): void
423
    {
424
        $this->taxonomies = $taxonomies;
1✔
425
    }
426

427
    /**
428
     * Returns taxonomies collection, for a language.
429
     */
430
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
431
    {
432
        return $this->taxonomies[$language];
1✔
433
    }
434

435
    /**
436
     * Set renderer object.
437
     */
438
    public function setRenderer(Renderer\RendererInterface $renderer): void
439
    {
440
        $this->renderer = $renderer;
1✔
441
    }
442

443
    /**
444
     * Returns Renderer object.
445
     */
446
    public function getRenderer(): Renderer\RendererInterface
447
    {
448
        return $this->renderer;
1✔
449
    }
450

451
    /**
452
     * Returns metrics array.
453
     */
454
    public function getMetrics(): array
455
    {
UNCOV
456
        return $this->metrics;
×
457
    }
458

459
    /**
460
     * Returns application version.
461
     *
462
     * @throws RuntimeException
463
     */
464
    public static function getVersion(): string
465
    {
466
        if (!isset(self::$version)) {
1✔
467
            try {
468
                $filePath = Util\File::getRealPath('VERSION');
1✔
469
                $version = Util\File::fileGetContents($filePath);
×
470
                if ($version === false) {
×
UNCOV
471
                    throw new RuntimeException(\sprintf('Can\'t read content of "%s".', $filePath));
×
472
                }
UNCOV
473
                self::$version = trim($version);
×
474
            } catch (\Exception) {
1✔
475
                self::$version = self::VERSION;
1✔
476
            }
477
        }
478

479
        return self::$version;
1✔
480
    }
481

482
    /**
483
     * Log soft errors.
484
     */
485
    protected function checkErrors(): void
486
    {
487
        // baseurl is required in production
488
        if (empty(trim((string) $this->config->get('baseurl'), '/'))) {
1✔
UNCOV
489
            $this->getLogger()->error('`baseurl` configuration key is required in production.');
×
490
        }
491
    }
492
}
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