Completed
Push — stable ( ef4570...c41d70 )
by Nuno
03:23
created

Builder   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 235
Duplicated Lines 4.26 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 88.16%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 3
dl 10
loc 235
ccs 67
cts 76
cp 0.8816
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 13 3
A build() 0 18 1
A getCompiler() 0 12 2
A makeBuildsFolder() 0 8 2
A setPermissions() 0 6 1
A __destruct() 0 7 2
B compile() 0 32 3
B prepare() 5 29 2
A clear() 5 16 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * This file is part of Laravel Zero.
5
 *
6
 * (c) Nuno Maduro <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 */
11
12
namespace LaravelZero\Framework\Commands\App;
13
14
use Phar;
15
use FilesystemIterator;
16
use UnexpectedValueException;
17
use Illuminate\Support\Facades\File;
18
use LaravelZero\Framework\Commands\Command;
19
use LaravelZero\Framework\Contracts\Providers\Composer;
20
21
/**
22
 * This is the Laravel Zero Framework Builder Command implementation.
23
 */
24
class Builder extends Command
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29
    protected $signature = 'app:build {name=application : The build name} {--with-dev : Whether the dev dependencies should be included}';
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    protected $description = 'Perform an application build';
35
36
    /**
37
     * Contains the default app structure.
38
     *
39
     * @var string[]
40
     */
41
    protected $structure = [
42
        'app'.DIRECTORY_SEPARATOR,
43
        'bootstrap'.DIRECTORY_SEPARATOR,
44
        'vendor'.DIRECTORY_SEPARATOR,
45
        'config'.DIRECTORY_SEPARATOR,
46
        'composer.json',
47
        'builder-stub',
48
        '.env',
49
    ];
50
51
    /**
52
     * Holds the stub name.
53
     *
54
     * @var string
55
     */
56
    protected $stub = 'builder-stub';
57
58
    /**
59
     * Holds the configuration on is original state.
60
     *
61
     * @var string
62
     */
63
    protected static $config;
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 1
    public function handle(): void
69
    {
70 1
        $this->info('Building the application...');
71
72 1
        if (Phar::canWrite()) {
73 1
            $this->build($this->input->getArgument('name') ?: static::BUILD_NAME);
74
        } else {
75
            $this->error(
76
                'Unable to compile a phar because of php\'s security settings. '.'phar.readonly must be disabled in php.ini. '.PHP_EOL.PHP_EOL.'You will need to edit '.php_ini_loaded_file(
77
                ).' and add or set'.PHP_EOL.PHP_EOL.'    phar.readonly = Off'.PHP_EOL.PHP_EOL.'to continue. Details here: http://php.net/manual/en/phar.configuration.php'
78
            );
79
        }
80 1
    }
81
82
    /**
83
     * Builds the application into a single file.
84
     *
85
     * @param string $name The file name.
86
     *
87
     * @return $this
88
     */
89 1
    protected function build(string $name): Builder
90
    {
91
        /*
92
         * We prepare the application for a build, moving it to production. Then,
93
         * after compile all the code to a single file, we move the built file
94
         * to the builds folder with the correct permissions.
95
         */
96 1
        $this->prepare()
97 1
            ->compile($name)
98 1
            ->setPermissions($name)
99 1
            ->clear();
100
101 1
        $this->info(
102 1
            sprintf('Application built into a single file: %s', $this->app->buildsPath($name))
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
103
        );
104
105 1
        return $this;
106
    }
107
108
    /**
109
     * @param string $name
110
     *
111
     * @return $this
112
     */
113 1
    protected function compile(string $name): Builder
114
    {
115 1
        $compiler = $this->makeBuildsFolder()
116 1
            ->getCompiler($name);
117
118 1
        $structure = config('app.structure') ?: $this->structure;
119
120 1
        $regex = '#'.implode('|', $structure).'#';
121
122 1
        if (stristr(PHP_OS, 'WINNT') !== false) { // For windows:
123
            $compiler->buildFromDirectory($this->app->basePath(), str_replace('\\', '/', $regex));
124
        } else { // Linux, OS X:
125 1
            $compiler->buildFromDirectory($this->app->basePath(), $regex);
126
        }
127
128
        $this->task('Compiling code', function () use ($compiler) {
0 ignored issues
show
Documentation Bug introduced by
The method task does not exist on object<LaravelZero\Frame...k\Commands\App\Builder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
129 1
            $compiler->setStub(
130 1
                "#!/usr/bin/env php \n".$compiler->createDefaultStub(
131 1
                    $this->stub
132
                )
133
            );
134 1
        });
135
136
        // Unset the compiler to fix a "file in use" error on Windows.
137 1
        unset($compiler);
138
139 1
        $file = $this->app->buildsPath($name);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
140
141 1
        File::move("$file.phar", $file);
142
143 1
        return $this;
144
    }
145
146
    /**
147
     * Gets a new instance of the compiler.
148
     *
149
     * @param string $name
150
     *
151
     * @return \Phar
152
     */
153 1
    protected function getCompiler(string $name): \Phar
154
    {
155
        try {
156 1
            return new Phar(
157 1
                $this->app->buildsPath($name.'.phar'),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
158 1
                FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
159 1
                $name
160
            );
161
        } catch (UnexpectedValueException $e) {
162
            $this->app->abort(401, 'Unauthorized.');
163
        }
164
    }
165
166
    /**
167
     * @return $this
168
     */
169 1
    protected function makeBuildsFolder(): Builder
170
    {
171 1
        if (! File::exists($this->app->buildsPath())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
172 1
            File::makeDirectory($this->app->buildsPath());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
173
        }
174
175 1
        return $this;
176
    }
177
178
    /**
179
     * Sets the executable mode on the single application file.
180
     *
181
     * @param string $name
182
     *
183
     * @return $this
184
     */
185 1
    protected function setPermissions($name): Builder
186
    {
187 1
        chmod($this->app->buildsPath($name), 0755);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Foundation\Application as the method buildsPath() does only exist in the following implementations of said interface: LaravelZero\Framework\Application.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
188
189 1
        return $this;
190
    }
191
192
    /**
193
     * @return $this
194
     */
195 1
    protected function prepare(): Builder
196
    {
197 1
        $file = $this->app->configPath('app.php');
198 1
        static::$config = File::get($file);
199 1
        $config = include $file;
200
201 1
        $config['production'] = true;
202
203
        $this->task('Moving application to production mode', function () use ($file, $config) {
0 ignored issues
show
Documentation Bug introduced by
The method task does not exist on object<LaravelZero\Frame...k\Commands\App\Builder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
204 1
            File::put($file, '<?php return '.var_export($config, true).';'.PHP_EOL);
205 1
        });
206
207 1 View Code Duplication
        if ($this->option('with-dev') === false) {
0 ignored issues
show
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...
208
            $this->task('Temporarily removing dev dependencies', function () {
0 ignored issues
show
Documentation Bug introduced by
The method task does not exist on object<LaravelZero\Frame...k\Commands\App\Builder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
209 1
                $this->app[Composer::class]->install(['--no-dev']);
210 1
            });
211
        }
212
213 1
        $stub = str_replace('#!/usr/bin/env php', '', File::get($this->app->basePath(ARTISAN_BINARY)));
0 ignored issues
show
Unused Code introduced by
The call to Application::basePath() has too many arguments starting with ARTISAN_BINARY.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
214
215
        // Remove first line.
216 1
        $stubAsArray = explode("\n", $stub);
217 1
        array_shift($stubAsArray);
218 1
        $stub = implode("\n", $stubAsArray);
219
220 1
        File::put($this->app->basePath($this->stub), $stub);
0 ignored issues
show
Unused Code introduced by
The call to Application::basePath() has too many arguments starting with $this->stub.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
221
222 1
        return $this;
223
    }
224
225
    /**
226
     * @return $this
227
     */
228 1
    protected function clear(): Builder
229
    {
230 1
        File::put($this->app->configPath('app.php'), static::$config);
231
232 1
        File::delete($this->app->basePath($this->stub));
0 ignored issues
show
Unused Code introduced by
The call to Application::basePath() has too many arguments starting with $this->stub.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
233
234 1 View Code Duplication
        if ($this->option('with-dev') === false) {
0 ignored issues
show
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...
235
            $this->task('Reinstalling dev dependencies', function () {
0 ignored issues
show
Documentation Bug introduced by
The method task does not exist on object<LaravelZero\Frame...k\Commands\App\Builder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
236 1
                $this->app[Composer::class]->install();
237 1
            });
238
        }
239
240 1
        static::$config = null;
241
242 1
        return $this;
243
    }
244
245
    /**
246
     * Makes sure that the `clear` is performed even
247
     * if the command fails.
248
     *
249
     * @return void
250
     */
251 18
    public function __destruct()
252
    {
253 18
        if (static::$config !== null) {
254
            $this->clear();
255
            $this->error('Something went wrong.');
256
        }
257 18
    }
258
}
259