Completed
Push — symfony-console ( e84eb9...8a66e5 )
by Arnaud
02:25 queued 11s
created

CommandServe::setUpServer()   A

Complexity

Conditions 5
Paths 18

Size

Total Lines 37

Duplication

Lines 37
Ratio 100 %

Importance

Changes 0
Metric Value
dl 37
loc 37
rs 9.0168
c 0
b 0
f 0
cc 5
nc 18
nop 1
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Command;
10
11
use Cecil\Util\Plateform;
12
use Symfony\Component\Console\Input\ArrayInput;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputDefinition;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
19
use Symfony\Component\Finder\Finder;
20
use Symfony\Component\Process\Exception\ProcessFailedException;
21
use Symfony\Component\Process\Process;
22
use Yosymfony\ResourceWatcher\Crc32ContentHash;
23
use Yosymfony\ResourceWatcher\ResourceCacheMemory;
24
use Yosymfony\ResourceWatcher\ResourceWatcher;
25
26
class CommandServe extends Command
27
{
28
    /**
29
     * @var string
30
     */
31
    public static $tmpDir = '.cecil';
32
    /**
33
     * @var string
34
     */
35
    protected $drafts;
36
    /**
37
     * @var bool
38
     */
39
    protected $open;
40
    /**
41
     * @var string
42
     */
43
    protected $host;
44
    /**
45
     * @var string
46
     */
47
    protected $port;
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 View Code Duplication
    protected function configure()
53
    {
54
        $this
55
            ->setName('serve')
56
            ->setAliases(['s'])
57
            ->setDescription('Start the built-in server')
58
            ->setDefinition(
59
                new InputDefinition([
60
                    new InputArgument('path', InputArgument::OPTIONAL, 'If specified, use the given path as working directory'),
61
                    new InputOption('drafts', 'd', InputOption::VALUE_NONE, 'Include drafts'),
62
                    new InputOption('open', 'o', InputOption::VALUE_NONE, 'Open browser automatically'),
63
                    new InputOption('host', null, InputOption::VALUE_OPTIONAL, 'Server host'),
64
                    new InputOption('port', null, InputOption::VALUE_OPTIONAL, 'Server port'),
65
                ])
66
            )
67
            ->setHelp('Start the live-reloading-built-in web server.');
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    protected function execute(InputInterface $input, OutputInterface $output)
74
    {
75
        $this->drafts = $input->getOption('drafts');
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getOption('drafts') can also be of type array<integer,string> or boolean. However, the property $drafts is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
76
        $this->open = $input->getOption('open');
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getOption('open') can also be of type string or array<integer,string>. However, the property $open is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
77
        $this->host = $input->getOption('host') ?? 'localhost';
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getOption('host') ?? 'localhost' can also be of type array<integer,string> or boolean. However, the property $host is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
78
        $this->port = $input->getOption('port') ?? '8000';
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getOption('port') ?? '8000' can also be of type array<integer,string> or boolean. However, the property $port is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
79
80
        $this->setUpServer($output);
81
        $command = sprintf(
82
            'php -S %s:%d -t %s %s',
83
            $this->host,
84
            $this->port,
85
            $this->getPath() . '/' . $this->getBuilder($output)->getConfig()->get('output.dir'),
86
            sprintf('%s/%s/router.php', $this->getPath(), self::$tmpDir)
87
        );
88
        $process = new Process($command);
0 ignored issues
show
Documentation introduced by
$command is of type string, but the function expects a array.

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...
89
90
        // (re)build before serve
91
        $buildCommand = $this->getApplication()->find('build');
92
        $buildInput = new ArrayInput([
93
            'command'  => 'build',
94
            'path'     => $this->getPath(),
95
            '--drafts' => $this->drafts,
96
        ]);
97
        $returnCode = $buildCommand->run($buildInput, $output);
0 ignored issues
show
Unused Code introduced by
$returnCode is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
98
99
        // handle process
100
        if (!$process->isStarted()) {
101
            // write changes cache
102
            $finder = new Finder();
103
            $finder->files()
104
                ->name('*.md')
105
                ->name('*.twig')
106
                ->name('*.yml')
107
                ->name('*.css')
108
                ->name('*.scss')
109
                ->name('*.js')
110
                ->in($this->getPath())
111
                ->exclude($this->getBuilder($output)->getConfig()->get('output.dir'));
112 View Code Duplication
            if (!$this->nowatcher) {
0 ignored issues
show
Bug introduced by
The property nowatcher does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
                $hashContent = new Crc32ContentHash();
114
                $resourceCache = new ResourceCacheMemory();
115
                $resourceWatcher = new ResourceWatcher($resourceCache, $finder, $hashContent);
116
                $resourceWatcher->initialize();
117
            }
118
            // start server
119
            try {
120
                $output->writeln(sprintf('<info>Starting server (http://%s:%d)...</info>', $this->host, $this->port));
121
                $process->start();
122
                if ($this->open) {
123
                    Plateform::openBrowser(sprintf('http://%s:%s', $this->host, $this->port));
124
                }
125
                while ($process->isRunning()) {
126
                    if (!$this->nowatcher) {
127
                        $result = $resourceWatcher->findChanges();
0 ignored issues
show
Bug introduced by
The variable $resourceWatcher does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
128
                        if ($result->hasChanges()) {
129
                            // re-build
130
                            $output->writeln('<comment>Changes detected.</comment>');
131
                            $returnCode = $buildCommand->run($buildInput, $output);
0 ignored issues
show
Unused Code introduced by
$returnCode is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
132
                        }
133
                        usleep(1000000); // wait 1s
134
                    }
135
                }
136
            } catch (ProcessFailedException $e) {
137
                $this->tearDownServer();
138
139
                throw new \Exception(sprintf($e->getMessage()));
140
            }
141
        }
142
143
        return 0;
144
    }
145
146 View Code Duplication
    private function setUpServer($output)
147
    {
148
        try {
149
            $root = __DIR__ . '/../../';
150
            if (Plateform::isPhar()) {
151
                $root = Plateform::getPharPath() . '/';
152
            }
153
            // copy router
154
            $this->fs->copy(
155
                $root . 'res/server/router.php',
156
                $this->getPath() . '/' . self::$tmpDir . '/router.php',
157
                true
158
            );
159
            // copy livereload JS
160
            if (!$this->nowatcher) {
161
                $this->fs->copy(
162
                    $root . 'res/server/livereload.js',
163
                    $this->getPath() . '/' . self::$tmpDir . '/livereload.js',
164
                    true
165
                );
166
            }
167
            // copy baseurl text file
168
            $this->fs->dumpFile(
169
                $this->getPath() . '/' . self::$tmpDir . '/baseurl',
170
                sprintf(
171
                    '%s;%s',
172
                    $this->getBuilder($output)->getConfig()->get('baseurl'),
173
                    sprintf('http://%s:%s/', $this->host, $this->port)
174
                )
175
            );
176
        } catch (IOExceptionInterface $e) {
177
            throw new \Exception(sprintf('An error occurred while copying file at "%s"', $e->getPath()));
178
        }
179
        if (!is_file(sprintf('%s/%s/router.php', $this->getPath(), self::$tmpDir))) {
180
            throw new \Exception(sprintf('Router not found: "./%s/router.php"', self::$tmpDir));
181
        }
182
    }
183
184 View Code Duplication
    public function tearDownServer()
185
    {
186
        try {
187
            $this->fs->remove($this->getPath() . '/' . self::$tmpDir);
188
        } catch (IOExceptionInterface $e) {
189
            throw new \Exception(sprintf($e->getMessage()));
190
        }
191
    }
192
}
193