RefreshCommand   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 133
Duplicated Lines 9.02 %

Coupling/Cohesion

Components 2
Dependencies 5

Importance

Changes 0
Metric Value
wmc 14
lcom 2
cbo 5
dl 12
loc 133
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 34 1
A scrape() 0 15 2
B execute() 12 47 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * @file RefreshCommand.php
5
 * @brief This file contains the RefreshCommand class.
6
 * @details
7
 * @author Filippo F. Fadda
8
 */
9
10
11
namespace Facebook\ObjectDebugger\Command;
12
13
14
use Symfony\Component\Console\Exception\InvalidOptionException;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
19
use Facebook\Facebook;
20
21
22
/**
23
 * @brief Scrapes pubs' information from WhatPub.
24
 * @nosubgrouping
25
 */
26
class RefreshCommand extends AbstractCommand {
27
28
  /**
29
   * @var Facebook $fb
30
   */
31
  private $fb;
32
33
  /**
34
   * @var InputInterface $input
35
   */
36
  private $input;
37
38
  /**
39
   * @var OutputInterface $output
40
   */
41
  private $output;
42
43
44
  /**
45
   * @brief Fetches new scrape information and update the Facebook cache.
46
   */
47
  protected function configure() {
48
    $this->setName("refresh");
49
    $this->setDescription("Fetches new scrape information and update the Facebook cache");
50
51
    $this->addOption("file",
52
      'i',
53
      InputOption::VALUE_REQUIRED,
54
      "Text file which contains a list of URLs, one per row");
55
56
    $this->addOption("url",
57
      'u',
58
      InputOption::VALUE_REQUIRED,
59
      "URL of a single page to scrape");
60
61
    $this->addOption("id",
62
      'd',
63
      InputOption::VALUE_REQUIRED,
64
      "Facebook id");
65
66
    $this->addOption("secret",
67
      's',
68
      InputOption::VALUE_REQUIRED,
69
      "Facebook secret");
70
71
    $this->addOption("token",
72
      't',
73
      InputOption::VALUE_REQUIRED,
74
      "Facebook App|User access token");
75
76
    $this->addOption("encode",
77
      'e',
78
      InputOption::VALUE_NONE,
79
      "Encode the provided URL");
80
  }
81
82
83
  /**
84
   * @brief Scrapes the information.
85
   * @param string $url The page URL to scrape.
86
   */
87
  private function scrape($url) {
88
    $this->output->write($url);
89
90
    if ($this->input->getOption('encode'))
91
      $url = urlencode($url);
92
93
    $params = [
94
      'id' => $url,
95
      'scrape' => 'true'
96
    ];
97
98
    $response = $this->fb->post('/', $params);
0 ignored issues
show
Unused Code introduced by
$response 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...
99
100
    $this->output->writeln(' => done');
101
  }
102
103
104
  /**
105
   * @brief Executes the command.
106
   * @param InputInterface $input The input interface
107
   * @param OutputInterface $output The output interface
108
   * @return string
109
   */
110
  protected function execute(InputInterface $input, OutputInterface $output) {
111
    $this->input = $input;
112
    $this->output = $output;
113
114
    $config = $this->getApplication()->getConfig();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getConfig() does only exist in the following sub-classes of Symfony\Component\Console\Application: Facebook\ObjectDebugger\Console. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
115
116
    if ($input->getOption('id'))
117
      $appId = $input->getOption('id');
118
    elseif (array_key_exists('appId', $config))
119
      $appId = $config['appId'];
120
    else
121
      throw new InvalidOptionException('Facebook Open Graph requires an App ID.');
122
123 View Code Duplication
    if ($input->getOption('secret'))
0 ignored issues
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...
124
      $appSecret = $input->getOption('secret');
125
    elseif (array_key_exists('appSecret', $config))
126
      $appSecret = $config['appSecret'];
127
    else
128
      throw new InvalidOptionException('Facebook Open Graph requires an App Secret.');
129
130 View Code Duplication
    if ($input->getOption('token'))
0 ignored issues
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...
131
      $accessToken = $input->getOption('token');
132
    elseif (array_key_exists('appAccessToken', $config))
133
      $accessToken = $config['appAccessToken'];
134
    else
135
      throw new InvalidOptionException('Facebook Open Graph requires an App|User Access Token.');
136
137
    $this->fb = new Facebook([
138
      'app_id' => $appId,
139
      'app_secret' => $appSecret,
140
      'default_access_token' => $accessToken,
141
      'default_graph_version' => 'v2.8',
142
    ]);
143
144
    if ($url = $input->getOption('url')) {
145
      $this->scrape($url);
146
    }
147
    elseif ($fileName = $input->getOption('file')) {
148
      $urls = file($fileName, FILE_IGNORE_NEW_LINES);
149
150
      if ($urls === FALSE)
151
        throw new \RuntimeException('Cannot open the file.');
152
153
      foreach ($urls as $url)
154
        $this->scrape($url);
155
    }
156
  }
157
158
}