Completed
Push — master ( 6a50c0...c1563b )
by Vladimir
02:57
created

Website::copyStaticFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 7
b 0
f 0
nc 2
nop 0
dl 0
loc 13
rs 9.4285
ccs 0
cts 9
cp 0
crap 6
1
<?php
2
3
namespace allejo\stakx\Object;
4
5
use allejo\stakx\Core\ConsoleInterface;
6
use allejo\stakx\Engines\TwigMarkdownEngine;
7
use allejo\stakx\Manager\AssetManager;
8
use allejo\stakx\Manager\PageManager;
9
use allejo\stakx\Manager\ThemeManager;
10
use allejo\stakx\System\Filesystem;
11
use allejo\stakx\Manager\CollectionManager;
12
use allejo\stakx\Manager\DataManager;
13
use allejo\stakx\System\Folder;
14
use allejo\stakx\Twig\FilesystemExtension;
15
use allejo\stakx\Twig\TwigExtension;
16
use Aptoma\Twig\Extension\MarkdownExtension;
17
use JasonLewis\ResourceWatcher\Tracker;
18
use JasonLewis\ResourceWatcher\Watcher;
19
use Symfony\Component\Console\Output\OutputInterface;
20
use Twig_Environment;
21
use Twig_Loader_Filesystem;
22
23
class Website
24
{
25
    private static $twig_ref;
26
27
    /**
28
     * The Twig environment that will be used to render pages. This includes all of the loaded extensions and global
29
     * variables.
30
     *
31
     * @var Twig_Environment
32
     */
33
    private $twig;
34
35
    /**
36
     * The location of where the compiled website will be written to
37
     *
38
     * @var Folder
39
     */
40
    private $outputDirectory;
41
42
    /**
43
     * The main configuration to be used to build the specified website
44
     *
45
     * @var Configuration
46
     */
47
    private $configuration;
48
49
    /**
50
     * When set to true, the Stakx website will be built without a configuration file
51
     *
52
     * @var bool
53
     */
54
    private $confLess;
55
56
    /**
57
     * When set to true, Twig templates will not have access to filters or functions which provide access to the
58
     * filesystem
59
     *
60
     * @var bool
61
     */
62
    private $safeMode;
63
64
    /**
65
     * @var ConsoleInterface
66
     */
67
    private $output;
68
69
    /**
70
     * @var AssetManager
71
     */
72
    private $am;
73
74
    /**
75
     * @var CollectionManager
76
     */
77
    private $cm;
78
79
    /**
80
     * @var DataManager
81
     */
82
    private $dm;
83
84
    /**
85
     * @var Filesystem
86
     */
87
    private $fs;
88
89
    /**
90
     * @var PageManager
91
     */
92
    private $pm;
93
94
    /**
95
     * @var ThemeManager
96
     */
97
    private $tm;
98
99
    /**
100
     * Website constructor.
101
     *
102
     * @param OutputInterface $output
103
     */
104
    public function __construct (OutputInterface $output)
105
    {
106
        $this->output = new ConsoleInterface($output);
107
        $this->cm = new CollectionManager();
108
        $this->dm = new DataManager();
109
        $this->pm = new PageManager();
110
        $this->fs = new Filesystem();
111
    }
112
113
    /**
114
     * Compile the website.
115
     *
116
     * @param bool $cleanDirectory Clean the target directing before rebuilding
117
     */
118
    public function build ($cleanDirectory)
119
    {
120
        // Parse DataItems
121
        $this->dm->setConsoleOutput($this->output);
122
        $this->dm->parseDataItems($this->getConfiguration()->getDataFolders());
123
        $this->dm->parseDataSets($this->getConfiguration()->getDataSets());
124
125
        // Prepare Collections
126
        $this->cm->setConsoleOutput($this->output);
127
        $this->cm->parseCollections($this->getConfiguration()->getCollectionsFolders());
128
129
        // Handle PageViews
130
        $this->pm->setConsoleOutput($this->output);
131
        $this->pm->setTwig($this->twig);
132
        $this->pm->parsePageViews($this->getConfiguration()->getPageViewFolders());
133
        $this->pm->prepareDynamicPageViews($this->cm->getCollections());
0 ignored issues
show
Documentation introduced by
$this->cm->getCollections() is of type array<integer,array<inte...x\Object\ContentItem>>>, but the function expects a array<integer,object<all...kx\Object\ContentItem>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
134
135
        // Configure the environment
136
        $this->createFolderStructure($cleanDirectory);
137
        $this->configureTwig();
138
139
        // Our output directory
140
        $this->outputDirectory = new Folder($this->getConfiguration()->getTargetFolder());
141
        $this->outputDirectory->setTargetDirectory($this->getConfiguration()->getBaseUrl());
142
143
        //
144
        // Theme Management
145
        //
146
        $theme = $this->configuration->getTheme();
147
148
        if (!is_null($theme))
149
        {
150
            $this->output->notice("Looking for '${theme}' theme...");
151
152
            $this->tm = new ThemeManager($theme, $this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
153
            $this->tm->setConsoleOutput($this->output);
154
            $this->tm->setFolder($this->outputDirectory);
155
            $this->tm->copyFiles();
156
        }
157
158
        //
159
        // Static file management
160
        //
161
        $this->am = new AssetManager($this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
162
        $this->am->setConsoleOutput($this->output);
163
        $this->am->setFolder($this->outputDirectory);
164
        $this->am->copyFiles();
165
166
        //
167
        // Compiler
168
        //
169
        $this->output->notice('Compiling files...');
170
        $this->pm->compileAll(
171
            $this->outputDirectory
172
        );
173
    }
174
175
    public function watch ()
176
    {
177
        $this->build(true);
178
179
        $tracker    = new Tracker();
180
        $watcher    = new Watcher($tracker, $this->fs);
181
        $listener   = $watcher->watch(getcwd());
182
        $targetPath = $this->getConfiguration()->getTargetFolder();
183
184
        $this->output->notice('Watch started successfully');
185
186
        $listener->onModify(function ($resource, $path) use ($targetPath) {
187
            $filePath = $this->fs->getRelativePath($path);
188
189
            if ((substr($filePath, 0, strlen($targetPath)) === $targetPath) ||
190
                (substr($filePath, 0, 1) === '.'))
191
            {
192
                return;
193
            }
194
195
            $this->output->writeln(sprintf("File change detected: %s", $filePath));
196
197
            try
198
            {
199
                if ($this->pm->isPageView($filePath))
200
                {
201
                    $this->pm->compileSingle($filePath);
202
                }
203
                else if ($this->cm->isContentItem($filePath))
204
                {
205
                    $contentItem = &$this->cm->getContentItem($filePath);
206
                    $contentItem->refreshFileContent();
207
208
                    $this->pm->compileContentItem($contentItem);
0 ignored issues
show
Bug introduced by
It seems like $contentItem defined by $this->cm->getContentItem($filePath) on line 205 can be null; however, allejo\stakx\Manager\Pag...r::compileContentItem() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
209
                }
210
            }
211
            catch (\Exception $e)
212
            {
213
                $this->output->error(sprintf("Your website failed to build with the following error: %s",
214
                    $e->getMessage()
215
                ));
216
            }
217
        });
218
219
        $watcher->start();
220
    }
221
222
    /**
223
     * @return Configuration
224
     */
225
    public function getConfiguration ()
226
    {
227
        return $this->configuration;
228
    }
229
230
    /**
231
     * @param string $configFile
232
     *
233
     * @throws \LogicException
234
     */
235
    public function setConfiguration ($configFile)
236
    {
237
        if (!$this->fs->exists($configFile) && !$this->isConfLess())
238
        {
239
            $this->output->error("You are trying to build a website in a directory without a configuration file. Is this what you meant to do?");
240
            $this->output->error("To build a website without a configuration, use the '--no-conf' option");
241
242
            throw new \LogicException("Cannot build a website without a configuration when not in Configuration-less mode");
243
        }
244
245
        if ($this->isConfLess())
246
        {
247
            $configFile = "";
248
        }
249
250
        $this->configuration = new Configuration($configFile, $this->output);
251
    }
252
253
    /**
254
     * Get whether or not the website is being built in Configuration-less mode
255
     *
256
     * @return bool True when being built with no configuration file
257
     */
258
    public function isConfLess ()
259
    {
260
        return $this->confLess;
261
    }
262
263
    /**
264
     * Set whether or not the website should be built with a configuration
265
     *
266
     * @param bool $status True when a website should be built without a configuration
267
     */
268
    public function setConfLess ($status)
269
    {
270
        $this->confLess = $status;
271
    }
272
273
    /**
274
     * Get whether or not the website is being built in safe mode.
275
     *
276
     * Safe mode is defined as disabling file system access from Twig and disabling user Twig extensions
277
     *
278
     * @return bool True when the website is being built in safe mode
279
     */
280
    public function isSafeMode ()
281
    {
282
        return $this->safeMode;
283
    }
284
285
    /**
286
     * Set whether a website should be built in safe mode
287
     *
288
     * @param bool $bool True if a website should be built in safe mode
289
     */
290
    public function setSafeMode ($bool)
291
    {
292
        $this->safeMode = $bool;
293
    }
294
295
    public static function getTwigInstance ()
296
    {
297 3
        return self::$twig_ref;
298
    }
299
300
    /**
301
     * Prepare the Stakx environment by creating necessary cache folders
302
     *
303
     * @param bool $cleanDirectory Clean the target directory
304
     */
305
    private function createFolderStructure ($cleanDirectory)
306
    {
307
        $tarDir = $this->fs->absolutePath($this->configuration->getTargetFolder());
308
309
        if ($cleanDirectory)
310
        {
311
            $this->fs->remove($tarDir);
312
        }
313
314
        $this->fs->remove($this->fs->absolutePath('.stakx-cache'));
315
        $this->fs->mkdir('.stakx-cache/twig');
316
        $this->fs->mkdir($tarDir);
317
    }
318
319
    /**
320
     * Configure the Twig environment used by Stakx. This includes loading themes, global variables, extensions, and
321
     * debug settings.
322
     *
323
     * @todo Load custom Twig extensions from _config.yml
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
324
     */
325
    private function configureTwig ()
326
    {
327
        $loader   = new Twig_Loader_Filesystem(array(
328
            getcwd()
329
        ));
330
        $theme    = $this->configuration->getTheme();
331
        $mdEngine = new TwigMarkdownEngine();
332
333
        // Only load a theme if one is specified and actually exists
334
        if (!is_null($theme))
335
        {
336
            try
337
            {
338
                $loader->addPath($this->fs->absolutePath('_themes', $this->configuration->getTheme()), 'theme');
339
            }
340
            catch (\Twig_Error_Loader $e)
341
            {
342
                $this->output->error("The following theme could not be loaded: {theme}", array(
343
                    "theme" => $theme
344
                ));
345
                $this->output->error($e->getMessage());
346
            }
347
        }
348
349
        $this->twig = new Twig_Environment($loader, array(
350
            'autoescape' => $this->getConfiguration()->getTwigAutoescape(),
351
            //'cache'      => '.stakx-cache/twig'
352
        ));
353
354
        $this->twig->addGlobal('site', $this->configuration->getConfiguration());
355
        $this->twig->addGlobal('collections', $this->cm->getCollections());
356
        $this->twig->addGlobal('menu', $this->pm->getSiteMenu());
357
        $this->twig->addGlobal('data', $this->dm->getDataItems());
358
        $this->twig->addExtension(new TwigExtension());
359
        $this->twig->addExtension(new \Twig_Extensions_Extension_Text());
360
        $this->twig->addExtension(new MarkdownExtension($mdEngine));
361
362
        if (!$this->safeMode)
363
        {
364
            $this->twig->addExtension(new FilesystemExtension());
365
        }
366
367
        if ($this->configuration->isDebug())
368
        {
369
            $this->twig->addExtension(new \Twig_Extension_Debug());
370
            $this->twig->enableDebug();
371
        }
372
373
        self::$twig_ref = &$this->twig;
374
    }
375
}