Completed
Push — master ( a99fa5...b5a796 )
by Mikael
02:43
created

TFBCLoadAdditionalContent::loadAdditionalContent()   D

Complexity

Conditions 18
Paths 35

Size

Total Lines 82
Code Lines 60

Duplication

Lines 13
Ratio 15.85 %

Importance

Changes 4
Bugs 0 Features 3
Metric Value
c 4
b 0
f 3
dl 13
loc 82
rs 4.9297
cc 18
eloc 60
nc 35
nop 3

How to fix   Long Method    Complexity   

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 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
                        // Support relative routes
51
                        $route = $meta["route"];
52
                        if (substr_compare($route, "./", 0, 2) === 0) {
53
                            $route = dirname($routeIndex) . "/" . substr($route, 2);
54
                        }
55
56
                        // Get the content
57
                        $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...
58
                        $views[$id]["data"] = array_merge_recursive_distinct($views[$id]["data"], $data);
59
                        break;
60
61
                    case "columns":
62
                        $columns = $meta["columns"];
63
                        foreach ($columns as $key => $value) {
64
                            $data = $this->getDataForAdditionalRoute($value["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...
65
                            $columns[$key] = $data;
66
                        }
67
                        $views[$id]["data"]["columns"] = $columns;
68
                        break;
69
70
                    case "toc-sort":
71
                        $baseRoute = dirname($routeIndex);
72
                        $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...
73
                        break;
74
75 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...
76
                        $baseRoute = dirname($routeIndex);
77
                        $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...
78
                        $this->limitToc($toc, $meta);
79
                        $views[$id]["data"]["toc"] = $toc;
80
                        $views[$id]["data"]["meta"] = $meta;
81
                        break;
82
83
                    case "book-toc":
84
                        $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...
85
                        $views[$id]["data"]["toc"] = $toc;
86
                        break;
87
88
                    case "author":
89
                        if (isset($views["main"]["data"]["author"])) {
90
                            $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...
91
                        }
92
                        break;
93
94
                    case "copy":
95
                        $viewToCopy = $views[$id]["data"]["meta"]["view"];
96
                        $views[$id]["data"] = $views[$viewToCopy]["data"];
97
                        break;
98
99
                    default:
100
                        throw new Exception(t("Unsupported data/meta/type '!TYPE' for additional content.", ["!TYPE" => $meta["type"]]));
101
                }
102
            }
103
        }
104
    }
105
106
107
108
    /**
109
     * Find next and previous links of current content.
110
     *
111
     * @param string $routeIndex target route to find next and previous for.
112
     *
113
     * @return array with next and previous if found.
114
     */
115
    private function findNextAndPrevious($routeIndex)
116
    {
117
        $key = dirname($routeIndex);
118
        if (!isset($this->meta[$key]["__toc__"])) {
119
            return [null, null];
120
        }
121
122
        $toc = $this->meta[$key]["__toc__"];
123
        if (!isset($toc[$routeIndex])) {
124
            return [null, null];
125
        }
126
127
        $index2Key = array_keys($toc);
128
        $keys = array_flip($index2Key);
129
        $values = array_values($toc);
130
        $count = count($keys);
131
132
        $current = $keys[$routeIndex];
133
        $previous = null;
134 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...
135
            $isSectionHeader = $values[$i]["sectionHeader"];
136
            $isInternal = $values[$i]["internal"];
137
            if ($isSectionHeader || $isInternal) {
138
                continue;
139
            }
140
            $previous = $values[$i];
141
            $previous["route"] = $index2Key[$i];
142
            break;
143
        }
144
        
145
        $next = null;
146 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...
147
            $isSectionHeader = $values[$i]["sectionHeader"];
148
            $isInternal = $values[$i]["internal"];
149
            if ($isSectionHeader || $isInternal) {
150
                continue;
151
            }
152
            $next = $values[$i];
153
            $next["route"] = $index2Key[$i];
154
            break;
155
        }
156
157
        return [$next, $previous];
158
    }
159
160
161
162
    /**
163
     * Order toc items.
164
     *
165
     * @param string $baseRoute route to use to find __toc__.
166
     * @param string $meta on how to order toc.
167
     *
168
     * @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...
169
     */
170
    private function orderToc($baseRoute, $meta)
171
    {
172
        $defaults = [
173
            "orderby" => "section",
174
            "orderorder" => "asc",
175
        ];
176
        $options = array_merge($defaults, $meta);
177
        $orderby = $options["orderby"];
178
        $order   = $options["orderorder"];
179
        $toc = $this->meta[$baseRoute]["__toc__"];
180
        
181
        uksort($toc, function ($a, $b) use ($toc, $orderby, $order) {
182
                $a = $toc[$a][$orderby];
183
                $b = $toc[$b][$orderby];
184
185
                $asc = $order == "asc" ? 1 : -1;
186
                
187
                if ($a == $b) {
188
                    return 0;
189
                } elseif ($a > $b) {
190
                    return $asc;
191
                }
192
                return -$asc;
193
        });
194
        
195
        $this->meta[$baseRoute]["__toc__"] = $toc;
196
    }
197
198
199
    /**
200
     * Limit and paginate toc items.
201
     *
202
     * @param string &$toc  array with current toc.
203
     * @param string &$meta on how to order and limit toc.
204
     *
205
     * @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...
206
     */
207
    private function limitToc(&$toc, &$meta)
208
    {
209
        $defaults = [
210
            "items" => 7,
211
            "offset" => 0,
212
        ];
213
        $options = array_merge($defaults, $meta);
214
215
        // Check if pagination is currently used
216
        if ($this->currentPage) {
217
            $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...
218
        }
219
220
        $meta["totalItems"] = count($toc);
221
        $meta["currentPage"] = (int) floor($options["offset"] / $options["items"]) + 1;
222
        $meta["totalPages"] = (int) floor($meta["totalItems"] / $options["items"] + 1);
223
224
        // Next and previous page
225
        $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...
226
        $meta["nextPageUrl"] = null;
227
        $meta["previousPageUrl"] = null;
228
        
229
        if ($meta["currentPage"] > 1 && $meta["totalPages"] > 1) {
230
            $previousPage = $meta["currentPage"] - 1;
231
            $previous = "";
232
            if ($previousPage != 1) {
233
                $previous = "/$pagination/$previousPage";
234
            }
235
            $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...
236
        }
237
238
        if ($meta["currentPage"] < $meta["totalPages"]) {
239
            $nextPage = $meta["currentPage"] + 1;
240
            $meta["nextPageUrl"] = $this->baseRoute . "/$pagination/$nextPage";
241
        }
242
243
244
        // Only use slice of toc
245
        $startSlice = ($meta["currentPage"] - 1) * $options["items"];
246
        $toc = array_slice($toc, $startSlice, $options["items"]);
247
        $meta["displayedItems"] = count($toc);
248
    }
249
}
250