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.

JobCommand   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 210
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
dl 0
loc 210
rs 10
c 0
b 0
f 0
wmc 24
lcom 1
cbo 13

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A mergeApplicationDefinition() 0 11 3
A getSynopsis() 0 11 2
A configure() 0 7 1
A getDescription() 0 10 2
A getHelp() 0 9 1
A getJob() 0 7 2
B initialize() 0 29 4
C execute() 0 30 8
1
<?php
2
/**
3
 * See class comment
4
 *
5
 * PHP Version 5
6
 *
7
 * @category   Netresearch
8
 * @package    Netresearch\Kite
9
 * @subpackage Console
10
 * @author     Christian Opitz <[email protected]>
11
 * @license    http://www.netresearch.de Netresearch Copyright
12
 * @link       http://www.netresearch.de
13
 */
14
15
namespace Netresearch\Kite\Console\Command;
16
use Netresearch\Kite\Console\Output\Output;
17
use Netresearch\Kite\Service\Config;
18
use Netresearch\Kite\Exception;
19
use Netresearch\Kite\Exception\ExitException;
20
use Netresearch\Kite\Job;
21
use Netresearch\Kite\Service\Console;
22
use Netresearch\Kite\Service\Descriptor;
23
use Symfony\Component\Console\Command\Command;
24
use Symfony\Component\Console\Input\InputInterface;
25
26
use Symfony\Component\Console\Output\ConsoleOutput;
27
use Symfony\Component\Console\Output\OutputInterface;
28
29
/**
30
 * Command to execute a job
31
 *
32
 * @category   Netresearch
33
 * @package    Netresearch\Kite
34
 * @subpackage Console
35
 * @author     Christian Opitz <[email protected]>
36
 * @license    http://www.netresearch.de Netresearch Copyright
37
 * @link       http://www.netresearch.de
38
 */
39
class JobCommand extends Command
40
{
41
    /**
42
     * @var \Netresearch\Kite\Job
43
     */
44
    protected $job;
45
46
    /**
47
     * @var \Netresearch\Kite\Service\Console
48
     */
49
    protected $console;
50
51
    protected $jobDefinitionMerged = false;
52
53
    /**
54
     * Constructor.
55
     *
56
     * @param string $name   The name of the job
57
     * @param Config $config Config
58
     *
59
     * @api
60
     */
61
    public function __construct($name, Config $config)
62
    {
63
        parent::__construct($name);
64
        $this->console = new Console($config);
65
    }
66
67
    /**
68
     * Remove workflow option
69
     *
70
     * @param bool $mergeArgs mergeArgs
71
     *
72
     * @return void
73
     */
74
    public function mergeApplicationDefinition($mergeArgs = true)
75
    {
76
        parent::mergeApplicationDefinition($mergeArgs);
77
        $options = array();
78
        foreach ($this->getDefinition()->getOptions() as $option) {
79
            if ($option->getName() !== 'workflow') {
80
                $options[] = $option;
81
            }
82
        }
83
        $this->getDefinition()->setOptions($options);
84
    }
85
86
    /**
87
     * Merge in job definition
88
     *
89
     * @param bool $short Whether to return short synopsis
90
     *
91
     * @return string
92
     */
93
    public function getSynopsis($short = false)
94
    {
95
        if (!$this->jobDefinitionMerged) {
96
            $definition = $this->getJob()->getDefinition();
97
            $this->getDefinition()->addOptions($definition->getOptions());
98
            $this->getDefinition()->addArguments($definition->getArguments());
99
            $this->jobDefinitionMerged = true;
100
        }
101
102
        return preg_replace('/^generic:([^:]+):([^ ]+)/', '--$1=$2', parent::getSynopsis($short));
103
    }
104
105
    /**
106
     * Configures the current command.
107
     *
108
     * @return void
109
     */
110
    protected function configure()
111
    {
112
        parent::configure();
113
114
        $this->addOption('dry-run', null, null, 'Show what would happen');
115
        $this->addOption('no-debug-file', null, null, 'Never put debug output to a file');
116
    }
117
118
    /**
119
     * Get the description
120
     *
121
     * @return string
122
     */
123
    public function getDescription()
124
    {
125
        $description = parent::getDescription();
126
        if ($description === null) {
127
            $descriptor = new Descriptor();
128
            $description = (string) $descriptor->describeTask($this->getJob());
129
            parent::setDescription($description);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (setDescription() instead of getDescription()). Are you sure this is correct? If so, you might want to change this to $this->setDescription().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
130
        }
131
        return $description;
132
    }
133
134
    /**
135
     * Display the help - doing this here, because in configure() the helpers are not
136
     * yet available.
137
     *
138
     * @return string
139
     */
140
    public function getHelp()
0 ignored issues
show
Coding Style introduced by
getHelp uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
141
    {
142
        return "\n"
143
            . "The <info>%command.name%</info> command executes the according job\n"
144
            . "from kite configuration:\n\n"
145
            . $this->getHelper('formatter')->formatBlock($this->getDescription(), 'fg=black;bg=green', true)
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method formatBlock() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\FormatterHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
146
            . "\n\nThe canonicalized command is:\n\n"
147
            . "  <info>php " . $_SERVER['PHP_SELF'] . ' ' . preg_replace('/^generic:([^:]+):([^ ]+)/', '--$1=$2', $this->getName()) . "</info>\n";
148
    }
149
150
    /**
151
     * Create and return the job
152
     *
153
     * @return Job
154
     */
155
    public function getJob()
156
    {
157
        if (!$this->job) {
158
            $this->job = $this->console->getFactory()->createJob($this->getName());
159
        }
160
        return $this->job;
161
    }
162
163
    /**
164
     * Initialize the environment
165
     *
166
     * @param InputInterface  $input  Input
167
     * @param OutputInterface $output Output
168
     *
169
     * @return void
170
     */
171
    protected function initialize(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Coding Style introduced by
initialize uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
172
    {
173
        $this->console
174
            ->setApplication($this->getApplication())
0 ignored issues
show
Bug introduced by
It seems like $this->getApplication() can be null; however, setApplication() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
175
            ->setInput($input)
176
            ->setOutput($output);
0 ignored issues
show
Compatibility introduced by
$output of type object<Symfony\Component...Output\OutputInterface> is not a sub-type of object<Netresearch\Kite\Console\Output\Output>. It seems like you assume a concrete implementation of the interface Symfony\Component\Console\Output\OutputInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
177
178
        if (!$input->getOption('no-debug-file') && $debugDir = $input->getOption('debug-dir')) {
179
            $this->console->getFilesystem()->ensureDirectoryExists($debugDir);
180
            // keep max 20 logs
181
            $files = glob($debugDir . '/*');
182
            while (count($files) > 19) {
183
                $this->console->getFilesystem()->remove(array_shift($files));
184
            }
185
            $logFile = date('YmdHis');
186
            $debugOutput = new Output(
187
                fopen(rtrim($debugDir, '\\/') . '/' . $logFile, 'w'),
188
                Output::VERBOSITY_VERY_VERBOSE,
189
                true
190
            );
191
            $this->console->setDebugOutput($debugOutput);
192
            $debugOutput->setTerminalDimensions($this->getApplication()->getTerminalDimensions());
193
            $debugOutput->writeln(
194
                $this->getHelper('formatter')->formatBlock(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method formatBlock() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\FormatterHelper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
195
                    implode(' ', $_SERVER['argv']), 'fg=black;bg=white', true
196
                ) . "\n"
197
            );
198
        }
199
    }
200
201
    /**
202
     * Executes the current command.
203
     *
204
     * This method is not abstract because you can use this class
205
     * as a concrete class. In this case, instead of defining the
206
     * execute() method, you set the code to execute by passing
207
     * a Closure to the setCode() method.
208
     *
209
     * @param InputInterface  $input  An InputInterface instance
210
     * @param OutputInterface $output An OutputInterface instance
211
     *
212
     * @return null|int null or 0 if everything went fine, or an error code
213
     *
214
     * @throws \LogicException When this abstract method is not implemented
215
     *
216
     * @see setCode()
217
     */
218
    protected function execute(InputInterface $input, OutputInterface $output)
219
    {
220
        $job = $this->getJob();
221
        try {
222
            $job->run();
223
        } catch (\Exception $e) {
224
            if ($e instanceof ExitException && $e->getCode() === 0) {
225
                if ($e->getMessage()) {
226
                    $output->writeln('<info>' . $e->getMessage() . '</info>');
227
                }
228
                return 0;
229
            }
230
231
            // This doesn't go to the debug log, as $output->writeln and not $console->output is used:
232
            $this->getApplication()->renderException($e, $output instanceof ConsoleOutput ? $output->getErrorOutput() : $output);
233
            // But this one:
234
            $this->getApplication()->renderException($e, $this->console->getDebugOutput());
235
236
            $exitCode = $e->getCode();
237
            if (is_numeric($exitCode)) {
238
                $exitCode = (int) $exitCode;
239
                if (0 === $exitCode) {
240
                    $exitCode = 1;
241
                }
242
            } else {
243
                $exitCode = 1;
244
            }
245
            return $exitCode;
246
        }
247
    }
248
}
249
250
?>
251