Passed
Pull Request — master (#1676)
by Arnaud
08:52 queued 03:11
created

Builder::validConfig()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 8.304

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 9
c 1
b 1
f 0
nc 10
nop 0
dl 0
loc 17
ccs 6
cts 10
cp 0.6
crap 8.304
rs 9.2222
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\Plateform;
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\Themes\Import',
41
        'Cecil\Step\Pages\Load',
42
        'Cecil\Step\Data\Load',
43
        'Cecil\Step\StaticFiles\Load',
44
        'Cecil\Step\Pages\Create',
45
        'Cecil\Step\Pages\Convert',
46
        'Cecil\Step\Taxonomies\Create',
47
        'Cecil\Step\Pages\Generate',
48
        'Cecil\Step\Menus\Create',
49
        'Cecil\Step\StaticFiles\Copy',
50
        'Cecil\Step\Pages\Render',
51
        'Cecil\Step\Pages\Save',
52
        'Cecil\Step\Optimize\Html',
53
        'Cecil\Step\Optimize\Css',
54
        'Cecil\Step\Optimize\Js',
55
        'Cecil\Step\Optimize\Images',
56
    ];
57
58
    /** @var Config Configuration. */
59
    protected $config;
60
61
    /** @var LoggerInterface Logger. */
62
    protected $logger;
63
64
    /** @var bool Debug mode. */
65
    protected $debug = false;
66
67
    /** @var array Build options. */
68
    protected $options;
69
70
    /** @var Finder Content iterator. */
71
    protected $content;
72
73
    /** @var array Data collection. */
74
    protected $data = [];
75
76
    /** @var array Static files collection. */
77
    protected $static = [];
78
79
    /** @var PagesCollection Pages collection. */
80
    protected $pages;
81
82
    /** @var array Menus collection. */
83
    protected $menus;
84
85
    /** @var Collection\Taxonomy\Collection Taxonomies collection. */
86
    protected $taxonomies;
87
88
    /** @var Renderer\RendererInterface Renderer. */
89
    protected $renderer;
90
91
    /** @var GeneratorManager Generators manager. */
92
    protected $generatorManager;
93
94
    /** @var string Application version. */
95
    protected static $version;
96
97
    /**
98
     * @param Config|array|null    $config
99
     * @param LoggerInterface|null $logger
100
     */
101 1
    public function __construct($config = null, LoggerInterface $logger = null)
102
    {
103
        // set logger
104 1
        if ($logger === null) {
105
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
106
        }
107 1
        $this->setLogger($logger);
108
        // set config
109 1
        $this->setConfig($config)->setSourceDir(null)->setDestinationDir(null);
110
        // debug mode?
111 1
        if (getenv('CECIL_DEBUG') == 'true' || (bool) $this->getConfig()->get('debug')) {
112 1
            $this->debug = true;
113
        }
114
    }
115
116
    /**
117
     * Creates a new Builder instance.
118
     */
119 1
    public static function create(): self
120
    {
121 1
        $class = new \ReflectionClass(get_called_class());
122
123 1
        return $class->newInstanceArgs(func_get_args());
124
    }
125
126
    /**
127
     * Builds a new website.
128
     */
129 1
    public function build(array $options): self
130
    {
131
        // set start script time and memory usage
132 1
        $startTime = microtime(true);
133 1
        $startMemory = memory_get_usage();
134
135
        // baseurl is required in production
136 1
        if (empty(trim((string) $this->config->get('baseurl'), '/'))) {
137
            $this->getLogger()->error(\sprintf('The current `baseurl` ("%s") is not valid for production (should be something like "baseurl: https://example.com/").', $this->config->get('baseurl')));
138
        }
139
140
        // prepare options
141 1
        $this->options = array_merge([
142 1
            'drafts'  => false, // build drafts or not
143 1
            'dry-run' => false, // if dry-run is true, generated files are not saved
144 1
            'page'    => '',    // specific page to build
145 1
        ], $options);
146
147
        // process each step
148 1
        $steps = [];
149
        // init...
150 1
        foreach ($this->steps as $step) {
151
            /** @var Step\StepInterface $stepObject */
152 1
            $stepObject = new $step($this);
153 1
            $stepObject->init($this->options);
154 1
            if ($stepObject->canProcess()) {
155 1
                $steps[] = $stepObject;
156
            }
157
        }
158
        // ...and process!
159 1
        $stepNumber = 0;
160 1
        $stepsTotal = count($steps);
161 1
        foreach ($steps as $step) {
162 1
            $stepNumber++;
163
            /** @var Step\StepInterface $step */
164 1
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
165 1
            $step->process();
166
        }
167
168
        // process duration
169 1
        $message = \sprintf('Built in %s s (%s)', round(microtime(true) - $startTime, 2), Util::convertMemory(memory_get_usage() - $startMemory));
170 1
        $this->getLogger()->notice($message);
171
172 1
        return $this;
173
    }
174
175
    /**
176
     * Set configuration.
177
     *
178
     * @param Config|array|null $config
179
     */
180 1
    public function setConfig($config): self
181
    {
182 1
        if (!$config instanceof Config) {
183 1
            $config = new Config($config);
184
        }
185 1
        if ($this->config !== $config) {
186 1
            $this->config = $config;
187
        }
188
189 1
        return $this;
190
    }
191
192
    /**
193
     * Returns configuration.
194
     */
195 1
    public function getConfig(): Config
196
    {
197 1
        return $this->config;
198
    }
199
200
    /**
201
     * Config::setSourceDir() alias.
202
     */
203 1
    public function setSourceDir(string $sourceDir = null): self
204
    {
205 1
        $this->config->setSourceDir($sourceDir);
206
207 1
        return $this;
208
    }
209
210
    /**
211
     * Config::setDestinationDir() alias.
212
     */
213 1
    public function setDestinationDir(string $destinationDir = null): self
214
    {
215 1
        $this->config->setDestinationDir($destinationDir);
216
217 1
        return $this;
218
    }
219
220
    /**
221
     * {@inheritdoc}
222
     */
223 1
    public function setLogger(LoggerInterface $logger)
224
    {
225 1
        $this->logger = $logger;
226
    }
227
228
    /**
229
     * Returns the logger instance.
230
     */
231 1
    public function getLogger(): LoggerInterface
232
    {
233 1
        return $this->logger;
234
    }
235
236
    /**
237
     * Returns debug mode state.
238
     */
239 1
    public function isDebug(): bool
240
    {
241 1
        return $this->debug;
242
    }
243
244
    /**
245
     * Returns build options.
246
     */
247 1
    public function getBuildOptions(): array
248
    {
249 1
        return $this->options;
250
    }
251
252
    /**
253
     * Set collected pages files.
254
     */
255 1
    public function setPagesFiles(Finder $content): void
256
    {
257 1
        $this->content = $content;
258
    }
259
260
    /**
261
     * Returns pages files.
262
     */
263 1
    public function getPagesFiles(): ?Finder
264
    {
265 1
        return $this->content;
266
    }
267
268
    /**
269
     * Set collected data.
270
     */
271 1
    public function setData(array $data): void
272
    {
273 1
        $this->data = $data;
274
    }
275
276
    /**
277
     * Returns data collection.
278
     */
279 1
    public function getData(): array
280
    {
281 1
        return $this->data;
282
    }
283
284
    /**
285
     * Set collected static files.
286
     */
287 1
    public function setStatic(array $static): void
288
    {
289 1
        $this->static = $static;
290
    }
291
292
    /**
293
     * Returns static files collection.
294
     */
295 1
    public function getStatic(): array
296
    {
297 1
        return $this->static;
298
    }
299
300
    /**
301
     * Set/update Pages collection.
302
     */
303 1
    public function setPages(PagesCollection $pages): void
304
    {
305 1
        $this->pages = $pages;
306
    }
307
308
    /**
309
     * Returns pages collection.
310
     */
311 1
    public function getPages(): ?PagesCollection
312
    {
313 1
        return $this->pages;
314
    }
315
316
    /**
317
     * Set menus collection.
318
     */
319 1
    public function setMenus(array $menus): void
320
    {
321 1
        $this->menus = $menus;
322
    }
323
324
    /**
325
     * Returns all menus, for a language.
326
     */
327 1
    public function getMenus(string $language): Collection\Menu\Collection
328
    {
329 1
        return $this->menus[$language];
330
    }
331
332
    /**
333
     * Set taxonomies collection.
334
     */
335 1
    public function setTaxonomies(Collection\Taxonomy\Collection $taxonomies): void
336
    {
337 1
        $this->taxonomies = $taxonomies;
338
    }
339
340
    /**
341
     * Returns taxonomies collection.
342
     */
343 1
    public function getTaxonomies(): ?Collection\Taxonomy\Collection
344
    {
345 1
        return $this->taxonomies;
346
    }
347
348
    /**
349
     * Set renderer object.
350
     */
351 1
    public function setRenderer(Renderer\RendererInterface $renderer): void
352
    {
353 1
        $this->renderer = $renderer;
354
    }
355
356
    /**
357
     * Returns Renderer object.
358
     */
359 1
    public function getRenderer(): Renderer\RendererInterface
360
    {
361 1
        return $this->renderer;
362
    }
363
364
    /**
365
     * Returns application version.
366
     *
367
     * @throws RuntimeException
368
     */
369 1
    public static function getVersion(): string
370
    {
371 1
        if (!isset(self::$version)) {
372 1
            $filePath = __DIR__ . '/../VERSION';
373 1
            if (Plateform::isPhar()) {
374
                $filePath = Plateform::getPharPath() . '/VERSION';
375
            }
376
377
            try {
378 1
                if (!file_exists($filePath)) {
379 1
                    throw new RuntimeException(\sprintf('%s file doesn\'t exist!', $filePath));
380
                }
381
                $version = Util\File::fileGetContents($filePath);
382
                if ($version === false) {
383
                    throw new RuntimeException(\sprintf('Can\'t get %s file!', $filePath));
384
                }
385
                self::$version = trim($version);
386 1
            } catch (\Exception $e) {
387 1
                self::$version = self::VERSION;
388
            }
389
        }
390
391 1
        return self::$version;
392
    }
393
}
394