Completed
Push — master ( b5a796...c9a850 )
by Mikael
02:54
created

TFBCLoadAdditionalContent   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 238
Duplicated Lines 13.87 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 6
Bugs 0 Features 3
Metric Value
wmc 36
c 6
b 0
f 3
lcom 1
cbo 1
dl 33
loc 238
rs 8.8

4 Methods

Rating   Name   Duplication   Size   Complexity  
C loadAdditionalContent() 13 79 17
D findNextAndPrevious() 20 44 9
B orderToc() 0 27 4
B limitToc() 0 42 6

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
namespace Anax\Content;
4
5
/**
6
 * File Based Content, code for loading additional content into view through 
7
 * data["meta"].
8
 */
9
trait TFBCLoadAdditionalContent
10
{
11
    /**
12
     * Load extra info into views based of meta information provided in each
13
     * view.
14
     *
15
     * @param array  &$views     with all views.
16
     * @param string $route      current route
17
     * @param string $routeIndex route with appended /index
18
     *
19
     * @throws NotFoundException when mapping can not be done.
20
     *
21
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
22
     */
23
    private function loadAdditionalContent(&$views, $route, $routeIndex)
24
    {
25
        foreach ($views as $id => $view) {
26
            $meta = isset($view["data"]["meta"])
27
                ? $view["data"]["meta"]
28
                : null;
29
30
            if (is_array($meta)) {
31
                switch ($meta["type"]) {
32
                    case "article-toc":
33
                        $content = $views["main"]["data"]["content"];
34
                        $views[$id]["data"]["articleToc"] = $this->di->textFilter->createToc($content);
0 ignored issues
show
Bug introduced by
The property di does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
35
                        break;
36
37
                    case "breadcrumb":
38
                        $views[$id]["data"]["breadcrumb"] = $this->createBreadcrumb($route);
0 ignored issues
show
Bug introduced by
It seems like createBreadcrumb() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
39
                        break;
40
41 View Code Duplication
                    case "next-previous":
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...
42
                        $baseRoute = dirname($routeIndex);
43
                        list($next, $previous) = $this->findNextAndPrevious($routeIndex);
44
                        $views[$id]["data"]["next"] = $next;
45
                        $views[$id]["data"]["previous"] = $previous;
46
                        break;
47
48
                    case "single": // OBSOLETE
49
                    case "content":
50
                        $route = $this->getActiveRoute($meta["route"], $routeIndex);
0 ignored issues
show
Bug introduced by
It seems like getActiveRoute() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
51
52
                        // Get the content
53
                        $data = $this->getDataForAdditionalRoute($route);
0 ignored issues
show
Bug introduced by
It seems like getDataForAdditionalRoute() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
54
                        $views[$id]["data"] = array_merge_recursive_distinct($views[$id]["data"], $data);
55
                        break;
56
57
                    case "columns":
58
                        $columns = $meta["columns"];
59
                        foreach ($columns as $key => $value) {
60
                            $route = $this->getActiveRoute($value["route"], $routeIndex);
0 ignored issues
show
Bug introduced by
It seems like getActiveRoute() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
61
                            $data = $this->getDataForAdditionalRoute($route);
0 ignored issues
show
Bug introduced by
It seems like getDataForAdditionalRoute() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
62
                            $columns[$key] = $data;
63
                        }
64
                        $views[$id]["data"]["columns"] = $columns;
65
                        break;
66
67
                    case "toc-sort":
68
                        $baseRoute = dirname($routeIndex);
69
                        $this->orderToc($baseRoute, $meta);
0 ignored issues
show
Documentation introduced by
$meta is of type array<string,?,{"type":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
70
                        break;
71
72 View Code Duplication
                    case "toc":
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...
73
                        $baseRoute = dirname($routeIndex);
74
                        $toc = $this->meta[$baseRoute]["__toc__"];
0 ignored issues
show
Bug introduced by
The property meta does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
75
                        $this->limitToc($toc, $meta);
76
                        $views[$id]["data"]["toc"] = $toc;
77
                        $views[$id]["data"]["meta"] = $meta;
78
                        break;
79
80
                    case "book-toc":
81
                        $toc = $this->meta[$baseRoute]["__toc__"];
0 ignored issues
show
Bug introduced by
The variable $baseRoute does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
82
                        $views[$id]["data"]["toc"] = $toc;
83
                        break;
84
85
                    case "author":
86
                        if (isset($views["main"]["data"]["author"])) {
87
                            $views[$id]["data"]["author"] = $this->loadAuthorDetails($views["main"]["data"]["author"]);
0 ignored issues
show
Bug introduced by
It seems like loadAuthorDetails() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
88
                        }
89
                        break;
90
91
                    case "copy":
92
                        $viewToCopy = $views[$id]["data"]["meta"]["view"];
93
                        $views[$id]["data"] = $views[$viewToCopy]["data"];
94
                        break;
95
96
                    default:
97
                        throw new Exception(t("Unsupported data/meta/type '!TYPE' for additional content.", ["!TYPE" => $meta["type"]]));
98
                }
99
            }
100
        }
101
    }
102
103
104
105
    /**
106
     * Find next and previous links of current content.
107
     *
108
     * @param string $routeIndex target route to find next and previous for.
109
     *
110
     * @return array with next and previous if found.
111
     */
112
    private function findNextAndPrevious($routeIndex)
113
    {
114
        $key = dirname($routeIndex);
115
        if (!isset($this->meta[$key]["__toc__"])) {
116
            return [null, null];
117
        }
118
119
        $toc = $this->meta[$key]["__toc__"];
120
        if (!isset($toc[$routeIndex])) {
121
            return [null, null];
122
        }
123
124
        $index2Key = array_keys($toc);
125
        $keys = array_flip($index2Key);
126
        $values = array_values($toc);
127
        $count = count($keys);
128
129
        $current = $keys[$routeIndex];
130
        $previous = null;
131 View Code Duplication
        for ($i = $current - 1; $i >= 0; $i--) {
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...
132
            $isSectionHeader = $values[$i]["sectionHeader"];
133
            $isInternal = $values[$i]["internal"];
134
            if ($isSectionHeader || $isInternal) {
135
                continue;
136
            }
137
            $previous = $values[$i];
138
            $previous["route"] = $index2Key[$i];
139
            break;
140
        }
141
        
142
        $next = null;
143 View Code Duplication
        for ($i = $current + 1; $i < $count; $i++) {
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...
144
            $isSectionHeader = $values[$i]["sectionHeader"];
145
            $isInternal = $values[$i]["internal"];
146
            if ($isSectionHeader || $isInternal) {
147
                continue;
148
            }
149
            $next = $values[$i];
150
            $next["route"] = $index2Key[$i];
151
            break;
152
        }
153
154
        return [$next, $previous];
155
    }
156
157
158
159
    /**
160
     * Order toc items.
161
     *
162
     * @param string $baseRoute route to use to find __toc__.
163
     * @param string $meta on how to order toc.
164
     *
165
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
166
     */
167
    private function orderToc($baseRoute, $meta)
168
    {
169
        $defaults = [
170
            "orderby" => "section",
171
            "orderorder" => "asc",
172
        ];
173
        $options = array_merge($defaults, $meta);
174
        $orderby = $options["orderby"];
175
        $order   = $options["orderorder"];
176
        $toc = $this->meta[$baseRoute]["__toc__"];
177
        
178
        uksort($toc, function ($a, $b) use ($toc, $orderby, $order) {
179
                $a = $toc[$a][$orderby];
180
                $b = $toc[$b][$orderby];
181
182
                $asc = $order == "asc" ? 1 : -1;
183
                
184
                if ($a == $b) {
185
                    return 0;
186
                } elseif ($a > $b) {
187
                    return $asc;
188
                }
189
                return -$asc;
190
        });
191
        
192
        $this->meta[$baseRoute]["__toc__"] = $toc;
193
    }
194
195
196
    /**
197
     * Limit and paginate toc items.
198
     *
199
     * @param string &$toc  array with current toc.
200
     * @param string &$meta on how to order and limit toc.
201
     *
202
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
203
     */
204
    private function limitToc(&$toc, &$meta)
205
    {
206
        $defaults = [
207
            "items" => 7,
208
            "offset" => 0,
209
        ];
210
        $options = array_merge($defaults, $meta);
211
212
        // Check if pagination is currently used
213
        if ($this->currentPage) {
214
            $options["offset"] = ($this->currentPage - 1) * $options["items"];
0 ignored issues
show
Bug introduced by
The property currentPage does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
215
        }
216
217
        $meta["totalItems"] = count($toc);
218
        $meta["currentPage"] = (int) floor($options["offset"] / $options["items"]) + 1;
219
        $meta["totalPages"] = (int) floor($meta["totalItems"] / $options["items"] + 1);
220
221
        // Next and previous page
222
        $pagination = $this->config["pagination"];
0 ignored issues
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
223
        $meta["nextPageUrl"] = null;
224
        $meta["previousPageUrl"] = null;
225
        
226
        if ($meta["currentPage"] > 1 && $meta["totalPages"] > 1) {
227
            $previousPage = $meta["currentPage"] - 1;
228
            $previous = "";
229
            if ($previousPage != 1) {
230
                $previous = "/$pagination/$previousPage";
231
            }
232
            $meta["previousPageUrl"] = $this->baseRoute . $previous;
0 ignored issues
show
Bug introduced by
The property baseRoute does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
233
        }
234
235
        if ($meta["currentPage"] < $meta["totalPages"]) {
236
            $nextPage = $meta["currentPage"] + 1;
237
            $meta["nextPageUrl"] = $this->baseRoute . "/$pagination/$nextPage";
238
        }
239
240
241
        // Only use slice of toc
242
        $startSlice = ($meta["currentPage"] - 1) * $options["items"];
243
        $toc = array_slice($toc, $startSlice, $options["items"]);
244
        $meta["displayedItems"] = count($toc);
245
    }
246
}
247