Completed
Push — master ( 6e5d34...b1d130 )
by Peter
05:21
created

ScriptHandler::useNewDirectoryStructure()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 2
eloc 2
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * GpsLab component.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2017, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
10
namespace GpsLab\Bundle\GeoIP2Bundle\Composer;
11
12
use Composer\Script\Event;
13
use Symfony\Component\Process\PhpExecutableFinder;
14
use Symfony\Component\Process\Process;
15
16
class ScriptHandler
17
{
18
    /**
19
     * Composer variables are declared static so that an event could update
20
     * a composer.json and set new options, making them immediately available
21
     * to forthcoming listeners.
22
     */
23
    private static $options = array(
24
        'symfony-app-dir' => 'app',
25
        'symfony-web-dir' => 'web',
26
        'symfony-assets-install' => 'hard',
27
        'symfony-cache-warmup' => false,
28
    );
29
30
    /**
31
     * @param Event $event
32
     */
33
    public static function updateDatabase(Event $event)
34
    {
35
        $options = static::getOptions($event);
36
        $consoleDir = static::getConsoleDir($event, 'clear the cache');
0 ignored issues
show
Bug introduced by
Since getConsoleDir() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of getConsoleDir() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
37
38
        if (null === $consoleDir) {
39
            return;
40
        }
41
42
        self::executeCommand($event, $consoleDir, 'geoip2:update --no-debug', $options['process-timeout']);
43
    }
44
45
    /**
46
     * @param Event $event
47
     * @param string $cmd
48
     * @param int $timeout
49
     */
50
    private static function executeCommand(Event $event, $consoleDir, $cmd, $timeout = 300)
51
    {
52
        $php = escapeshellarg(static::getPhp(false));
0 ignored issues
show
Bug introduced by
Since getPhp() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of getPhp() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
53
        $phpArgs = implode(' ', array_map('escapeshellarg', static::getPhpArguments()));
0 ignored issues
show
Bug introduced by
Since getPhpArguments() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of getPhpArguments() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
54
        $console = escapeshellarg($consoleDir.'/console');
55
        if ($event->getIO()->isDecorated()) {
56
            $console .= ' --ansi';
57
        }
58
        $process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$console.' '.$cmd, null, null, null, $timeout);
59
        $process->run(function ($type, $buffer) use ($event) { $event->getIO()->write($buffer, false); });
60
61
        if (!$process->isSuccessful()) {
62
            throw new \RuntimeException(sprintf(
63
                "An error occurred when executing the \"%s\" command:\n\n%s\n\n%s.",
64
                escapeshellarg($cmd),
65
                $process->getOutput(),
66
                $process->getErrorOutput()
67
            ));
68
        }
69
    }
70
71
    /**
72
     * @param Event $event
73
     *
74
     * @return array
75
     */
76
    protected static function getOptions(Event $event)
77
    {
78
        $options = array_merge(static::$options, $event->getComposer()->getPackage()->getExtra());
0 ignored issues
show
Bug introduced by
Since $options is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $options to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
79
80
        $options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];
81
        $options['symfony-cache-warmup'] = getenv('SYMFONY_CACHE_WARMUP') ?: $options['symfony-cache-warmup'];
82
83
        $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');
84
85
        return $options;
86
    }
87
88
    /**
89
     * Returns a relative path to the directory that contains the `console` command.
90
     *
91
     * @param Event  $event      The command event
92
     * @param string $actionName The name of the action
93
     *
94
     * @return string|null The path to the console directory, null if not found.
95
     */
96
    private static function getConsoleDir(Event $event, $actionName)
97
    {
98
        $options = static::getOptions($event);
99
100
        if (static::useNewDirectoryStructure($options)) {
0 ignored issues
show
Bug introduced by
Since useNewDirectoryStructure() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of useNewDirectoryStructure() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
101
            if (!static::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
0 ignored issues
show
Bug introduced by
Since hasDirectory() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of hasDirectory() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
102
                return;
103
            }
104
105
            return $options['symfony-bin-dir'];
106
        }
107
108
        if (!static::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
0 ignored issues
show
Bug introduced by
Since hasDirectory() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of hasDirectory() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
109
            return;
110
        }
111
112
        return $options['symfony-app-dir'];
113
    }
114
115
    /**
116
     * @param Event  $event
117
     * @param string $configName
118
     * @param string $path
119
     * @param string $actionName
120
     *
121
     * @return bool
122
     */
123
    private static function hasDirectory(Event $event, $configName, $path, $actionName)
124
    {
125
        if (!is_dir($path)) {
126
            $event->getIO()->write(sprintf('The %s (%s) specified in composer.json was not found in %s, can not %s.', $configName, $path, getcwd(), $actionName));
127
128
            return false;
129
        }
130
131
        return true;
132
    }
133
134
    /**
135
     * Returns true if the new directory structure is used.
136
     *
137
     * @param array $options Composer options
138
     *
139
     * @return bool
140
     */
141
    private static function useNewDirectoryStructure(array $options)
142
    {
143
        return isset($options['symfony-var-dir']) && is_dir($options['symfony-var-dir']);
144
    }
145
146
    /**
147
     * Get path to php executable.
148
     *
149
     * @param bool $include_args
150
     *
151
     * @throws \RuntimeException
152
     *
153
     * @return string
154
     */
155
    private static function getPhp($include_args = true)
156
    {
157
        $phpFinder = new PhpExecutableFinder();
158
        if (!$phpPath = $phpFinder->find($include_args)) {
159
            throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
160
        }
161
162
        return $phpPath;
163
    }
164
165
    /**
166
     * @return array
167
     */
168
    private static function getPhpArguments()
169
    {
170
        $ini = null;
0 ignored issues
show
Unused Code introduced by
$ini 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...
171
        $arguments = [];
172
        $phpFinder = new PhpExecutableFinder();
173
        if (method_exists($phpFinder, 'findArguments')) {
174
            $arguments = $phpFinder->findArguments();
175
        }
176
177
        if ($env = strval(getenv('COMPOSER_ORIGINAL_INIS'))) {
178
            $paths = explode(PATH_SEPARATOR, $env);
179
            $ini = array_shift($paths);
180
        } else {
181
            $ini = php_ini_loaded_file();
182
        }
183
184
        if ($ini) {
185
            $arguments[] = '--php-ini='.$ini;
186
        }
187
188
        return $arguments;
189
    }
190
}
191