Completed
Push — stable ( 86ecc3...3a45ea )
by Nuno
07:34
created

Builder::compile()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0021

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 15
cts 16
cp 0.9375
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 1
crap 3.0021
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
20
/**
21
 * This is the Laravel Zero Framework Builder Command implementation.
22
 */
23
class Builder extends Command
24
{
25
    /**
26
     * Contains the default app structure.
27
     *
28
     * @var string[]
29
     */
30
    protected $structure = [
31
        'app' . DIRECTORY_SEPARATOR,
32
        'bootstrap' . DIRECTORY_SEPARATOR,
33
        'vendor' . DIRECTORY_SEPARATOR,
34
        'config' . DIRECTORY_SEPARATOR,
35
        'composer.json',
36
        'builder-stub',
37
        '.env'
38
    ];
39
40
    /**
41
     * Holds the stub name.
42
     *
43
     * @var string
44
     */
45
    protected $stub = 'builder-stub';
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    protected $signature = 'app:build {name=application : The build name}';
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    protected $description = 'Perform an application build';
56
57
    /**
58
     * Holds the configuration on is original state.
59
     *
60
     * @var string
61
     */
62
    protected static $config;
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 1
    public function handle(): void
68
    {
69 1
        $this->info('Building the application...');
70
71 1
        if (Phar::canWrite()) {
72 1
            $this->build($this->input->getArgument('name') ?: static::BUILD_NAME);
73
        } else {
74
            $this->error(
75
                '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(
76
                ) . ' 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'
77
            );
78
        }
79 1
    }
80
81
    /**
82
     * Builds the application into a single file.
83
     *
84
     * @param string $name The file name.
85
     *
86
     * @return $this
87
     */
88 1
    protected function build(string $name): Builder
89
    {
90
        /*
91
         * We prepare the application for a build, moving it to production. Then,
92
         * after compile all the code to a single file, we move the built file
93
         * to the builds folder with the correct permissions.
94
         */
95 1
        $this->prepare()
96 1
            ->compile($name)
97 1
            ->setPermissions($name)
98 1
            ->clear();
99
100 1
        $this->info(
101 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...
102
        );
103
104 1
        return $this;
105
    }
106
107
    /**
108
     * @param string $name
109
     *
110
     * @return $this
111
     */
112 1
    protected function compile(string $name): Builder
113
    {
114 1
        $compiler = $this->makeBuildsFolder()
115 1
            ->getCompiler($name);
116
117 1
        $structure = config('app.structure') ?: $this->structure;
118
119 1
        $regex = '#' . implode('|', $structure) . '#';
120
121 1
        if (stristr(PHP_OS, 'WINNT') !== false) { // For windows:
122
            $compiler->buildFromDirectory($this->app->basePath(), str_replace('\\', '/', $regex));
123
        } else { // Linux, OS X:
124 1
            $compiler->buildFromDirectory($this->app->basePath(), $regex);
125
        }
126
127 1
        $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...
128 1
            $compiler->setStub(
129 1
                "#!/usr/bin/env php \n" . $compiler->createDefaultStub(
130 1
                    $this->stub
131
                )
132
            );
133 1
        });
134
135 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...
136
137 1
        File::move("$file.phar", $file);
138
139 1
        return $this;
140
    }
141
142
    /**
143
     * Gets a new instance of the compiler.
144
     *
145
     * @param string $name
146
     *
147
     * @return \Phar
148
     */
149 1
    protected function getCompiler(string $name): \Phar
150
    {
151
        try {
152 1
            return new Phar(
153 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...
154 1
                FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
155 1
                $name
156
            );
157
        } catch (UnexpectedValueException $e) {
158
            $this->app->abort(401, 'Unauthorized.');
159
        }
160
    }
161
162
    /**
163
     * @return $this
164
     */
165 1
    protected function makeBuildsFolder(): Builder
166
    {
167 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...
168 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...
169
        }
170
171 1
        return $this;
172
    }
173
174
    /**
175
     * Sets the executable mode on the single application file.
176
     *
177
     * @param string $name
178
     *
179
     * @return $this
180
     */
181 1
    protected function setPermissions($name): Builder
182
    {
183 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...
184
185 1
        return $this;
186
    }
187
188
    /**
189
     * @return $this
190
     */
191 1
    protected function prepare(): Builder
192
    {
193 1
        $file = $this->app->configPath('app.php');
194 1
        static::$config = File::get($file);
195 1
        $config = include $file;
196
197 1
        $config['production'] = true;
198
199 1
        $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...
200 1
            File::put($file, '<?php return ' . var_export($config, true) . ';' . PHP_EOL);
201 1
        });
202
203 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...
204
205 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...
206
207 1
        return $this;
208
    }
209
210
    /**
211
     * @return $this
212
     */
213 1 View Code Duplication
    protected function clear(): Builder
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
214
    {
215 1
        File::put($this->app->configPath('app.php'), static::$config);
216
217 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...
218
219 1
        static::$config = null;
220
221 1
        return $this;
222
    }
223
224
    /**
225
     * Makes sure that the `clear` is performed even
226
     * if the command fails.
227
     *
228
     * @return void
229
     */
230 20 View Code Duplication
    public function __destruct()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
231
    {
232 20
        if (static::$config !== null) {
233
            File::put($this->app->configPath('app.php'), static::$config);
234
            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...
235
        }
236 20
    }
237
}
238