Completed
Push — 8.x-2.x ( c6d484...0f1fa4 )
by Frédéric G.
02:32
created

TopController::mongodb_watchdog_page_top()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 74
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 50
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 74
rs 8.4878

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Drupal\mongodb_watchdog\Controller;
4
5
/**
6
 * Class TopController implements the Top403/Top404 controllers.
7
 */
8
class TopController {
9
  public function top403() {
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
10
    return ['#markup' => "403"];
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal 403 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
11
  }
12
13
  public function top404() {
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
14
    return ['#markup' => "404"];
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal 404 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
15
  }
16
  /**
17
   * Page callback for "admin/reports/[access-denied|page-not-found]".
18
   *
19
   * @return array
0 ignored issues
show
introduced by
Return comment must be on the next line
Loading history...
20
   */
21
  function mongodb_watchdog_page_top($type) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
introduced by
Method name "TopController::mongodb_watchdog_page_top" is not in lowerCamel format
Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for mongodb_watchdog_page_top.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
22
    $ret = array();
23
    $type_param = array('%type' => $type);
24
    $limit = 50;
25
26
    // Safety net
0 ignored issues
show
introduced by
Inline comments must end in full-stops, exclamation marks, or question marks
Loading history...
27
    $types = array(
28
      'page not found',
29
      'access denied',
30
    );
31
    if (!in_array($type, $types)) {
32
      drupal_set_message(t('Unknown top report type: %type', $type_param), 'error');
33
      watchdog('mongodb_watchdog', 'Unknown top report type: %type', $type_param, WATCHDOG_WARNING);
34
      $ret = '';
35
      return $ret;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $ret; (string) is incompatible with the return type documented by Drupal\mongodb_watchdog\...ngodb_watchdog_page_top 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...
36
    }
37
38
    // Find _id for the error type.
39
    $watchdog = mongodb_collection(variable_get('mongodb_watchdog', 'watchdog'));
40
    $template = $watchdog->findOne(array('type' => $type), array('_id'));
0 ignored issues
show
Bug introduced by
The method findOne does only exist in MongoCollection, but not in MongoDebugCollection and MongoDummy.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
41
42
    // findOne() will return NULL if no row is found
0 ignored issues
show
introduced by
Inline comments must end in full-stops, exclamation marks, or question marks
Loading history...
43
    if (empty($template)) {
44
      $ret['empty'] = array(
45
        '#markup' => t('No "%type" message found', $type_param),
46
        '#prefix' => '<div class="mongodb-watchdog-message">',
47
        '#suffix' => '</div>',
48
      );
49
      $ret = drupal_render($ret);
50
      return $ret;
51
    }
52
53
    // Find occurrences of error type.
54
    $key = $template['_id'];
55
    $event_collection = mongodb_collection('watchdog_event_' . $key);
56
    $reduce = <<<EOT
57
function (doc, accumulator) {
58
  accumulator.count++;
59
}
60
EOT;
61
62
    $counts = $event_collection->group(
0 ignored issues
show
Bug introduced by
The method group does only exist in MongoCollection, but not in MongoDebugCollection and MongoDummy.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
63
      array('variables.@param' => 1),
64
      array('count' => array()),
65
      $reduce
66
    );
67
    if (!$counts['ok']) {
68
      drupal_set_message(t('No "%type" occurrence found', $type_param), 'error');
69
      $ret = '';
70
      return $ret;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $ret; (string) is incompatible with the return type documented by Drupal\mongodb_watchdog\...ngodb_watchdog_page_top 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...
71
    }
72
    $counts = $counts['retval'];
73
    usort($counts, '_mongodb_watchdog_sort_top');
74
    $counts = array_slice($counts, 0, $limit);
75
76
    $header = array(
77
      t('#'),
78
      t('Paths'),
79
    );
80
    $rows = array();
81
    foreach ($counts as $count) {
82
      $rows[] = array(
83
        $count['variables.@param'],
84
        $count['count'],
85
      );
86
    }
87
88
    $ret = array(
89
      '#theme' => 'table',
90
      '#header' => $header,
91
      '#rows' => $rows,
92
    );
93
    return $ret;
94
  }
95
96
  /**
97
   * usort() helper function to sort top entries returned from a group query.
0 ignored issues
show
introduced by
Doc comment short description must start with a capital letter
Loading history...
98
   *
99
   * @param array $x
0 ignored issues
show
introduced by
Missing parameter comment
Loading history...
100
   * @param array $y
0 ignored issues
show
introduced by
Missing parameter comment
Loading history...
101
   *
102
   * @return boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
introduced by
Expected "bool" but found "boolean" for function return type
Loading history...
introduced by
Return comment must be on the next line
Loading history...
103
   */
104
  function _mongodb_watchdog_sort_top($x, $y) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility introduced by
Avoid variables with short names like $x. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Comprehensibility introduced by
Avoid variables with short names like $y. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
introduced by
Type hint "array" missing for $x
Loading history...
introduced by
Type hint "array" missing for $y
Loading history...
introduced by
Method name "TopController::_mongodb_watchdog_sort_top" is not in lowerCamel format
Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for _mongodb_watchdog_sort_top.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
105
    $cx = $x['count'];
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cx. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
106
    $cy = $y['count'];
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cy. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
107
    return $cy - $cx;
108
  }
109
110
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
111