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 ( d0c102...8ca686 )
by Sam
02:40
created

Module::getLock()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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