Completed
Push — master ( 05c35a...2edd45 )
by Alexis
06:51
created

StatusesHomeTimelineCommand::getConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
dl 0
loc 14
ccs 11
cts 11
cp 1
rs 9.4286
c 2
b 0
f 1
cc 1
eloc 9
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AlexisLefebvre\Bundle\AsyncTweetsBundle\Command;
4
5
use Symfony\Component\Console\Input\InputInterface;
6
use Symfony\Component\Console\Input\InputOption;
7
use Symfony\Component\Console\Output\OutputInterface;
8
use Symfony\Component\Console\Helper\ProgressBar;
9
use Abraham\TwitterOAuth\TwitterOAuth;
10
use Symfony\Component\Console\Helper\Table;
11
use AlexisLefebvre\Bundle\AsyncTweetsBundle\Utils\PersistTweet;
12
13
class StatusesHomeTimelineCommand extends BaseCommand
14
{
15
    private $displayTable;
16
    private $table;
17
    private $progress;
18
    
19
    /** @see https://dev.twitter.com/rest/reference/get/statuses/home_timeline */
20
    private $parameters = array(
21
        'count' => 200,
22
        'exclude_replies' => true
23
    );
24
    
25 7
    protected function configure()
26
    {
27 7
        parent::configure();
28
        
29 7
        $this
30 7
            ->setName('statuses:hometimeline')
31 7
            ->setDescription('Fetch home timeline')
32
            # http://symfony.com/doc/2.3/cookbook/console/console_command.html#automatically-registering-commands
33 7
            ->addOption('table', null, InputOption::VALUE_NONE,
34 7
                'Display a table with tweets')
35
        ;
36 7
    }
37
38
    /**
39
     * @param InputInterface $input
40
     * @param OutputInterface $output
41
     */
42 7
    protected function execute(InputInterface $input, OutputInterface $output)
43
    {
44 7
        $this->setAndDisplayLastTweet($output);
45
        
46 7
        $content = $this->getContent($input);
47
        
48 7
        if (! is_array($content))
49 7
        {
50 2
            $this->displayContentNotArrayError($output, $content);
51 2
            return 1;
52
        }
53
        
54 5
        $numberOfTweets = count($content);
55
        
56 5
        if ($numberOfTweets == 0)
57 5
        {
58 2
            $output->writeln('<comment>No new tweet.</comment>');
59 2
            return 0;
60
        }
61
        
62 3
        $this->addAndDisplayTweets($input, $output, $content, $numberOfTweets);
63 3
    }
64
    
65
    /**
66
     * @param OutputInterface $output
67
     */
68 7
    protected function setAndDisplayLastTweet(OutputInterface $output)
69
    {
70
        # Get the last tweet
71 7
        $lastTweet = $this->em
72 7
            ->getRepository('AsyncTweetsBundle:Tweet')
73 7
            ->getLastTweet();
74
        
75
        # And use it in the request if it exists
76 7
        if ($lastTweet) {
77 1
            $this->parameters['since_id'] = $lastTweet->getId();
78
            
79 1
            $comment = 'last tweet = '.$this->parameters['since_id'];
80 1
        }
81
        else {
82 6
            $comment = 'no last tweet';
83
        }    
84
        
85 7
        $output->writeln('<comment>'.$comment.'</comment>');
86 7
    }
87
    
88
    /**
89
     * @param InputInterface $input
90
     */
91 1
    protected function getContent(InputInterface $input)
92
    {
93 1
        $connection = new TwitterOAuth(
94 1
            $this->container->getParameter('twitter_consumer_key'),
95 1
            $this->container->getParameter('twitter_consumer_secret'),
96 1
            $this->container->getParameter('twitter_token'),
97 1
            $this->container->getParameter('twitter_token_secret')
98 1
        );
99
        
100 1
        return($connection->get(
101 1
            'statuses/home_timeline',
102 1
            $this->parameters
103 1
        ));
104
    }
105
    
106
    /**
107
     * @param OutputInterface $output
108
     * @param null|object $content
109
     */
110 2
    protected function displayContentNotArrayError(OutputInterface $output,
111
        $content)
112
    {
113 2
        $formatter = $this->getHelper('formatter');
114
        
115 2
        $errorMessages = array('Error!', 'Something went wrong, $content is not an array.');
116 2
        $formattedBlock = $formatter->formatBlock($errorMessages, 'error');
117 2
        $output->writeln($formattedBlock);
118 2
        $output->writeln(print_r($content, true));
119 2
    }
120
    
121
    /**
122
     * @param InputInterface $input
123
     * @param OutputInterface $output
124
     * @param array $content
125
     * @param integer $numberOfTweets
126
     */
127 3
    protected function addAndDisplayTweets(InputInterface $input,
128
        OutputInterface $output, $content, $numberOfTweets)
129
    {
130 3
        $output->writeln('<comment>Number of tweets: '.$numberOfTweets.'</comment>');
131
        
132
        # Iterate through $content in order to add the oldest tweet first, 
133
        #  if there is an error the oldest tweet will still be saved
134
        #  and newer tweets can be saved next time the command is launched
135 3
        $tweets = array_reverse($content);
136
        
137 3
        $this->setProgressBar($output, $numberOfTweets);
138 3
        $this->setTable($input, $output);
139 3
        $this->iterateTweets($tweets);
140
        
141 3
        $this->progress->finish();
142 3
        $output->writeln('');
143
        
144 3
        if ($this->displayTable) {
145 2
            $this->table->render();
146 2
        }
147 3
    }
148
    
149
    /**
150
     * @param OutputInterface $output
151
     * @param integer $numberOfTweets
152
     */
153 3
    protected function setProgressBar(OutputInterface $output,
154
        $numberOfTweets)
155
    {
156 3
        $this->progress = new ProgressBar($output, $numberOfTweets);
157 3
        $this->progress->setBarCharacter('<comment>=</comment>');
158 3
        $this->progress->start();
159 3
    }
160
    
161
    /**
162
     * @param InputInterface $input
163
     * @param OutputInterface $output
164
     */
165 3
    protected function setTable(InputInterface $input,
166
        OutputInterface $output)
167
    {
168 3
        $this->displayTable = $input->getOption('table');
169
        
170
        # Display
171 3
        if ($this->displayTable)
172 3
        {
173 2
            $this->table = new Table($output);
174 2
            $this->table
175 2
                ->setHeaders(array('Datetime', 'Text excerpt', 'Name'))
176
            ;
177 2
        }
178 3
    }
179
    
180
    /**
181
     * @param array $tweets
182
     */
183 3
    protected function iterateTweets($tweets)
184
    {
185 3
        $persistTweet = new PersistTweet($this->em, $this->displayTable,
186 3
            $this->table);
187
        
188 3
        foreach ($tweets as $tweetTmp)
189
        {
190 3
            $persistTweet->addTweet($tweetTmp, true);
191
            
192 3
            $this->progress->advance();
193 3
        }
194 3
    }
195
}
196