Completed
Push — master ( 54fa46...73d26f )
by Vladimir
02:25
created

Website   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 334
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 25
Bugs 0 Features 0
Metric Value
dl 0
loc 334
rs 10
c 25
b 0
f 0
wmc 27
lcom 1
cbo 13

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A build() 0 61 2
B watch() 0 39 5
A getConfiguration() 0 4 1
A setConfiguration() 0 17 4
A isConfLess() 0 4 1
A setConfLess() 0 4 1
A isSafeMode() 0 4 1
A setSafeMode() 0 4 1
A isNoClean() 0 4 1
A setNoClean() 0 4 1
B modificationWatcher() 0 30 6
A createFolderStructure() 0 13 2
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_MODIFIED:
199
                        $this->modificationWatcher($filePath);
200
                        break;
201
                }
202
            }
203
            catch (\Exception $e)
204
            {
205
                $this->output->error(sprintf("Your website failed to build with the following error: %s",
206
                    $e->getMessage()
207
                ));
208
            }
209
        });
210
211
        $watcher->start();
212
    }
213
214
    /**
215
     * @return Configuration
216
     */
217
    public function getConfiguration ()
218
    {
219
        return $this->configuration;
220
    }
221
222
    /**
223
     * @param string $configFile
224
     *
225
     * @throws \LogicException
226
     */
227
    public function setConfiguration ($configFile)
228
    {
229
        if (!$this->fs->exists($configFile) && !$this->isConfLess())
230
        {
231
            $this->output->error("You are trying to build a website in a directory without a configuration file. Is this what you meant to do?");
232
            $this->output->error("To build a website without a configuration, use the '--no-conf' option");
233
234
            throw new \LogicException("Cannot build a website without a configuration when not in Configuration-less mode");
235
        }
236
237
        if ($this->isConfLess())
238
        {
239
            $configFile = "";
240
        }
241
242
        $this->configuration = new Configuration($configFile, $this->output);
243
    }
244
245
    /**
246
     * Get whether or not the website is being built in Configuration-less mode
247
     *
248
     * @return bool True when being built with no configuration file
249
     */
250
    public function isConfLess ()
251
    {
252
        return $this->confLess;
253
    }
254
255
    /**
256
     * Set whether or not the website should be built with a configuration
257
     *
258
     * @param bool $status True when a website should be built without a configuration
259
     */
260
    public function setConfLess ($status)
261
    {
262
        $this->confLess = $status;
263
    }
264
265
    /**
266
     * Get whether or not the website is being built in safe mode.
267
     *
268
     * Safe mode is defined as disabling file system access from Twig and disabling user Twig extensions
269
     *
270
     * @return bool True when the website is being built in safe mode
271
     */
272
    public function isSafeMode ()
273
    {
274
        return $this->safeMode;
275
    }
276
277
    /**
278
     * Set whether a website should be built in safe mode
279
     *
280
     * @param bool $bool True if a website should be built in safe mode
281
     */
282
    public function setSafeMode ($bool)
283
    {
284
        $this->safeMode = $bool;
285
    }
286
287
    /**
288
     * @return boolean
289
     */
290
    public function isNoClean()
291
    {
292
        return $this->noClean;
293
    }
294
295
    /**
296
     * @param boolean $noClean
297
     */
298
    public function setNoClean($noClean)
299
    {
300
        $this->noClean = $noClean;
301
    }
302
303
    private function modificationWatcher ($filePath)
304
    {
305
        $this->output->writeln(sprintf("File change detected: %s", $filePath));
306
307
        if ($this->pm->isTracked($filePath))
308
        {
309
            $this->pm->refreshItem($filePath);
310
        }
311
        else if ($this->cm->isTracked($filePath))
312
        {
313
            $contentItem = &$this->cm->getContentItem($filePath);
314
            $contentItem->refreshFileContent();
315
316
            $this->pm->compileContentItem($contentItem);
0 ignored issues
show
Bug introduced by
It seems like $contentItem defined by $this->cm->getContentItem($filePath) on line 313 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...
317
        }
318
        else if ($this->dm->isTracked($filePath))
319
        {
320
            $this->dm->refreshItem($filePath);
321
            $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...
322
            $this->pm->compileAll();
323
        }
324
        else if ($this->tm->isTracked($filePath))
325
        {
326
            $this->tm->refreshItem($filePath);
327
        }
328
        else if ($this->am->isTracked($filePath))
329
        {
330
            $this->am->refreshItem($filePath);
331
        }
332
    }
333
334
    /**
335
     * Prepare the Stakx environment by creating necessary cache folders
336
     *
337
     * @param bool $cleanDirectory Clean the target directory
338
     */
339
    private function createFolderStructure ($cleanDirectory)
340
    {
341
        $tarDir = $this->fs->absolutePath($this->configuration->getTargetFolder());
342
343
        if ($cleanDirectory)
344
        {
345
            $this->fs->remove($tarDir);
346
        }
347
348
        $this->fs->remove($this->fs->absolutePath('.stakx-cache'));
349
        $this->fs->mkdir('.stakx-cache/twig');
350
        $this->fs->mkdir($tarDir);
351
    }
352
}