GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( a607a3...bc04e9 )
by Sam
06:24
created

Module::createBuildContext()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 50
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 50
rs 9.3333
ccs 20
cts 20
cp 1
cc 3
eloc 29
nc 4
nop 0
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace SamIT\Yii2\PhpFpm;
5
6
use Docker\Context\Context;
7
use Docker\Context\ContextBuilder;
8
use yii\mutex\Mutex;
9
10
class Module extends \yii\base\Module
11
{
12
13
    /**
14
     * @var bool Whether the container should attempt to run migrations on launch.
15
     */
16
    public $runMigrations = false;
17
18
    /**
19
     * @var bool whether migrations should acquire a lock.
20
     * It must be configured in the 'mutex' component of this module or the application
21
     * Note that this mutex must be shared between all instances of your application.
22
     * Consider using something like redis or mysql mutex.
23
     */
24
    public $migrationsUseMutex = true;
25
26
    /**
27
     * The variables will be populated via the pool config.
28
     * @var string[] List of required environment variables. If one is missing the container will exit.
29
     *
30
     */
31
    public $environmentVariables = [];
32
33
    /**
34
     * @var array Pool directives
35
     * @see http://php.net/manual/en/install.fpm.configuration.php
36
     *
37
     */
38
    public $poolConfig = [
39
        'user' => 'nobody',
40
        'group' => 'nobody',
41
        'listen' => 9000,
42
        'pm' => 'dynamic',
43
        'pm.max_children' => 40,
44
        'pm.start_servers' => 3,
45
        'pm.min_spare_servers' => 1,
46
        'pm.max_spare_servers' => 3,
47
        'access.log' => '/proc/self/fd/2',
48
        'clear_env' => 'yes',
49
50
    ];
51
52
    /**
53
     * @var array PHP configuration, supplied via php_admin_value in fpm config.
54
     */
55
    public $phpConfig = [
56
        'upload_max_filesize' => '20M',
57
        'post_max_size' => '25M'
58
    ];
59
60
    /**
61
     * @var array Global directives
62
     * @see http://php.net/manual/en/install.fpm.configuration.php
63
     *
64
     */
65
    public $fpmConfig = [
66
        'error_log' => '/proc/self/fd/2',
67
        'daemonize' => 'no',
68
    ];
69
70
    public $extensions = [
71
        'ctype',
72
        'gd',
73
        'iconv',
74
        'intl',
75
        'json',
76
        'mbstring',
77
        'session',
78
        'pdo_mysql',
79
        'session',
80
        'curl'
81
    ];
82
83
    /**
84
     * @var Name and optionally tag of the image.
85
     * 
86
     */
87
    public $image;
88
89 1
    /**
90
     * @var string Location of composer.json / composer.lock
91 1
     */
92
    public $composerFilePath = '@app/../';
93 1
    /**
94 1
     * @return string A PHP-FPM config file.
95 1
     */
96 1
    protected function createFpmConfig()
97
    {
98
        $config = [];
99
        // Add global directives.
100
        if (!empty($this->fpmConfig)) {
101 1
            $config[] = '[global]';
102 1
            foreach ($this->fpmConfig as $key => $value) {
103 1
                $config[] = "$key = $value";
104
            }
105
        }
106 1
107
        // Add pool directives.
108
        $poolConfig = $this->poolConfig;
109
        foreach($this->phpConfig as $key => $value) {
110 1
            $poolConfig["php_admin_value[$key]"] = $value;
111 1
        }
112 1
113 1
        foreach($this->environmentVariables as $name) {
114
            $poolConfig["env[$name]"] = "$$name";
115
        }
116
117 1
        if (!empty($poolConfig)) {
118
            $config[] = '[www]';
119
            foreach ($poolConfig as $key => $value) {
120
                $config[] = "$key = $value";
121
            }
122
        }
123 1
124
        return \implode("\n", $config);
125 1
    }
126 1
127
    /**
128 1
     * @return string A shell script that checks for existence of (non-empty) variables and runs php-fpm.
129
     */
130
    protected function createEntrypoint(): string
131
    {
132
        // Get the route.
133
        $route = "{$this->getUniqueId()}/migrate/up";
134 1
135
        $result = [];
136
        $result[] = '#!/bin/sh';
137
        // Check for variables.
138
        foreach($this->environmentVariables as $name) {
139
            $result[] = \strtr('if [ -z "${name}" ]; then echo "Variable \${name} is required."; exit 1; fi', [
140
                '{name}' => $name
141
            ]);
142
        }
143
144
        if ($this->runMigrations) {
145
            $result[] = <<<SH
146
ATTEMPTS=0
147
while [ \$ATTEMPTS -lt 10 ]; do
148
  # First run migrations.
149
  /project/protected/yiic $route --interactive=0
150
  if [ $? -eq 0 ]; then
151
    echo "Migrations done";
152
    break;
153
  fi
154
  echo "Failed to run migrations, retrying in 10s.";
155
  sleep 10;
156 1
  let ATTEMPTS=ATTEMPTS+1
157 1
done
158
159
if [ \$ATTEMPTS -gt 9 ]; then
160 1
  echo "Migrations failed.."
161
  exit 1;
162 1
fi
163 1
SH;
164
        }
165
166
        $result[] = 'exec php-fpm7 --force-stderr --fpm-config /php-fpm.conf';
167
        return \implode("\n", $result);
168 1
    }
169 1
170 1
    public function createBuildContext(): Context
171 1
    {
172
        static $builder;
173
        $builder = new ContextBuilder();
174 1
175
        /**
176
         * BEGIN COMPOSER
177
         */
178 1
        $builder->from('composer');
179 1
        $builder->addFile('/build/composer.json', \Yii::getAlias($this->composerFilePath) .'/composer.json');
180 1
        if (\file_exists(\Yii::getAlias($this->composerFilePath) . '/composer.lock')) {
181
            $builder->addFile('/build/composer.lock', \Yii::getAlias($this->composerFilePath) . '/composer.lock');
182
        }
183
184
        $builder->run('cd /build && composer install --no-dev --no-autoloader --ignore-platform-reqs');
185
186
187 1
        // Add the actual source code.
188
        $root = \Yii::getAlias('@app');
189 1
        $builder->addFile('/build/' . \basename($root), $root);
0 ignored issues
show
Bug introduced by
It seems like $root defined by \Yii::getAlias('@app') on line 188 can also be of type boolean; however, Docker\Context\ContextBuilder::addFile() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
190
        $builder->run('cd /build && composer dumpautoload -o');
191
192
        /**
193
         * END COMPOSER
194 1
         */
195 1
196
197 1
        $builder->from('alpine:edge');
198 1
        $packages = [
199 1
            'php7',
200 1
            'php7-fpm',
201 1
            'tini',
202 1
            'ca-certificates'
203 1
        ];
204 1
        foreach ($this->extensions as $extension) {
205
            $packages[] = "php7-$extension";
206
        }
207 1
        $builder->run('apk add --update --no-cache ' . \implode(' ', $packages));
208 1
        $builder->volume('/runtime');
209
        $builder->copy('--from=0 /build', '/project');
210
        $builder->add('/entrypoint.sh', $this->createEntrypoint());
211
        $builder->run('chmod +x /entrypoint.sh');
212
        $builder->add('/php-fpm.conf', $this->createFpmConfig());
213
        $builder->run("php-fpm7 --force-stderr --fpm-config /php-fpm.conf -t");
214
        $builder->entrypoint('["/sbin/tini", "--", "/entrypoint.sh"]');
215
216
217
        $builder->run('find /project | wc -l');
218
        return $builder->getContext();
219
    }
220
221
    public function getLock(int $timeout = 0)
222
    {
223
        if ($this->has('mutex')) {
224
            $mutex = $this->get('mutex');
225
            if ($mutex instanceof Mutex
226
                && $mutex->acquire(__CLASS__, $timeout)
227
            ) {
228
                register_shutdown_function(function() use ($mutex) {
229
                    $mutex->release(__CLASS__);
230
                });
231
                return true;
232
            }
233
        }
234
        return false;
235
    }
236
}