Passed
Pull Request — master (#2125)
by Arnaud
10:41 queued 02:51
created

Builder::getMetrics()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
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 Cecil\Util\Platform;
21
use Psr\Log\LoggerAwareInterface;
22
use Psr\Log\LoggerInterface;
23
use Symfony\Component\Finder\Finder;
24
25
/**
26
 * Class Builder.
27
 */
28
class Builder implements LoggerAwareInterface
29
{
30
    public const VERSION = '8.x-dev';
31
    public const VERBOSITY_QUIET = -1;
32
    public const VERBOSITY_NORMAL = 0;
33
    public const VERBOSITY_VERBOSE = 1;
34
    public const VERBOSITY_DEBUG = 2;
35
36
    /**
37
     * @var array Steps processed by build().
38
     */
39
    protected $steps = [
40
        'Cecil\Step\Pages\Load',
41
        'Cecil\Step\Data\Load',
42
        'Cecil\Step\StaticFiles\Load',
43
        'Cecil\Step\Pages\Create',
44
        'Cecil\Step\Pages\Convert',
45
        'Cecil\Step\Taxonomies\Create',
46
        'Cecil\Step\Pages\Generate',
47
        'Cecil\Step\Menus\Create',
48
        'Cecil\Step\StaticFiles\Copy',
49
        'Cecil\Step\Pages\Render',
50
        'Cecil\Step\Pages\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 Menus collection. */
82
    protected $menus;
83
84
    /** @var array Taxonomies collection. */
85
    protected $taxonomies;
86
87
    /** @var Renderer\RendererInterface Renderer. */
88
    protected $renderer;
89
90
    /** @var GeneratorManager Generators manager. */
91
    protected $generatorManager;
92
93
    /** @var string Application version. */
94
    protected static $version;
95
96
    /** @var array Build metrics. */
97
    protected $metrics = [];
98
99
    /**
100
     * @param Config|array|null    $config
101
     * @param LoggerInterface|null $logger
102
     */
103 1
    public function __construct($config = null, ?LoggerInterface $logger = null)
104
    {
105
        // set logger
106 1
        if ($logger === null) {
107
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
108
        }
109 1
        $this->setLogger($logger);
110
        // set config
111 1
        $this->setConfig($config)->setSourceDir(null)->setDestinationDir(null);
112
        // debug mode?
113 1
        if (getenv('CECIL_DEBUG') == 'true' || (bool) $this->getConfig()->get('debug')) {
114 1
            $this->debug = true;
115
        }
116
        // autoloads local extensions
117 1
        Util::autoload($this, 'extensions');
118
    }
119
120
    /**
121
     * Creates a new Builder instance.
122
     */
123 1
    public static function create(): self
124
    {
125 1
        $class = new \ReflectionClass(\get_called_class());
126
127 1
        return $class->newInstanceArgs(\func_get_args());
128
    }
129
130
    /**
131
     * Builds a new website.
132
     */
133 1
    public function build(array $options): self
134
    {
135
        // set start script time and memory usage
136 1
        $startTime = microtime(true);
137 1
        $startMemory = memory_get_usage();
138
139
        // log configuration errors
140 1
        $this->logConfigError();
141
142
        // prepare options
143 1
        $this->options = array_merge([
144 1
            'drafts'  => false, // build drafts or not
145 1
            'dry-run' => false, // if dry-run is true, generated files are not saved
146 1
            'page'    => '',    // specific page to build
147 1
        ], $options);
148
149
        // process each step
150 1
        $steps = [];
151
        // init...
152 1
        foreach ($this->steps as $step) {
153
            /** @var Step\StepInterface $stepObject */
154 1
            $stepObject = new $step($this);
155 1
            $stepObject->init($this->options);
156 1
            if ($stepObject->canProcess()) {
157 1
                $steps[] = $stepObject;
158
            }
159
        }
160
        // ...and process!
161 1
        $stepNumber = 0;
162 1
        $stepsTotal = \count($steps);
163 1
        foreach ($steps as $step) {
164 1
            $stepNumber++;
165
            /** @var Step\StepInterface $step */
166 1
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
167 1
            $stepStartTime = microtime(true);
168 1
            $stepStartMemory = memory_get_usage();
169 1
            $step->process();
170
            // step duration and memory usage
171 1
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
172 1
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime((float) $stepStartTime);
173 1
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
174 1
            $this->getLogger()->info(\sprintf(
175 1
                '%s done in %s (%s)',
176 1
                $this->metrics['steps'][$stepNumber]['name'],
177 1
                $this->metrics['steps'][$stepNumber]['duration'],
178 1
                $this->metrics['steps'][$stepNumber]['memory']
179 1
            ));
180
        }
181
        // build duration and memory usage
182 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

182
        $this->metrics['total']['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $startTime);
Loading history...
183 1
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
184 1
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
185
186 1
        return $this;
187
    }
188
189
    /**
190
     * Set configuration.
191
     *
192
     * @param Config|array|null $config
193
     */
194 1
    public function setConfig($config): self
195
    {
196 1
        if (!$config instanceof Config) {
197 1
            $config = new Config($config);
198
        }
199 1
        if ($this->config !== $config) {
200 1
            $this->config = $config;
201
        }
202
203 1
        return $this;
204
    }
205
206
    /**
207
     * Returns configuration.
208
     */
209 1
    public function getConfig(): Config
210
    {
211 1
        return $this->config;
212
    }
213
214
    /**
215
     * Config::setSourceDir() alias.
216
     */
217 1
    public function setSourceDir(?string $sourceDir = null): self
218
    {
219 1
        $this->config->setSourceDir($sourceDir);
220
221 1
        return $this;
222
    }
223
224
    /**
225
     * Config::setDestinationDir() alias.
226
     */
227 1
    public function setDestinationDir(?string $destinationDir = null): self
228
    {
229 1
        $this->config->setDestinationDir($destinationDir);
230
231 1
        return $this;
232
    }
233
234
    /**
235
     * {@inheritdoc}
236
     */
237 1
    public function setLogger(LoggerInterface $logger): void
238
    {
239 1
        $this->logger = $logger;
240
    }
241
242
    /**
243
     * Returns the logger instance.
244
     */
245 1
    public function getLogger(): LoggerInterface
246
    {
247 1
        return $this->logger;
248
    }
249
250
    /**
251
     * Returns debug mode state.
252
     */
253 1
    public function isDebug(): bool
254
    {
255 1
        return (bool) $this->debug;
256
    }
257
258
    /**
259
     * Returns build options.
260
     */
261 1
    public function getBuildOptions(): array
262
    {
263 1
        return $this->options;
264
    }
265
266
    /**
267
     * Set collected pages files.
268
     */
269 1
    public function setPagesFiles(Finder $content): void
270
    {
271 1
        $this->content = $content;
272
    }
273
274
    /**
275
     * Returns pages files.
276
     */
277 1
    public function getPagesFiles(): ?Finder
278
    {
279 1
        return $this->content;
280
    }
281
282
    /**
283
     * Set collected data.
284
     */
285 1
    public function setData(array $data): void
286
    {
287 1
        $this->data = $data;
288
    }
289
290
    /**
291
     * Returns data collection.
292
     */
293 1
    public function getData(?string $language = null): ?array
294
    {
295 1
        if ($language) {
296 1
            if (empty($this->data[$language])) {
297
                // fallback to default language
298 1
                return $this->data[$this->config->getLanguageDefault()];
299
            }
300
301 1
            return $this->data[$language];
302
        }
303
304 1
        return $this->data;
305
    }
306
307
    /**
308
     * Set collected static files.
309
     */
310 1
    public function setStatic(array $static): void
311
    {
312 1
        $this->static = $static;
313
    }
314
315
    /**
316
     * Returns static files collection.
317
     */
318 1
    public function getStatic(): array
319
    {
320 1
        return $this->static;
321
    }
322
323
    /**
324
     * Set/update Pages collection.
325
     */
326 1
    public function setPages(PagesCollection $pages): void
327
    {
328 1
        $this->pages = $pages;
329
    }
330
331
    /**
332
     * Returns pages collection.
333
     */
334 1
    public function getPages(): ?PagesCollection
335
    {
336 1
        return $this->pages;
337
    }
338
339
    /**
340
     * Set menus collection.
341
     */
342 1
    public function setMenus(array $menus): void
343
    {
344 1
        $this->menus = $menus;
345
    }
346
347
    /**
348
     * Returns all menus, for a language.
349
     */
350 1
    public function getMenus(string $language): Collection\Menu\Collection
351
    {
352 1
        return $this->menus[$language];
353
    }
354
355
    /**
356
     * Set taxonomies collection.
357
     */
358 1
    public function setTaxonomies(array $taxonomies): void
359
    {
360 1
        $this->taxonomies = $taxonomies;
361
    }
362
363
    /**
364
     * Returns taxonomies collection, for a language.
365
     */
366 1
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
367
    {
368 1
        return $this->taxonomies[$language];
369
    }
370
371
    /**
372
     * Set renderer object.
373
     */
374 1
    public function setRenderer(Renderer\RendererInterface $renderer): void
375
    {
376 1
        $this->renderer = $renderer;
377
    }
378
379
    /**
380
     * Returns Renderer object.
381
     */
382 1
    public function getRenderer(): Renderer\RendererInterface
383
    {
384 1
        return $this->renderer;
385
    }
386
387
    /**
388
     * Returns metrics array.
389
     */
390
    public function getMetrics(): array
391
    {
392
        return $this->metrics;
393
    }
394
395
    /**
396
     * Returns application version.
397
     *
398
     * @throws RuntimeException
399
     */
400 1
    public static function getVersion(): string
401
    {
402 1
        if (!isset(self::$version)) {
403 1
            $filePath = __DIR__ . '/../VERSION';
404 1
            if (Platform::isPhar()) {
405
                $filePath = Platform::getPharPath() . '/VERSION';
406
            }
407
408
            try {
409 1
                if (!file_exists($filePath)) {
410 1
                    throw new RuntimeException(\sprintf('File "%s" doesn\'t exist.', $filePath));
411
                }
412
                $version = Util\File::fileGetContents($filePath);
413
                if ($version === false) {
414
                    throw new RuntimeException(\sprintf('Can\'t get file "%s".', $filePath));
415
                }
416
                self::$version = trim($version);
417 1
            } catch (\Exception) {
418 1
                self::$version = self::VERSION;
419
            }
420
        }
421
422 1
        return self::$version;
423
    }
424
425
    /**
426
     * Log configuration errors.
427
     */
428 1
    protected function logConfigError(): void
429
    {
430
        // warning about baseurl
431 1
        if (empty(trim((string) $this->config->get('baseurl'), '/'))) {
432 1
            $this->getLogger()->warning('`baseurl` configuration key is required in production.');
433
        }
434
    }
435
}
436