Passed
Push — master ( 092a24...2d756b )
by Alexis
01:25 queued 11s
created

src/Command/StatusesReadCommand.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace AlexisLefebvre\Bundle\AsyncTweetsBundle\Command;
4
5
use Symfony\Component\Console\Helper\Table;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
10
class StatusesReadCommand extends BaseCommand
11
{
12
    private $table;
13
14 9
    protected function configure()
15
    {
16 9
        parent::configure();
17
18
        $this
19 9
            ->setName('statuses:read')
20 9
            ->setDescription('Read home timeline')
21 9
            ->addArgument('page', InputArgument::OPTIONAL, 'Page');
22 9
    }
23
24
    /**
25
     * @param InputInterface  $input
26
     * @param OutputInterface $output
27
     *
28
     * @return int|void
29
     */
30 2
    protected function execute(InputInterface $input, OutputInterface $output)
31
    {
32
        /** @var int|null $page */
33 2
        $page = $input->getArgument('page');
34
35 2
        if ($page < 1) {
36 2
            $page = 1;
37
        }
38
39 2
        $output->writeln(sprintf(
40 2
            'Current page: <comment>%d</comment>',
41 2
            $page
42
        ));
43
44
        // Get the tweets
45 2
        $tweets = $this->em
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getWithUsers() does only exist in the following implementations of said interface: AlexisLefebvre\Bundle\As...\Entity\TweetRepository.

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...
46 2
            ->getRepository('AsyncTweetsBundle:Tweet')
47 2
            ->getWithUsers($page);
48
49 2
        if (!$tweets) {
50 1
            $output->writeln('<info>No tweet to display.</info>');
51
52 1
            return 0;
53
        }
54
55 1
        $this->displayTweets($output, $tweets);
56 1
    }
57
58
    /**
59
     * @param OutputInterface $output
60
     * @param array           $tweets
61
     */
62 1
    protected function displayTweets(
63
        OutputInterface $output,
64
        $tweets
65
    ) {
66 1
        $this->setTable($output);
67
68 1
        foreach ($tweets as $tweet) {
69 1
            $this->table->addRows(
70
                [
71
                    [
72 1
                        $this->formatCell(
73 1
                            'info',
74 1
                            $tweet->getUser()->getName(),
75 1
                            13
76
                        ),
77 1
                        $this->formatCell(
78 1
                            'comment',
79 1
                            $tweet->getText(),
80 1
                            40
81
                        ),
82 1
                        $tweet->getCreatedAt()->format('Y-m-d H:i'),
83
                    ],
84
                    // empty row between tweets
85
                    ['', '', ''],
86
                ]
87
            );
88
        }
89
90 1
        $this->table->render();
91 1
    }
92
93 1
    protected function setTable(OutputInterface $output)
94
    {
95 1
        $this->table = new Table($output);
96 1
        $this->table
97 1
            ->setHeaders([
98
                // Add spaces to use all the 80 columns,
99
                //  even if name or texts are short
100 1
                sprintf('%-13s', 'Name'),
101 1
                sprintf('%-40s', 'Text'),
102 1
                sprintf('%-16s', 'Datetime'),
103
            ]);
104 1
    }
105
106
    /**
107
     * @param string $tag
108
     * @param string $content
109
     * @param int    $length
110
     *
111
     * @return string
112
     */
113 1
    protected function formatCell($tag, $content, $length)
114
    {
115 1
        return '<'.$tag.'>'.
116
            // Close and reopen the tag before each new line
117 1
            str_replace(
118 1
                "\n",
119 1
                '</'.$tag.">\n<".$tag.'>',
120 1
                wordwrap($content, $length, "\n")
121
            ).
122 1
            '</'.$tag.'>';
123
    }
124
}
125