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 ( d64ae4...63c71a )
by Sam
18:51 queued 04:24
created

Module::createEntrypoint()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 39
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.3332

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 39
ccs 8
cts 12
cp 0.6667
rs 8.8571
cc 3
eloc 14
nc 4
nop 0
crap 3.3332
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 string The name of the created image.
85
     */
86
    public $image;
87
88
    /**
89
     * @var string The tag of the created image.
90
     */
91
    public $tag = 'latest';
92
93
    /**
94
     * @var bool wheter to push successful builds.
95
     */
96
    public $push = false;
97
98
    /**
99
     * @var string Location of composer.json / composer.lock
100
     */
101
    public $composerFilePath = '@app/../';
102
    /**
103
     * @return string A PHP-FPM config file.
104
     */
105 4
    protected function createFpmConfig()
106
    {
107 4
        $config = [];
108
        // Add global directives.
109 4
        if (!empty($this->fpmConfig)) {
110 4
            $config[] = '[global]';
111 4
            foreach ($this->fpmConfig as $key => $value) {
112 4
                $config[] = "$key = $value";
113
            }
114
        }
115
116
        // Add pool directives.
117 4
        $poolConfig = $this->poolConfig;
118 4
        foreach($this->phpConfig as $key => $value) {
119 4
            $poolConfig["php_admin_value[$key]"] = $value;
120
        }
121
122 4
        foreach($this->environmentVariables as $name) {
123
            $poolConfig["env[$name]"] = "$$name";
124
        }
125
126 4
        if (!empty($poolConfig)) {
127 4
            $config[] = '[www]';
128 4
            foreach ($poolConfig as $key => $value) {
129 4
                $config[] = "$key = $value";
130
            }
131
        }
132
133 4
        return \implode("\n", $config);
134
    }
135
136
    /**
137
     * @return string A shell script that checks for existence of (non-empty) variables and runs php-fpm.
138
     */
139 4
    protected function createEntrypoint(): string
140
    {
141
        // Get the route.
142 4
        $route = "{$this->getUniqueId()}/migrate/up";
143
144 4
        $result = [];
145 4
        $result[] = '#!/bin/sh';
146
        // Check for variables.
147 4
        foreach($this->environmentVariables as $name) {
148
            $result[] = \strtr('if [ -z "${name}" ]; then echo "Variable \${name} is required."; exit 1; fi', [
149
                '{name}' => $name
150
            ]);
151
        }
152
153 4
        if ($this->runMigrations) {
154
            $result[] = <<<SH
155
ATTEMPTS=0
156
while [ \$ATTEMPTS -lt 10 ]; do
157
  # First run migrations.
158
  /project/protected/yiic $route --interactive=0
159
  if [ $? -eq 0 ]; then
160
    echo "Migrations done";
161
    break;
162
  fi
163
  echo "Failed to run migrations, retrying in 10s.";
164
  sleep 10;
165
  let ATTEMPTS=ATTEMPTS+1
166
done
167
168
if [ \$ATTEMPTS -gt 9 ]; then
169
  echo "Migrations failed.."
170
  exit 1;
171
fi
172
SH;
173
        }
174
175 4
        $result[] = 'exec php-fpm7 --force-stderr --fpm-config /php-fpm.conf';
176 4
        return \implode("\n", $result);
177
    }
178
179 4
    public function createBuildContext(): Context
180
    {
181 4
        static $builder;
182 4
        $builder = new ContextBuilder();
183
184
        /**
185
         * BEGIN COMPOSER
186
         */
187 4
        $builder->from('composer');
188 4
        $builder->addFile('/build/composer.json', \Yii::getAlias($this->composerFilePath) .'/composer.json');
189 4
        if (\file_exists(\Yii::getAlias($this->composerFilePath) . '/composer.lock')) {
190 4
            $builder->addFile('/build/composer.lock', \Yii::getAlias($this->composerFilePath) . '/composer.lock');
191
        }
192
193 4
        $builder->run('cd /build && composer install --no-dev --no-autoloader --ignore-platform-reqs');
194
195
196
        // Add the actual source code.
197 4
        $root = \Yii::getAlias('@app');
198 4
        if (!\is_string($root)) {
199
            throw new \Exception('Alias @app must be defined.');
200
        }
201 4
        $builder->addFile('/build/' . \basename($root), $root);
202 4
        $builder->run('cd /build && composer dumpautoload -o');
203
204
        /**
205
         * END COMPOSER
206
         */
207
208
209 4
        $builder->from('alpine:edge');
210
        $packages = [
211 4
            'php7',
212
            'php7-fpm',
213
            'tini',
214
            'ca-certificates'
215
        ];
216 4
        foreach ($this->extensions as $extension) {
217
            $packages[] = "php7-$extension";
218
        }
219 4
        $builder->run('apk add --update --no-cache ' . \implode(' ', $packages));
220 4
        $builder->volume('/runtime');
221 4
        $builder->copy('--from=0 /build', '/project');
222 4
        $builder->add('/entrypoint.sh', $this->createEntrypoint());
223 4
        $builder->run('chmod +x /entrypoint.sh');
224 4
        $builder->add('/php-fpm.conf', $this->createFpmConfig());
225 4
        $builder->run("php-fpm7 --force-stderr --fpm-config /php-fpm.conf -t");
226 4
        $builder->entrypoint('["/sbin/tini", "--", "/entrypoint.sh"]');
227
228
229 4
        $builder->run('find /project | wc -l');
230 4
        return $builder->getContext();
231
    }
232
233 3
    public function getLock(int $timeout = 0)
234
    {
235 3
        if ($this->has('mutex')) {
236 1
            $mutex = $this->get('mutex');
237 1
            if ($mutex instanceof Mutex
238 1
                && $mutex->acquire(__CLASS__, $timeout)
239
            ) {
240 1
                \register_shutdown_function(function() use ($mutex): void {
241
                    $mutex->release(__CLASS__);
242 1
                });
243 1
                return true;
244
            }
245
        }
246 3
        return false;
247
    }
248
}