Completed
Pull Request — master (#11)
by Vladimir
02:33
created

Website::watch()   C

Complexity

Conditions 9
Paths 1

Size

Total Lines 60
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 9
eloc 32
nc 1
nop 0
dl 0
loc 60
rs 6.8358
c 6
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Tracker;
14
use JasonLewis\ResourceWatcher\Watcher;
15
use Symfony\Component\Console\Output\OutputInterface;
16
17
class Website
18
{
19
    /**
20
     * The location of where the compiled website will be written to
21
     *
22
     * @var Folder
23
     */
24
    private $outputDirectory;
25
26
    /**
27
     * The main configuration to be used to build the specified website
28
     *
29
     * @var Configuration
30
     */
31
    private $configuration;
32
33
    /**
34
     * When set to true, the Stakx website will be built without a configuration file
35
     *
36
     * @var bool
37
     */
38
    private $confLess;
39
40
    /**
41
     * When set to true, Twig templates will not have access to filters or functions which provide access to the
42
     * filesystem
43
     *
44
     * @var bool
45
     */
46
    private $safeMode;
47
48
    /**
49
     * @var ConsoleInterface
50
     */
51
    private $output;
52
53
    /**
54
     * @var AssetManager
55
     */
56
    private $am;
57
58
    /**
59
     * @var CollectionManager
60
     */
61
    private $cm;
62
63
    /**
64
     * @var DataManager
65
     */
66
    private $dm;
67
68
    /**
69
     * @var Filesystem
70
     */
71
    private $fs;
72
73
    /**
74
     * @var PageManager
75
     */
76
    private $pm;
77
78
    /**
79
     * @var ThemeManager
80
     */
81
    private $tm;
82
83
    /**
84
     * Website constructor.
85
     *
86
     * @param OutputInterface $output
87
     */
88
    public function __construct (OutputInterface $output)
89
    {
90
        $this->output = new ConsoleInterface($output);
91
        $this->cm = new CollectionManager();
92
        $this->dm = new DataManager();
93
        $this->pm = new PageManager();
94
        $this->fs = new Filesystem();
95
    }
96
97
    /**
98
     * Compile the website.
99
     *
100
     * @param bool $cleanDirectory Clean the target directing before rebuilding
101
     * @param bool $tracking       Whether or not to keep track of files as they're compiled to save time in 'watch'
102
     */
103
    public function build ($cleanDirectory, $tracking = false)
104
    {
105
        // Configure the environment
106
        $this->createFolderStructure($cleanDirectory);
107
108
        // Parse DataItems
109
        $this->dm->setConsoleOutput($this->output);
110
        $this->dm->parseDataItems($this->getConfiguration()->getDataFolders());
111
        $this->dm->parseDataSets($this->getConfiguration()->getDataSets());
112
113
        // Prepare Collections
114
        $this->cm->setConsoleOutput($this->output);
115
        $this->cm->parseCollections($this->getConfiguration()->getCollectionsFolders());
116
117
        // Handle PageViews
118
        $this->pm->setConsoleOutput($this->output);
119
        $this->pm->parsePageViews($this->getConfiguration()->getPageViewFolders());
120
        $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...
121
        $this->pm->configureTwig($this->getConfiguration(), array(
122
            'safe'    => $this->safeMode,
123
            'globals' => array(
124
                array('name' => 'site',        'value' => $this->getConfiguration()->getConfiguration()),
125
                array('name' => 'collections', 'value' => $this->cm->getCollections()),
126
                array('name' => 'menu',        'value' => $this->pm->getSiteMenu()),
127
                array('name' => 'data',        'value' => $this->dm->getDataItems())
128
            )
129
        ));
130
131
        // Our output directory
132
        $this->outputDirectory = new Folder($this->getConfiguration()->getTargetFolder());
133
        $this->outputDirectory->setTargetDirectory($this->getConfiguration()->getBaseUrl());
134
135
        //
136
        // Theme Management
137
        //
138
        $theme = $this->configuration->getTheme();
139
140
        if (!is_null($theme))
141
        {
142
            $this->output->notice("Looking for '${theme}' theme...");
143
144
            $this->tm = new ThemeManager($theme, $this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
145
            $this->tm->setConsoleOutput($this->output);
146
            $this->tm->setTracking($tracking);
147
            $this->tm->setFolder($this->outputDirectory);
148
            $this->tm->copyFiles();
149
        }
150
151
        //
152
        // Static file management
153
        //
154
        $this->am = new AssetManager($this->getConfiguration()->getIncludes(), $this->getConfiguration()->getExcludes());
155
        $this->am->setConsoleOutput($this->output);
156
        $this->am->setFolder($this->outputDirectory);
0 ignored issues
show
Documentation introduced by
$this->outputDirectory is of type object<allejo\stakx\System\Folder>, but the function expects a object<allejo\stakx\Manager\Folder>.

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...
157
        $this->am->enableTracking($tracking);
158
        $this->am->copyFiles();
159
160
        //
161
        // Compiler
162
        //
163
        $this->output->notice('Compiling files...');
164
        $this->pm->compileAll(
165
            $this->outputDirectory
166
        );
167
    }
168
169
    public function watch ()
170
    {
171
        $this->build(true, true);
172
173
        $tracker    = new Tracker();
174
        $watcher    = new Watcher($tracker, $this->fs);
175
        $listener   = $watcher->watch(getcwd());
176
        $targetPath = $this->getConfiguration()->getTargetFolder();
177
178
        $this->output->notice('Watch started successfully');
179
180
        $listener->onModify(function ($resource, $path) use ($targetPath) {
181
            $filePath = $this->fs->getRelativePath($path);
182
183
            if ((substr($filePath, 0, strlen($targetPath)) === $targetPath) ||
184
                (substr($filePath, 0, 1) === '.'))
185
            {
186
                return;
187
            }
188
189
            $this->output->writeln(sprintf("File change detected: %s", $filePath));
190
191
            try
192
            {
193
                if ($this->pm->isPageView($filePath))
194
                {
195
                    $this->pm->compileSingle($filePath);
196
                }
197
                else if ($this->cm->isTrackedByManager($filePath))
198
                {
199
                    $contentItem = &$this->cm->getContentItem($filePath);
200
                    $contentItem->refreshFileContent();
201
202
                    $this->pm->compileContentItem($contentItem);
0 ignored issues
show
Bug introduced by
It seems like $contentItem defined by $this->cm->getContentItem($filePath) on line 199 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...
203
                }
204
                else if ($this->tm->isFileAsset($filePath))
205
                {
206
                    $this->tm->copyFile($filePath);
207
                }
208
                else if ($this->dm->isTracked($filePath))
209
                {
210
                    $this->dm->refreshItem($filePath);
211
                    $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...
212
                    $this->pm->compileAll($this->outputDirectory);
213
                }
214
                else if ($this->am->isTracked($filePath))
215
                {
216
                    $this->am->refreshItem($filePath);
217
                }
218
            }
219
            catch (\Exception $e)
220
            {
221
                $this->output->error(sprintf("Your website failed to build with the following error: %s",
222
                    $e->getMessage()
223
                ));
224
            }
225
        });
226
227
        $watcher->start();
228
    }
229
230
    /**
231
     * @return Configuration
232
     */
233
    public function getConfiguration ()
234
    {
235
        return $this->configuration;
236
    }
237
238
    /**
239
     * @param string $configFile
240
     *
241
     * @throws \LogicException
242
     */
243
    public function setConfiguration ($configFile)
244
    {
245
        if (!$this->fs->exists($configFile) && !$this->isConfLess())
246
        {
247
            $this->output->error("You are trying to build a website in a directory without a configuration file. Is this what you meant to do?");
248
            $this->output->error("To build a website without a configuration, use the '--no-conf' option");
249
250
            throw new \LogicException("Cannot build a website without a configuration when not in Configuration-less mode");
251
        }
252
253
        if ($this->isConfLess())
254
        {
255
            $configFile = "";
256
        }
257
258
        $this->configuration = new Configuration($configFile, $this->output);
259
    }
260
261
    /**
262
     * Get whether or not the website is being built in Configuration-less mode
263
     *
264
     * @return bool True when being built with no configuration file
265
     */
266
    public function isConfLess ()
267
    {
268
        return $this->confLess;
269
    }
270
271
    /**
272
     * Set whether or not the website should be built with a configuration
273
     *
274
     * @param bool $status True when a website should be built without a configuration
275
     */
276
    public function setConfLess ($status)
277
    {
278
        $this->confLess = $status;
279
    }
280
281
    /**
282
     * Get whether or not the website is being built in safe mode.
283
     *
284
     * Safe mode is defined as disabling file system access from Twig and disabling user Twig extensions
285
     *
286
     * @return bool True when the website is being built in safe mode
287
     */
288
    public function isSafeMode ()
289
    {
290
        return $this->safeMode;
291
    }
292
293
    /**
294
     * Set whether a website should be built in safe mode
295
     *
296
     * @param bool $bool True if a website should be built in safe mode
297
     */
298
    public function setSafeMode ($bool)
299
    {
300
        $this->safeMode = $bool;
301
    }
302
303
    /**
304
     * Prepare the Stakx environment by creating necessary cache folders
305
     *
306
     * @param bool $cleanDirectory Clean the target directory
307
     */
308
    private function createFolderStructure ($cleanDirectory)
309
    {
310
        $tarDir = $this->fs->absolutePath($this->configuration->getTargetFolder());
311
312
        if ($cleanDirectory)
313
        {
314
            $this->fs->remove($tarDir);
315
        }
316
317
        $this->fs->remove($this->fs->absolutePath('.stakx-cache'));
318
        $this->fs->mkdir('.stakx-cache/twig');
319
        $this->fs->mkdir($tarDir);
320
    }
321
}