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 ( 38e978...b0dac0 )
by Anton
02:21
created

functions.php ➔ task()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 7
nop 2
dl 0
loc 25
ccs 9
cts 9
cp 1
crap 5
rs 8.439
c 0
b 0
f 0
1
<?php
2
/* (c) Anton Medvedev <[email protected]>
3
 *
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
namespace Deployer;
8
9
use Deployer\Builder\BuilderInterface;
10
use Deployer\Server\Local;
11
use Deployer\Server\Remote;
12
use Deployer\Server\Builder;
13
use Deployer\Server\Configuration;
14
use Deployer\Server\Environment;
15
use Deployer\Task\Task as T;
16
use Deployer\Task\Context;
17
use Deployer\Task\GroupTask;
18
use Deployer\Task\Scenario\GroupScenario;
19
use Deployer\Task\Scenario\Scenario;
20
use Deployer\Type\Result;
21
use Symfony\Component\Console\Question\ConfirmationQuestion;
22
use Symfony\Component\Console\Question\Question;
23
use Symfony\Component\Finder\Finder;
24
use Symfony\Component\Process\Process;
25
use Deployer\Cluster\ClusterFactory;
26
use Symfony\Component\Console\Input\InputArgument;
27
use Symfony\Component\Console\Input\InputInterface;
28
use Symfony\Component\Console\Input\InputOption;
29
use Symfony\Component\Console\Output\OutputInterface;
30
31
// There are two types of functions: Deployer dependent and Context dependent.
32
// Deployer dependent function uses in definition stage of recipe and may require Deployer::get() method.
33
// Context dependent function uses while task execution and must require only Context::get() method.
34
// But there is also a third type of functions: mixed. Mixed function uses in definition stage and in task
35
// execution stage. They are acts like two different function, but have same name. Example of such function
36
// is set() func. This function determine in which stage it was called by Context::get() method.
37
38
/**
39
 * @param string $name
40
 * @param string|null $host
41 2
 * @param int $port
42
 * @return BuilderInterface
43 2
 */
44 2
function server($name, $host = null, $port = 22)
45
{
46 2
    $deployer = Deployer::get();
47
48
    $env = new Environment();
49 2
    $config = new Configuration($name, $host, $port);
50
51
    if (get('ssh_type') === 'ext-ssh2') {
52 2
        $server = new Remote\SshExtension($config);
53 2
    } elseif (get('ssh_type') && get('ssh_type') === 'native') {
54
        $server = new Remote\NativeSsh($config);
55 2
    } else {
56
        $server = new Remote\PhpSecLib($config);
57
    }
58
59
    $deployer->servers->set($name, $server);
60
    $deployer->environments->set($name, $env);
61
62
    return new Builder($config, $env);
63
}
64
65 15
66
/**
67 15
 * @param string $name
68 15
 * @return BuilderInterface
69 15
 */
70
function localServer($name)
71 15
{
72 15
    $deployer = Deployer::get();
73
74 15
    $env = new Environment();
75
    $config = new Configuration($name, 'localhost'); // Builder requires server configuration.
76
    $server = new Local($config);
77
78
    $deployer->servers->set($name, $server);
79
    $deployer->environments->set($name, $env);
80
81
    return new Builder($config, $env);
82
}
83
84
/**
85
 * @param string $name Name of the cluster
86
 * @param array $nodes An array of nodes' host/ip
87
 * @param int $port Ssh port of the nodes
88
 *
89
 * Example:
90
 * You should pass a cluster name and nodes array.
91 2
 * Nodes array should be as following:
92
 * [ '192.168.1.1', 'example.com', '192.168.1.5' ]
93 2
 * @return BuilderInterface
94
 */
95 2
function cluster($name, $nodes, $port = 22)
96
{
97
    $deployer = Deployer::get();
98
99
    $cluster = ClusterFactory::create($deployer, $name, $nodes, $port);
100
101
    return $cluster->getBuilder();
102
}
103
104
105 1
/**
106 1
 * Load server list file.
107 1
 * @param string $file
108 1
 */
109 1
function serverList($file)
110 1
{
111
    $bootstrap = new Bootstrap\BootstrapByConfigFile();
112
    $bootstrap->setConfig($file);
113
    $bootstrap->parseConfig();
114
    $bootstrap->initServers();
115
    $bootstrap->initClusters();
116
}
117
118
/**
119
 * Set task description.
120
 *
121
 * @param ?string $title
0 ignored issues
show
Documentation introduced by
The doc-type ?string could not be parsed: Unknown type name "?string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
122 17
 * @return ?string
0 ignored issues
show
Documentation introduced by
The doc-type ?string could not be parsed: Unknown type name "?string" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
123
 */
124 17
function desc($title = null)
125 17
{
126 17
    static $store = null;
127 17
128 3
    if ($title === null) {
129
        return $store;
130 3
    } else {
131 3
        return $store = $title;
132 3
    }
133 1
}
134
135
/**
136 17
 * Define a new task and save to tasks list.
137 17
 *
138
 * @param string $name Name of current task.
139 17
 * @param callable|array|string $body Callable task or array of other tasks names.
140
 * @return Task\Task
141
 * @throws \InvalidArgumentException
142
 */
143
function task($name, $body)
144
{
145
    $deployer = Deployer::get();
146
147
    if ($body instanceof \Closure) {
148
        $task = new T($name, $body);
149 14
    } elseif (is_array($body)) {
150 1
        $task = new GroupTask($name, $body);
0 ignored issues
show
Documentation introduced by
$body is of type array, but the function expects a string.

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...
151 2
    } elseif (is_string($body)) {
152 2
        $task = new T($name, function () use ($body) {
153
            run($body);
154 1
        });
155 1
    } else {
156
        throw new \InvalidArgumentException('Task should be an closure or array of other tasks.');
157
    }
158
159
    $deployer->tasks->set($name, $task);
160
161
    if (!empty(desc())) {
162
        $task->desc(desc());
163
        desc(''); // Clear title.
164
    }
165 1
166 1
    return $task;
167 1
}
168
169 1
/**
170 1
 * Call that task before specified task runs.
171
 *
172
 * @param string $it
173
 * @param string $that
174
 */
175
function before($it, $that)
176
{
177
    $deployer = Deployer::get();
178
    $beforeTask = $deployer->tasks->get($it);
179
180
    $beforeTask->addBefore($that);
181
}
182
183
/**
184 14
 * Call that task after specified task runs.
185 14
 *
186 14
 * @param string $it
187 14
 * @param string $that
188
 */
189
function after($it, $that)
190
{
191
    $deployer = Deployer::get();
192
    $afterTask = $deployer->tasks->get($it);
193
194
    $afterTask->addAfter($that);
195
}
196
197
/**
198
 * Add users arguments.
199
 *
200 14
 * Note what Deployer already has one argument: "stage".
201 14
 *
202 14
 * @param string $name
203 14
 * @param int $mode
204
 * @param string $description
205
 * @param mixed $default
206
 */
207
function argument($name, $mode = null, $description = '', $default = null)
208
{
209
    Deployer::get()->getConsole()->getUserDefinition()->addArgument(
210
        new InputArgument($name, $mode, $description, $default)
211
    );
212 2
}
213 2
214
/**
215
 * Add users options.
216
 *
217
 * @param string $name
218
 * @param string $shortcut
219
 * @param int $mode
220
 * @param string $description
221
 * @param mixed $default
222
 */
223
function option($name, $shortcut = null, $mode = null, $description = '', $default = null)
224
{
225
    Deployer::get()->getConsole()->getUserDefinition()->addOption(
226
        new InputOption($name, $shortcut, $mode, $description, $default)
227
    );
228
}
229
230
/**
231
 * Change the current working directory.
232
 *
233
 * @param string $path
234
 */
235
function cd($path)
236 12
{
237
    set('working_path', Context::get()->getEnvironment()->parse($path));
238
}
239
240
/**
241
 * Execute a callback within a specific directory and revert back to the initial working directory.
242
 *
243
 * @param string $path
244
 * @param callable $callback
245
 */
246
function within($path, $callback)
247 12
{
248 12
    $lastWorkingPath = workingPath();
249 12
    set('working_path', $path);
250
    $callback();
251 12
    set('working_path', $lastWorkingPath);
252 11
}
253 11
254
/**
255 12
 * Return the current working path.
256
 *
257
 * @return string
258
 */
259 12
function workingPath()
260
{
261 12
    return get('working_path', get(Environment::DEPLOY_PATH, ''));
262
}
263
264
/**
265
 * Run command on server.
266
 *
267 12
 * @param string $command
268
 * @return Result
269
 */
270
function run($command)
271
{
272
    $server = Context::get()->getServer();
273
    $serverName = $server->getConfiguration()->getName();
274
    $command = Context::get()->getEnvironment()->parse($command);
275
    $workingPath = workingPath();
276
277
    if (!empty($workingPath)) {
278
        $command = "cd $workingPath && $command";
279 5
    }
280
281 5
    if (isVeryVerbose()) {
282
        writeln("[$serverName] <fg=red>></fg=red> $command");
283
    }
284
285 5
    if ($server instanceof Local) {
286 5
        $output = $server->mustRun($command, function ($type, $buffer) use ($serverName) {
287 View Code Duplication
            if (isDebug()) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
288 4
                output()->writeln(array_map(function ($line) use ($serverName) {
289
                    return output()->isDecorated()
290
                        ? "[$serverName] \033[1;30m< $line\033[0m"
291
                        : "[$serverName] < $line";
292
                }, explode("\n", rtrim($buffer))), OutputInterface::OUTPUT_RAW);
293
            }
294
        });
295 5
    } else {
296
        $output = $server->run($command);
297 5 View Code Duplication
        if (isDebug() && !empty($output)) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
298
            output()->writeln(array_map(function ($line) use ($serverName) {
299
                return output()->isDecorated()
300
                    ? "[$serverName] \033[1;30m< $line\033[0m"
301 5
                    : "[$serverName] < $line";
302
            }, explode("\n", rtrim($output))), OutputInterface::OUTPUT_RAW);
303
        }
304
    }
305
306
    return new Result($output);
307
}
308
309
/**
310
 * Execute commands on local machine.
311
 * @param string $command Command to run locally.
312 1
 * @param int $timeout (optional) Override process command timeout in seconds.
313 1
 * @return Result Output of command.
314 1
 * @throws \RuntimeException
315
 */
316 1
function runLocally($command, $timeout = 60)
317 1
{
318
    $command = Context::get()->getEnvironment()->parse($command);
319 1
320 1
    if (isVeryVerbose()) {
321 1
        writeln("<comment>Run locally</comment>: $command");
322
    }
323 1
324
    $process = new Process($command);
325 1
    $process->setTimeout($timeout);
326 1
    $process->run(function ($type, $buffer) {
327 1
        if (isDebug()) {
328 1
            if ('err' === $type) {
329 1
                write("<fg=red>></fg=red> $buffer");
330
            } else {
331
                write("<fg=green>></fg=green> $buffer");
332 1
            }
333 1
        }
334
    });
335
336
    if (!$process->isSuccessful()) {
337 1
        throw new \RuntimeException($process->getErrorOutput());
338 1
    }
339 1
340 1
    return new Result($process->getOutput());
341 1
}
342 1
343
344
/**
345 1
 * Upload file or directory to current server.
346
 * @param string $local
347
 * @param string $remote
348
 * @throws \RuntimeException
349
 */
350
function upload($local, $remote)
351
{
352
    $server = Context::get()->getServer();
353
    $local = Context::get()->getEnvironment()->parse($local);
354
    $remote = Context::get()->getEnvironment()->parse($remote);
355 2
356 2
    if (is_file($local)) {
357 2
        writeln("Upload file <info>$local</info> to <info>$remote</info>");
358
359 2
        $server->upload($local, $remote);
360 2
    } elseif (is_dir($local)) {
361
        writeln("Upload from <info>$local</info> to <info>$remote</info>");
362
363
        $finder = new Finder();
364
        $files = $finder
365
            ->files()
366
            ->ignoreUnreadableDirs()
367
            ->ignoreVCS(true)
368 4
            ->ignoreDotFiles(false)
369 4
            ->in($local);
370
371
        /** @var $file \Symfony\Component\Finder\SplFileInfo */
372
        foreach ($files as $file) {
373
            if (isDebug()) {
374
                writeln("Uploading <info>{$file->getRealPath()}</info>");
375
            }
376
377
            $server->upload(
378
                $file->getRealPath(),
379
                $remote . '/' . $file->getRelativePathname()
380
            );
381
        }
382
    } else {
383
        throw new \RuntimeException("Uploading path '$local' does not exist.");
384
    }
385
}
386 14
387 14
/**
388
 * Download file from remote server.
389
 *
390
 * @param string $local
391
 * @param string $remote
392
 */
393
function download($local, $remote)
394
{
395 4
    $server = Context::get()->getServer();
396
    $local = Context::get()->getEnvironment()->parse($local);
397
    $remote = Context::get()->getEnvironment()->parse($remote);
398
399
    $server->download($local, $remote);
400
}
401
402
/**
403
 * Writes a message to the output and adds a newline at the end.
404
 * @param string|array $message
405
 */
406
function writeln($message)
407
{
408
    output()->writeln($message);
409
}
410
411
/**
412
 * Writes a message to the output.
413
 * @param string $message
414
 */
415
function write($message)
416
{
417
    output()->write($message);
418
}
419
420
/**
421
 * Setup configuration option.
422
 *
423
 * @param string $name
424
 * @param mixed $value
425
 */
426
function set($name, $value)
427
{
428
    if (Context::get() === false) {
429
        Deployer::setDefault($name, $value);
430
    } else {
431
        Context::get()->getEnvironment()->set($name, $value);
432
    }
433
}
434
435
/**
436
 * Merge new config params to existing config array.
437
 *
438
 * @param string $name
439
 * @param array $array
440
 */
441
function add($name, $array)
442
{
443
    if (Context::get() === false) {
444
        Deployer::addDefault($name, $array);
445
    } else {
446
        Context::get()->getEnvironment()->add($name, $array);
447
    }
448
}
449
450
/**
451
 * Get configuration value.
452
 *
453
 * @param string $name
454
 * @param mixed|null $default
455
 * @return mixed
456
 */
457
function get($name, $default = null)
458
{
459
    if (Context::get() === false) {
460
        return Deployer::getDefault($name, $default);
461
    } else {
462
        return Context::get()->getEnvironment()->get($name, $default);
463
    }
464
}
465
466
/**
467
 * Check if there is such configuration option.
468
 *
469
 * @param string $name
470
 * @return boolean
471
 */
472
function has($name)
473
{
474
    if (Context::get() === false) {
475
        return Deployer::hasDefault($name);
476
    } else {
477
        return Context::get()->getEnvironment()->has($name);
478
    }
479
}
480
481
/**
482
 * @param string $message
483
 * @param string|null $default
484
 * @return string
485
 * @codeCoverageIgnore
486 17
 */
487
function ask($message, $default = null)
488
{
489
    if (isQuiet()) {
490
        return $default;
491
    }
492
493
    $helper = Deployer::get()->getHelper('question');
494
495
    $message = "<question>$message" . (($default === null) ? "" : " [$default]") . "</question> ";
496
497
    $question = new Question($message, $default);
498
499
    return $helper->ask(input(), output(), $question);
500
}
501
502
/**
503 1
 * @param string $message
504
 * @param bool $default
505
 * @return bool
506
 * @codeCoverageIgnore
507
 */
508
function askConfirmation($message, $default = false)
509
{
510
    if (isQuiet()) {
511
        return $default;
512 16
    }
513
514
    $helper = Deployer::get()->getHelper('question');
515
516
    $yesOrNo = $default ? 'Y/n' : 'y/N';
517
    $message = "<question>$message [$yesOrNo]</question> ";
518
519
    $question = new ConfirmationQuestion($message, $default);
520
521 17
    return $helper->ask(input(), output(), $question);
522
}
523
524
/**
525
 * @param string $message
526
 * @return string
527
 * @codeCoverageIgnore
528
 */
529
function askHiddenResponse($message)
530
{
531
    if (isQuiet()) {
532
        return '';
533
    }
534 19
535 14
    $helper = Deployer::get()->getHelper('question');
536 14
537 19
    $message = "<question>$message</question> ";
538 19
539 8
    $question = new Question($message);
540 6
    $question->setHidden(true);
541
    $question->setHiddenFallback(false);
542 2
543
    return $helper->ask(input(), output(), $question);
544 2
}
545
546 14
/**
547
 * @return InputInterface
548
 */
549
function input()
550
{
551
    return Context::get()->getInput();
552
}
553
554
555
/**
556 2
 * @return OutputInterface
557
 */
558
function output()
559
{
560
    return Context::get()->getOutput();
561
}
562
563
/**
564
 * @return bool
565
 */
566
function isQuiet()
567
{
568
    return OutputInterface::VERBOSITY_QUIET === output()->getVerbosity();
569
}
570
571
572
/**
573
 * @return bool
574
 */
575
function isVerbose()
576
{
577
    return OutputInterface::VERBOSITY_VERBOSE <= output()->getVerbosity();
578
}
579
580
581
/**
582
 * @return bool
583
 */
584
function isVeryVerbose()
585
{
586
    return OutputInterface::VERBOSITY_VERY_VERBOSE <= output()->getVerbosity();
587
}
588
589
590
/**
591
 * @return bool
592
 */
593
function isDebug()
594
{
595
    return OutputInterface::VERBOSITY_DEBUG <= output()->getVerbosity();
596
}
597
598
/**
599
 * Deprecated, use set()/get().
600
 * @deprecated
601
 */
602
function env()
603
{
604
    throw new \RuntimeException('env() function deprecated. Please, use set() or get() instead of.');
605
}
606
607
/**
608
 * Check if command exist in bash.
609
 *
610
 * @param string $command
611
 * @return bool
612
 */
613
function commandExist($command)
614
{
615
    return run("if hash $command 2>/dev/null; then echo 'true'; fi")->toBool();
616
}
617