Completed
Push — master ( 597ac5...b01469 )
by Robbie
9s
created

DebugCommand   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 21
c 1
b 0
f 0
lcom 1
cbo 7
dl 0
loc 187
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 23 1
B execute() 0 26 4
A getId() 0 8 3
A getData() 0 14 3
B askInteractively() 0 30 3
B sanitizeResults() 0 13 5
A output() 0 18 2
1
<?php
2
3
namespace SilverLeague\Console\Command\Object;
4
5
use SilverLeague\Console\Command\SilverStripeCommand;
6
use Symfony\Component\Console\Helper\Table;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Console\Question\ChoiceQuestion;
12
use Symfony\Component\Console\Question\Question;
13
14
/**
15
 * Outputs a formatted data representation of a DataObject's values in either JSON or a table.
16
 *
17
 * The class name is required, but the ID is optional. If left blank an interactive search-by-column will be given
18
 * for all of the object's columns.
19
 *
20
 * @package silverstripe-console
21
 * @author  Robbie Averill <[email protected]>
22
 */
23
class DebugCommand extends SilverStripeCommand
24
{
25
    /**
26
     * {@inheritDoc}
27
     */
28
    protected function configure()
29
    {
30
        $this
31
            ->setName('object:debug')
32
            ->setDescription('Outputs a visual representation of a DataObject')
33
            ->addArgument('object', InputArgument::REQUIRED, 'DataObject class name')
34
            ->addArgument('id', InputArgument::OPTIONAL, 'The ID, or field to search')
35
            ->addOption('no-sort', null, InputOption::VALUE_NONE, 'Do not sort the output')
36
            ->addOption('output-table', null, InputOption::VALUE_NONE, 'Output in a table');
37
38
        $this->setHelp(
39
            <<<TEXT
40
Look up a DataObject by class name and either it's ID or an interactive search-by-column.
41
42
If no ID is provided then an interactive prompt will ask for the column to search by, then autocomplete all available
43
values for that class's columns to choose from.
44
45
The default output format is JSON. You can add the --output-table option to output the results in a table instead.
46
47
By default the output will also be sorted by key. Do prevent this, add the --no-sort option.
48
TEXT
49
        );
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     */
55
    protected function execute(InputInterface $input, OutputInterface $output)
56
    {
57
        $objectClass = $input->getArgument('object');
58
        if (!class_exists($objectClass) || !is_subclass_of($objectClass, "SilverStripe\ORM\DataObject")) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
59
            $output->writeln('<error>' . $objectClass . ' does not exist, or is not a DataObject.</error>');
60
            return;
61
        }
62
63
        $id = $this->getId($input, $output, $objectClass);
64
        $data = $this->getData($input, $objectClass, $id);
65
        if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
66
            $output->writeln('<error>' . $objectClass . ' with ID ' . $id . ' was not found.</error>');
67
            return;
68
        }
69
70
        $output->writeln(
71
            [
72
                '<info>Object: ' . $objectClass . '</info>',
73
                '<info>ID: ' . $id . '</info>',
74
                ''
75
            ]
76
        );
77
78
        $asTable = $input->getOption('output-table');
79
        $this->output($output, $data, $asTable);
80
    }
81
82
    /**
83
     * Get the "id" argument either from that provided, or trigger the interactive lookup
84
     *
85
     * @param  InputInterface $input
86
     * @param  OutputInterface $output
87
     * @return int
88
     */
89
    protected function getId(InputInterface $input, OutputInterface $output, $objectClass)
90
    {
91
        $id = $input->getArgument('id');
92
        if (!$id || !is_numeric($id)) {
93
            $id = $this->askInteractively($input, $output, $objectClass);
94
        }
95
        return $id;
96
    }
97
98
    /**
99
     * Load the object by the given ID and return an optionally sorted array of its data
100
     *
101
     * @param  InputInterface $input
102
     * @param  string $objectClass
103
     * @param  int $id
104
     * @return array
105
     */
106
    protected function getData(InputInterface $input, $objectClass, $id)
107
    {
108
        $data = $objectClass::get()->byId($id);
109
        if (!$data) {
110
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SilverLeague\Console\Com...t\DebugCommand::getData of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
111
        }
112
        $data = $data->toMap();
113
114
        $this->sanitizeResults($data);
115
        if (!$input->getOption('no-sort')) {
116
            ksort($data);
117
        }
118
        return $data;
119
    }
120
121
    /**
122
     * Find the DataObject entity to retrieve and return its ID. This method works by first asking to select
123
     * one of the object's data columns to filter with, then asking again with an autocompletion on that column
124
     * to assist with finding the entity you want to return.
125
     *
126
     * @param  InputInterface $input
127
     * @param  OutputInterface $output
128
     * @param  string $objectClass
129
     * @return int
130
     */
131
    protected function askInteractively(InputInterface $input, OutputInterface $output, $objectClass)
132
    {
133
        $choices = $objectClass::get()->toArray();
0 ignored issues
show
Unused Code introduced by
$choices 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...
134
        $class = singleton($objectClass);
135
        $columns = array_keys($objectClass::getSchema()->databaseFields($objectClass));
136
        $this->sanitizeResults($columns);
137
138
        $question = new ChoiceQuestion('Choose a column to search by:', $columns);
139
        $column = $this->getHelper('question')->ask($input, $output, $question);
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 ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

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...
140
141
        $entities = $objectClass::get()->map('ID', $column)->toArray();
142
        $this->sanitizeResults($entities, true);
143
144
        $question = new Question('Look up ' . $class->i18n_singular_name() . ' by ' . $column . ': ');
145
        $question->setAutocompleterValues($entities);
146
        $entity = $this->getHelper('question')->ask($input, $output, $question);
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 ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

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...
147
148
        preg_match('/\[#(?<id>\d+)\]$/', $entity, $matches);
149
        if (!empty($matches['id'])) {
150
            return $matches['id'];
151
        }
152
153
        // Try and look up the column and value instead
154
        $object = $objectClass::get()->filter($column, $entity)->first();
155
        if ($object) {
156
            return $object->ID;
157
        }
158
159
        return 0;
160
    }
161
162
    /**
163
     * Remove array entries that might be passwords, and add the ID to the end of the value for when autocompleting
164
     *
165
     * @param  array &$results The data array, or array of column names
166
     * @param  bool $addId     Whether to add the ID to the value for display purposes
167
     * @return $this
168
     */
169
    protected function sanitizeResults(&$results, $addId = false)
170
    {
171
        foreach ($results as $key => $value) {
172
            if (stripos($value, 'Password') !== false || stripos($key, 'Password') !== false) {
173
                unset($results[$key]);
174
            }
175
            if ($addId) {
176
                $results[$key] .= ' [#' . $key . ']';
177
            }
178
        }
179
180
        return $this;
181
    }
182
183
    /**
184
     * Output the results to the console in either JSON format or in a table
185
     *
186
     * @param  OutputInterface $output
187
     * @param  array $data
188
     * @param  bool $asTable
189
     * @return $this
190
     */
191
    protected function output(OutputInterface $output, $data, $asTable = false)
192
    {
193
        if (!$asTable) {
194
            return $output->writeln(json_encode($data, JSON_PRETTY_PRINT));
195
        }
196
197
        array_walk($data, function (&$value, $key) {
198
            $value = [$key, $value];
199
        });
200
201
        $table = new Table($output);
202
        $table
203
            ->setHeaders(['Key', 'Value'])
204
            ->setRows($data)
205
            ->render();
206
207
        return $this;
208
    }
209
}
210