Completed
Push — master ( 662efc...619ed4 )
by ophelie
7s
created

ComposeManager::formatCommand()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 3
Metric Value
c 6
b 0
f 3
dl 0
loc 22
rs 9.2
cc 3
eloc 10
nc 4
nop 2
1
<?php
2
3
namespace DockerCompose\Manager;
4
5
use DockerCompose\Exception\ComposeFileNotFoundException;
6
use DockerCompose\Exception\DockerHostConnexionErrorException;
7
use DockerCompose\Exception\DockerInstallationMissingException;
8
use DockerCompose\Exception\NoSuchServiceException;
9
use DockerCompose\ComposeFileCollection;
10
use mikehaertl\shellcommand\Command;
11
use Exception;
12
13
/**
14
 * DockerCompose\Manager\ComposeManager
15
 */
16
class ComposeManager
17
{
18
19
    /**
20
     * Start service containers
21
     *
22
     * @param mixed $composeFiles The compose files names
23
     */
24
    public function start($composeFiles = array())
25
    {
26
        return $this->processResult(
27
            $this->execute(
28
                $this->formatCommand('up -d', $this->createComposeFileCollection($composeFiles))
29
            )
30
        );
31
    }
32
33
    /**
34
     * Stop service containers
35
     *
36
     * @param mixed $composeFiles The compose files names
37
     */
38
    public function stop($composeFiles = array())
39
    {
40
        return $this->processResult(
41
            $this->execute(
42
                $this->formatCommand('stop', $this->createComposeFileCollection($composeFiles))
43
            )
44
        );
45
    }
46
47
    /**
48
     * Stop service containers
49
     *
50
     * @param mixed   $composeFiles  The compose files names
51
     * @param boolean $force         If the remove need to be force (default=false)
52
     * @param boolean $removeVolumes If we need to remove the volumes (default=false)
53
     */
54
    public function remove($composeFiles = array(), $force = false, $removeVolumes = false)
0 ignored issues
show
Unused Code introduced by
The parameter $force is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
55
    {
56
        $command = 'rm --force';
57
58
        if ($removeVolumes) {
59
            $command .= ' -v';
60
        }
61
62
        return $this->processResult(
63
            $this->execute(
64
                $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
65
            )
66
        );
67
    }
68
69
     /**
70
     * Stop service containers
71
     *
72
     * @param mixed   $composeFiles  The compose files names
73
     * @param string  $signal        Optionnal to precise SIGNAL to send to the container for SIGKILL replacement.
74
     */
75 View Code Duplication
    public function kill($composeFiles = array(), $signal = 'SIGKILL')
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...
76
    {
77
        $command = 'kill';
78
79
        if ($signal !== 'SIGKILL') {
80
            $command .= ' -s ' . $signal;
81
        }
82
83
        return $this->processResult(
84
            $this->execute(
85
                $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
86
            )
87
        );
88
    }
89
90
    /**
91
     * Build service images
92
     *
93
     * @param mixed   $composeFiles  The compose files names
94
     * @param boolean $pull          If we want attempt to pull a newer version of the from image
95
     * @param boolean $forceRemove   If we want remove the intermediate containers
96
     * @param bollean $cache         If we can use the cache when building the image
97
     */
98
    public function build($composeFiles = array(), $pull = true, $forceRemove = false, $cache = true)
99
    {
100
        $command = 'build';
101
102
        if ($pull) {
103
            $command .= ' --pull';
104
        }
105
106
        if ($forceRemove) {
107
            $command .= ' --force-rm';
108
        }
109
110
        if (!$cache) {
111
            $command .= ' --no-cache';
112
        }
113
114
        return $this->processResult(
115
            $this->execute(
116
                $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
117
            )
118
        );
119
    }
120
121
    /**
122
     * Pull service images
123
     *
124
     * @param mixed   $composeFiles  The compose files names
125
     */
126
    public function pull($composeFiles = array())
127
    {
128
        $command = 'pull';
129
130
        return $this->processResult(
131
            $this->execute(
132
                $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
133
            )
134
        );
135
    }
136
137
138
    /**
139
     * Restart running containers
140
     *
141
     * @param mixed   $composeFiles  The compose files names
142
     * @param integer $timeout       If we want attempt to pull a newer version of the from image
143
     */
144 View Code Duplication
    public function restart($composeFiles = array(), $timeout = 10)
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...
145
    {
146
        $command = 'restart';
147
148
        if ($timeout != 10) {
149
            $command .= ' --timeout='.$timeout;
150
        }
151
152
        return $this->processResult(
153
            $this->execute(
154
                $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
155
            )
156
        );
157
    }
158
159
    /**
160
     * Run service with command
161
     *
162
     * @param string $service Service name
163
     * @param string $command Command to pass to service
164
     * @param mixed   $composeFiles  The compose files names
165
     */
166
    public function run($service, $command, $composeFiles = array())
167
    {
168
        $command = 'run --rm ' . $service . ' ' . $command;
169
        $result = $this->execute(
170
            $this->formatCommand($command, $this->createComposeFileCollection($composeFiles))
171
        );
172
173
        if ($result['code'] == 1 && strpos($result['output'], 'service') != false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpos($result['output'], 'service') of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
174
            throw new NoSuchServiceException($result['output']);
175
        }
176
177
        return $this->processResult($result);
178
    }
179
180
    /**
181
     * List containers
182
     *
183
     * @param mixed $composeFiles The compose files names
184
     */
185
    public function ps($composeFiles = array())
186
    {
187
        return $this->processResult(
188
            $this->execute(
189
                $this->formatCommand('ps', $this->createComposeFileCollection($composeFiles))
190
            )
191
        );
192
    }
193
194
    /**
195
     * List IP containers
196
     *
197
     * @param mixed $composeFiles The compose files names
198
     */
199 View Code Duplication
    public function ips($composeFiles = array())
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...
200
    {
201
        $command = $this->formatCommand('ps', $this->createComposeFileCollection($composeFiles));
202
203
        $command = 'for CONTAINER in $(' . $command . ' -q); ';
204
        $command .= 'do echo "$(docker inspect --format \' {{ .Name }} \' $CONTAINER)\t';
205
        $command .= '$(docker inspect --format \' {{ .NetworkSettings.IPAddress }} \' $CONTAINER)"; done';
206
207
        return $this->processResult($this->execute($command));
0 ignored issues
show
Documentation introduced by
$command is of type string, but the function expects a object<mikehaertl\shellcommand\Command>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
208
    }
209
210
    /**
211
     * Process result with returned code and output
212
     *
213
     * @param array $result The result of command with output and returnCode
214
     *
215
     * @throws DockerInstallationMissingException When returned code is 127
216
     * @throws ComposeFileNotFoundException When no compose file precise and docker-compose.yml not found
217
     * @throws DockerHostConnexionErrorException When we can't connect to docker host
218
     * @throws \Exception When an unknown error is returned
219
     */
220
    private function processResult($result)
221
    {
222
        if ($result['code'] === 127) {
223
            throw new DockerInstallationMissingException();
224
        }
225
226
        if ($result['code'] === 1) {
227
            if (!strpos($result['output'], 'DOCKER_HOST')) {
228
                if (!strpos($result['output'], 'docker-compose.yml')) {
229
                    throw new Exception($result['output']);
230
                } else {
231
                    throw new ComposeFileNotFoundException();
232
                }
233
            } else {
234
                throw new DockerHostConnexionErrorException();
235
            }
236
        }
237
238
        return $result['output'];
239
    }
240
241
    /**
242
     * Create the composeFileCollection from the type of value given
243
     *
244
     * @param mixed $composeFiles The docker-compose files (can be array, string or ComposeFile)
245
     *
246
     * @return ComposeFileCollection
247
     */
248
    private function createComposeFileCollection($composeFiles)
249
    {
250
        if (!$composeFiles instanceof ComposeFileCollection) {
251
            if (!is_array($composeFiles)) {
252
                return new ComposeFileCollection([$composeFiles]);
253
            } else {
254
                return new ComposeFileCollection($composeFiles);
255
            }
256
        } else {
257
            return $composeFiles;
258
        }
259
    }
260
261
    /**
262
     * Format the command to execute
263
     *
264
     * @param string                $subcommand   The subcommand to pass to docker-compose command
265
     * @param ComposeFileCollection $composeFiles The compose files to precise in the command
266
     */
267
    private function formatCommand($subcommand, ComposeFileCollection $composeFiles)
268
    {
269
        $command = new Command("docker-compose");
270
        $project = '';
0 ignored issues
show
Unused Code introduced by
$project 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...
271
272
        # Add files names
273
        $preciseFiles = '';
0 ignored issues
show
Unused Code introduced by
$preciseFiles 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...
274
        foreach ($composeFiles->getAll() as $composeFile) {
275
            $command->addArg('-f', $composeFile->getFileName());
276
            #$preciseFiles .= ' -f ' . $composeFile->getFileName();
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
277
        }
278
279
        # Add project name
280
        if ($composeFiles->getProjectName() != null) {
281
            $command->addArg('--project-name', $composeFiles->getProjectName());
282
            #$project = ' --project-name ' . $composeFiles->getProjectName();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
283
        }
284
285
        $command->addArg($subcommand);
286
287
        return $command;
288
    }
289
290
    /**
291
     * Execute docker-compose commande
292
     * @codeCoverageIgnore
293
     * @param Command $command The command to execute.
294
     */
295
    protected function execute($command)
296
    {
297
        if ($command->execute()) {
298
            $output = $command->getOutput();
299
        } else {
300
            $output = $command->getError();
301
        }
302
303
        return array(
304
            'output' => $output,
305
            'code' => $command->getExitCode()
306
        );
307
    }
308
}
309