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 ( 669d0f...7cd591 )
by Sam
06:36
created

BuildController::actionBuild()   C

Complexity

Conditions 10
Paths 9

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 10.0328

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 54
ccs 27
cts 29
cp 0.931
rs 6.8372
cc 10
eloc 33
nc 9
nop 0
crap 10.0328

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
declare(strict_types=1);
3
4
namespace SamIT\Yii2\PhpFpm\controllers;
5
6
7
use Docker\API\Model\BuildInfo;
8
use Docker\API\Model\PushImageInfo;
9
use Docker\Context\Context;
10
use Docker\Context\ContextBuilder;
11
use Docker\Context\ContextInterface;
12
use Docker\Docker;
13
use Docker\Stream\BuildStream;
14
use Psr\Http\Message\ResponseInterface;
15
use SamIT\Yii2\PhpFpm\Module;
16
use yii\base\InvalidConfigException;
17
use yii\console\Controller;
18
use yii\helpers\Console;
19
use yii\web\Response;
20
use function Clue\StreamFilter\fun;
21
22
/**
23
 * Class BuildController
24
 * @package SamIT\Yii2\PhpFpm\controllers
25
 * @property Module $module
26
 */
27
class BuildController extends Controller
28
{
29
    public $defaultAction = 'build';
30
31
    /**
32
     * @var string The name of the created image
33
     * If not explicitly set will take its default from module config.
34
     */
35
    public $image;
36
37
    /**
38
     * @var string The tag of the created image
39
     * If not explicitly set will take its default from module config.
40
     */
41
    public $tag;
42
43
    /**
44
     * @var bool whether to push the image after a successful build.
45
     * If not explicitly set will take its default from module config.
46
     */
47
    public $push;
48
49
    /**
50
     * @var Docker
51
     */
52
    protected $docker;
53
54
    /**
55
     * @var string the user to authenticate against the repository
56
     */
57
    public $user;
58
59
    /**
60
     * @var string the password to authenticate against the repository
61
     */
62
    public $password;
63 3
64
    public function init(): void
65 3
    {
66 3
        parent::init();
67 3
        $this->docker = Docker::create();
68 3
        $this->push = $this->module->push;
69 3
        $this->image = $this->module->image;
70 3
        $this->tag = $this->module->tag;
71
    }
72 2
73
    public function actionBuild(): void
74
    {
75
        if ($this->push && !isset($this->image, $this->user, $this->password)) {
76 2
            throw new InvalidConfigException("When using the push option, you must configure or provide user, password and image");
77 2
        }
78 2
79 2
        $params = [];
80
81 2
82
        if (isset($this->image)) {
83 2
            $name = "{$this->image}:{$this->tag}";
84 2
            $params['t'] = $name;
85 2
        }
86
        $buildStream = $this->createBuildStream($params);
87 2
        $this->color = true;
88 2
        $buildStream->onFrame(function(BuildInfo $buildInfo): void {
89 2
            $this->stdout($buildInfo->getStream(), Console::FG_CYAN);
90
            $this->stdout($buildInfo->getProgress(), Console::FG_YELLOW);
91 2
            $this->stdout($buildInfo->getStatus(), Console::FG_RED);
92 2
            if (!empty($buildInfo->getProgressDetail())) {
93 1
                $this->stdout($buildInfo->getProgressDetail()->getMessage(), Console::FG_YELLOW);
94
            }
95
            if (!empty($buildInfo->getErrorDetail())) {
96 1
                $this->stdout($buildInfo->getErrorDetail()->getCode() . ':' . $buildInfo->getErrorDetail()->getMessage(), Console::FG_YELLOW);
97 1
            }
98 1
            if (!empty($buildInfo->getError())) {
99
                throw new \Exception($buildInfo->getError() . ':' . $buildInfo->getErrorDetail()->getMessage());
100
            }
101 1
        });
102
        $buildStream->wait();
103 1
        $this->stdout("Wait finished\n");
104
        $buildStream->wait();
105
106
        if ($this->push) {
107 1
            $params = [
108
                'X-Registry-Auth' => \base64_encode(\GuzzleHttp\json_encode([
109 1
                    'username' => $this->user,
110 1
                    'password' => $this->password
111
                ]))
112
            ];
113
            $pushResult = $this->docker->imagePush($name, $params ?? [], Docker::FETCH_OBJECT);
0 ignored issues
show
Bug introduced by
The variable $name does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
114
115
            if ($pushResult instanceof ResponseInterface) {
116 3
                throw new \Exception($pushResult->getReasonPhrase() . ':' . $pushResult->getBody()->getContents(), $pushResult->getStatusCode());
117
            }
118
            /** @var PushImageInfo $pushInfo */
119 3
            $pushInfo = \array_pop($pushResult);
120
121
            if (!empty($pushInfo->getError())) {
122 3
                throw new \Exception($pushInfo->getError());
123 3
            }
124
125
        }
126 1
    }
127
128
    public function actionTestClient(): void
129 1
    {
130
        $this->stdout("It seems the console client works!\n", Console::FG_GREEN);
131 1
    }
132 1
133 1
    public function createBuildStream(array $params = []): BuildStream
134 1
    {
135 1
136 1
        $context = $this->module->createBuildContext();
137 1
        /** @var BuildStream $buildStream */
138
        $buildStream = $this->docker->imageBuild($context->toStream(), $params, Docker::FETCH_STREAM);
139
140 1
        return $buildStream;
141
    }
142
143
    public function options($actionID)
144
    {
145
146
        $result = parent::options($actionID);
147
        switch ($actionID) {
148
            case 'build':
149
                $result[] = 'push';
150
                $result[] = 'image';
151
                $result[] = 'tag';
152
                $result[] = 'user';
153
                $result[] = 'password';
154
                break;
155
156
        }
157
        return $result;
158
    }
159
160
    public function optionAliases()
161
    {
162
        $result = parent::optionAliases();
163
        $result['p'] = 'push';
164
        $result['t'] = 'tag';
165
        $result['i'] = 'image';
166
        $result['u'] = 'user';
167
        $result['P'] = 'password';
168
        return $result;
169
    }
170
171 View Code Duplication
    public function stdout($string)
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...
172
    {
173
        if ($this->isColorEnabled()) {
174
            $args = \func_get_args();
175
            \array_shift($args);
176
            $string = Console::ansiFormat($string, $args);
177
        }
178
179
        echo $string;
180
        return \strlen($string);
181
    }
182
183
184
}