Completed
Push — master ( 827100...0aed89 )
by Vladimir
02:24
created

Website::modificationWatcher()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 6
nop 1
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace allejo\stakx\Object;
4
5
use allejo\stakx\Core\ConsoleInterface;
6
use allejo\stakx\Manager\AssetManager;
7
use allejo\stakx\Manager\PageManager;
8
use allejo\stakx\Manager\ThemeManager;
9
use allejo\stakx\System\Filesystem;
10
use allejo\stakx\Manager\CollectionManager;
11
use allejo\stakx\Manager\DataManager;
12
use allejo\stakx\System\Folder;
13
use JasonLewis\ResourceWatcher\Event;
14
use JasonLewis\ResourceWatcher\Resource\FileResource;
15
use JasonLewis\ResourceWatcher\Tracker;
16
use JasonLewis\ResourceWatcher\Watcher;
17
use Symfony\Component\Console\Output\OutputInterface;
18
19
class Website
20
{
21
    /**
22
     * The location of where the compiled website will be written to
23
     *
24
     * @var Folder
25
     */
26
    private $outputDirectory;
27
28
    /**
29
     * The main configuration to be used to build the specified website
30
     *
31
     * @var Configuration
32
     */
33
    private $configuration;
34
35
    /**
36
     * When set to true, the Stakx website will be built without a configuration file
37
     *
38
     * @var bool
39
     */
40
    private $confLess;
41
42
    /**
43
     * When set to true, Twig templates will not have access to filters or functions which provide access to the
44
     * filesystem
45
     *
46
     * @var bool
47
     */
48
    private $safeMode;
49
50
    /**
51
     * When set to true, Stakx will not clean the _site folder after a rebuild
52
     *
53
     * @var bool
54
     */
55
    private $noClean;
56
57
    /**
58
     * @var ConsoleInterface
59
     */
60
    private $output;
61
62
    /**
63
     * @var AssetManager
64
     */
65
    private $am;
66
67
    /**
68
     * @var CollectionManager
69
     */
70
    private $cm;
71
72
    /**
73
     * @var DataManager
74
     */
75
    private $dm;
76
77
    /**
78
     * @var Filesystem
79
     */
80
    private $fs;
81
82
    /**
83
     * @var PageManager
84
     */
85
    private $pm;
86
87
    /**
88
     * @var ThemeManager
89
     */
90
    private $tm;
91
92
    /**
93
     * Website constructor.
94
     *
95
     * @param OutputInterface $output
96
     */
97
    public function __construct (OutputInterface $output)
98
    {
99
        $this->output = new ConsoleInterface($output);
100
        $this->cm = new CollectionManager();
101
        $this->dm = new DataManager();
102
        $this->pm = new PageManager();
103
        $this->fs = new Filesystem();
104
    }
105
106
    /**
107
     * Compile the website.
108
     *
109
     * @param bool $cleanDirectory Clean the target directing before rebuilding
0 ignored issues
show
Bug introduced by
There is no parameter named $cleanDirectory. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
110
     * @param bool $tracking       Whether or not to keep track of files as they're compiled to save time in 'watch'
111
     */
112
    public function build ($tracking = false)
113
    {
114
        // Configure the environment
115
        $this->createFolderStructure(!$this->noClean);
116
117
        // Our output directory
118
        $this->outputDirectory = new Folder($this->getConfiguration()->getTargetFolder());
119
        $this->outputDirectory->setTargetDirectory($this->getConfiguration()->getBaseUrl());
120
121
        // Parse DataItems
122
        $this->dm->setConsoleOutput($this->output);
123
        $this->dm->parseDataItems($this->getConfiguration()->getDataFolders());
124
        $this->dm->parseDataSets($this->getConfiguration()->getDataSets());
125
126
        // Prepare Collections
127
        $this->cm->setConsoleOutput($this->output);
128
        $this->cm->parseCollections($this->getConfiguration()->getCollectionsFolders());
129
130
        // Handle PageViews
131
        $this->pm->setConsoleOutput($this->output);
132
        $this->pm->setTargetFolder($this->outputDirectory);
133
        $this->pm->setCollections($this->cm->getCollections());
134
        $this->pm->parsePageViews($this->getConfiguration()->getPageViewFolders());
135
        $this->pm->configureTwig($this->getConfiguration(), array(
136
            'safe'    => $this->safeMode,
137
            'globals' => array(
138
                array('name' => 'site',        'value' => $this->getConfiguration()->getConfiguration()),
139
                array('name' => 'collections', 'value' => $this->cm->getCollections()),
140
                array('name' => 'menu',        'value' => $this->pm->getSiteMenu()),
141
                array('name' => 'data',        'value' => $this->dm->getDataItems())
142
            )
143
        ));
144
        $this->pm->compileAll();
145
146
        //
147
        // Theme Management
148
        //
149
        $theme = $this->configuration->getTheme();
150
151
        if (!is_null($theme))
152
        {
153
            $this->output->notice("Looking for '${theme}' theme...");
154
155
            $this->tm = new ThemeManager($theme);
156
            $this->tm->configureFinder($this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
157
            $this->tm->setConsoleOutput($this->output);
158
            $this->tm->enableTracking($tracking);
159
            $this->tm->setFolder($this->outputDirectory);
160
            $this->tm->copyFiles();
161
        }
162
163
        //
164
        // Static file management
165
        //
166
        $this->am = new AssetManager();
167
        $this->am->configureFinder($this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
168
        $this->am->setConsoleOutput($this->output);
169
        $this->am->setFolder($this->outputDirectory);
170
        $this->am->enableTracking($tracking);
171
        $this->am->copyFiles();
172
    }
173
174
    public function watch ()
175
    {
176
        $this->build(true);
177
178
        $tracker    = new Tracker();
179
        $watcher    = new Watcher($tracker, $this->fs);
180
        $listener   = $watcher->watch(getcwd());
181
        $targetPath = $this->getConfiguration()->getTargetFolder();
182
183
        $this->output->notice('Watch started successfully');
184
185
        $listener->onAnything(function (Event $event, FileResource $resouce, $path) use ($targetPath) {
186
            $filePath = $this->fs->getRelativePath($path);
187
188
            if ((substr($filePath, 0, strlen($targetPath)) === $targetPath) ||
189
                (substr($filePath, 0, 1) === '.'))
190
            {
191
                return;
192
            }
193
194
            try
195
            {
196
                switch ($event->getCode())
197
                {
198
                    case Event::RESOURCE_CREATED:
199
                        $this->creationWatcher($filePath);
200
                        break;
201
202
                    case Event::RESOURCE_MODIFIED:
203
                        $this->modificationWatcher($filePath);
204
                        break;
205
                }
206
            }
207
            catch (\Exception $e)
208
            {
209
                $this->output->error(sprintf("Your website failed to build with the following error: %s",
210
                    $e->getMessage()
211
                ));
212
            }
213
        });
214
215
        $watcher->start();
216
    }
217
218
    /**
219
     * @return Configuration
220
     */
221
    public function getConfiguration ()
222
    {
223
        return $this->configuration;
224
    }
225
226
    /**
227
     * @param string $configFile
228
     *
229
     * @throws \LogicException
230
     */
231
    public function setConfiguration ($configFile)
232
    {
233
        if (!$this->fs->exists($configFile) && !$this->isConfLess())
234
        {
235
            $this->output->error("You are trying to build a website in a directory without a configuration file. Is this what you meant to do?");
236
            $this->output->error("To build a website without a configuration, use the '--no-conf' option");
237
238
            throw new \LogicException("Cannot build a website without a configuration when not in Configuration-less mode");
239
        }
240
241
        if ($this->isConfLess())
242
        {
243
            $configFile = "";
244
        }
245
246
        $this->configuration = new Configuration($configFile, $this->output);
247
    }
248
249
    /**
250
     * Get whether or not the website is being built in Configuration-less mode
251
     *
252
     * @return bool True when being built with no configuration file
253
     */
254
    public function isConfLess ()
255
    {
256
        return $this->confLess;
257
    }
258
259
    /**
260
     * Set whether or not the website should be built with a configuration
261
     *
262
     * @param bool $status True when a website should be built without a configuration
263
     */
264
    public function setConfLess ($status)
265
    {
266
        $this->confLess = $status;
267
    }
268
269
    /**
270
     * Get whether or not the website is being built in safe mode.
271
     *
272
     * Safe mode is defined as disabling file system access from Twig and disabling user Twig extensions
273
     *
274
     * @return bool True when the website is being built in safe mode
275
     */
276
    public function isSafeMode ()
277
    {
278
        return $this->safeMode;
279
    }
280
281
    /**
282
     * Set whether a website should be built in safe mode
283
     *
284
     * @param bool $bool True if a website should be built in safe mode
285
     */
286
    public function setSafeMode ($bool)
287
    {
288
        $this->safeMode = $bool;
289
    }
290
291
    /**
292
     * @return boolean
293
     */
294
    public function isNoClean()
295
    {
296
        return $this->noClean;
297
    }
298
299
    /**
300
     * @param boolean $noClean
301
     */
302
    public function setNoClean($noClean)
303
    {
304
        $this->noClean = $noClean;
305
    }
306
307
    private function creationWatcher ($filePath)
308
    {
309
        $this->output->writeln(sprintf("File creation detected: %s", $filePath));
310
    }
311
312
    private function modificationWatcher ($filePath)
313
    {
314
        $this->output->writeln(sprintf("File change detected: %s", $filePath));
315
316
        if ($this->pm->isTracked($filePath))
317
        {
318
            $this->pm->refreshItem($filePath);
319
        }
320
        else if ($this->cm->isTracked($filePath))
321
        {
322
            $contentItem = &$this->cm->getContentItem($filePath);
323
            $contentItem->refreshFileContent();
324
325
            $this->pm->compileContentItem($contentItem);
0 ignored issues
show
Bug introduced by
It seems like $contentItem defined by $this->cm->getContentItem($filePath) on line 322 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...
326
        }
327
        else if ($this->dm->isTracked($filePath))
328
        {
329
            $change = $this->dm->refreshItem($filePath);
330
331
            $this->pm->updateTwigVariable('data', $this->dm->getDataItems());
0 ignored issues
show
Documentation introduced by
$this->dm->getDataItems() is of type array, but the function expects a string.

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...
332
            $this->pm->compileSome(array(
333
                'namespace' => 'data',
334
                'dependency' => $change
335
            ));
336
        }
337
        else if ($this->tm->isTracked($filePath))
338
        {
339
            $this->tm->refreshItem($filePath);
340
        }
341
        else if ($this->am->isTracked($filePath))
342
        {
343
            $this->am->refreshItem($filePath);
344
        }
345
    }
346
347
    /**
348
     * Prepare the Stakx environment by creating necessary cache folders
349
     *
350
     * @param bool $cleanDirectory Clean the target directory
351
     */
352
    private function createFolderStructure ($cleanDirectory)
353
    {
354
        $tarDir = $this->fs->absolutePath($this->configuration->getTargetFolder());
355
356
        if ($cleanDirectory)
357
        {
358
            $this->fs->remove($tarDir);
359
        }
360
361
        $this->fs->remove($this->fs->absolutePath('.stakx-cache'));
362
        $this->fs->mkdir('.stakx-cache/twig');
363
        $this->fs->mkdir($tarDir);
364
    }
365
}