FBCLoadAdditionalContentTrait   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 289
Duplicated Lines 7.61 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 1
dl 22
loc 289
ccs 0
cts 161
cp 0
rs 8.72
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
F loadAdditionalContent() 0 124 24
B findNextAndPrevious() 22 46 11
A orderToc() 0 27 4
B limitToc() 0 45 7

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FBCLoadAdditionalContentTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FBCLoadAdditionalContentTrait, and based on these observations, apply Extract Interface, too.

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 FBCLoadAdditionalContentTrait
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 Mikael Roos
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->get("textfilter")->createToc($content);
0 ignored issues
show
Bug introduced by Mikael Roos
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 Mikael Roos
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
                    case "next-previous":
42
                        $baseRoute = dirname($routeIndex);
43
                        $this->orderToc($baseRoute, $meta);
0 ignored issues
show
Documentation introduced by Mikael Roos
$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...
44
                        list($next, $previous) = $this->findNextAndPrevious($routeIndex);
45
                        $views[$id]["data"]["next"] = $next;
46
                        $views[$id]["data"]["previous"] = $previous;
47
                        break;
48
49
                    case "single": // OBSOLETE
50
                    case "content":
51
                        $route = $this->getActiveRoute($meta["route"], $routeIndex);
0 ignored issues
show
Bug introduced by Mikael Roos
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...
52
53
                        // Load and parse route as view. Load meta view
54
                        // if any.
55
                        // Current view details preceds the loaded once.
56
                        $view = $this->loadAndParseRoute($route);
0 ignored issues
show
Bug introduced by Mikael Roos
It seems like loadAndParseRoute() 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...
57
                        $views[$id] = array_merge_recursive_distinct($view, $views[$id]);
58
                        break;
59
60
                    case "columns":
61
                        // Each column is an own view set with details
62
                        // Process as meta view and load additional content
63
                        $template = isset($meta["template"])
64
                            ? $meta["template"]
65
                            : null;
66
                        $columns = $meta["columns"];
67
                        foreach ($columns as $key => $view) {
68
                            $views2 = [ "main" => $view ];
69
                            $this->loadAdditionalContent($views2, $route, $routeIndex);
70
                            $columns[$key] = $views2["main"];
71
                            
72
                            if ($template) {
73
                                $columns[$key]["template"] = $template;
74
                            }
75
                        }
76
                        $views[$id]["data"]["columns"] = $columns;
77
                        break;
78
79
                    case "toc-sort":
80
                        $baseRoute = dirname($routeIndex);
81
                        $this->orderToc($baseRoute, $meta);
0 ignored issues
show
Documentation introduced by Mikael Roos
$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...
82
                        break;
83
84
                    case "toc":
85
                        $baseRoute = dirname($routeIndex);
86
87
                        // Include support for ordering
88
                        if (isset($meta["orderby"])
89
                            || isset($meta["orderorder"])) {
90
                            $this->orderToc($baseRoute, $meta);
0 ignored issues
show
Documentation introduced by Mikael Roos
$meta is of type array<string,?,{"type":"?","orderby":"?"}>, 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...
91
                        }
92
93
                        // Same as toc-route
94
                        $toc = $this->meta[$baseRoute]["__toc__"];
0 ignored issues
show
Bug introduced by Mikael Roos
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...
95
                        $this->limitToc($toc, $meta);
96
                        $views[$id]["data"]["toc"] = $toc;
97
                        $views[$id]["data"]["meta"] = $meta;
98
                        break;
99
100
                    case "toc-route":
101
                        // Get the toc for a specific route
102
                        $route = $this->getActiveRoute($meta["route"], $routeIndex);
0 ignored issues
show
Bug introduced by Mikael Roos
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...
103
                        $routeIndex2 = $this->mapRoute2IndexKey($route);
0 ignored issues
show
Bug introduced by Mikael Roos
It seems like mapRoute2IndexKey() 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...
104
                        $baseRoute = dirname($routeIndex2);
105
106
                        // Include support for ordering
107
                        if (isset($meta["orderby"])
108
                            || isset($meta["orderorder"])) {
109
                            $this->orderToc($baseRoute, $meta);
0 ignored issues
show
Documentation introduced by Mikael Roos
$meta is of type array<string,?,{"type":"?","orderby":"?"}>, 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...
110
                        }
111
112
                        // Same as toc
113
                        $toc = $this->meta[$baseRoute]["__toc__"];
114
                        $this->limitToc($toc, $meta, $baseRoute);
115
                        $views[$id]["data"]["toc"] = $toc;
116
                        $views[$id]["data"]["meta"] = $meta;
117
                        break;
118
119
                    case "book-toc":
120
                        $toc = $this->meta[$baseRoute]["__toc__"];
0 ignored issues
show
Bug introduced by Mikael Roos
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...
121
                        $views[$id]["data"]["toc"] = $toc;
122
                        break;
123
124
                    case "author":
125
                        if (isset($views["main"]["data"]["author"])) {
126
                            $views[$id]["data"]["author"] = $this->loadAuthorDetails($views["main"]["data"]["author"]);
0 ignored issues
show
Bug introduced by Mikael Roos
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...
127
                        }
128
                        break;
129
130
                    case "copy":
131
                        $viewToCopy = $views[$id]["data"]["meta"]["view"];
132
                        $views[$id]["data"] = array_merge_recursive_distinct(
133
                            $views[$viewToCopy]["data"],
134
                            $views[$id]["data"]
135
                        );
136
                        break;
137
138
                    default:
139
                        $msg = t("Unsupported data/meta/type '!TYPE' for additional content.", [
140
                            "!TYPE" => $meta["type"]
141
                        ]);
142
                        throw new Exception($msg);
143
                }
144
            }
145
        }
146
    }
147
148
149
150
    /**
151
     * Find next and previous links of current content.
152
     *
153
     * @param string $routeIndex target route to find next and previous for.
154
     *
155
     * @return array with next and previous if found.
156
     */
157
    private function findNextAndPrevious($routeIndex)
158
    {
159
        $key = dirname($routeIndex);
160
        if (!isset($this->meta[$key]["__toc__"])) {
161
            return [null, null];
162
        }
163
164
        $toc = $this->meta[$key]["__toc__"];
165
        if (!isset($toc[$routeIndex])) {
166
            return [null, null];
167
        }
168
169
        $index2Key = array_keys($toc);
170
        $keys = array_flip($index2Key);
171
        $values = array_values($toc);
172
        $count = count($keys);
173
174
        $current = $keys[$routeIndex];
175
        $previous = null;
176 View Code Duplication
        for ($i = $current - 1; $i >= 0; $i--) {
0 ignored issues
show
Duplication introduced by Mikael Roos
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...
177
            $isSectionHeader = $values[$i]["sectionHeader"];
178
            $isLinkable = $values[$i]["linkable"]; // ?? null;
179
            $isInternal = $values[$i]["internal"];
180
            if (($isSectionHeader && !$isLinkable) || $isInternal) {
181
                continue;
182
            }
183
            $previous = $values[$i];
184
            $previous["route"] = $index2Key[$i];
185
            break;
186
        }
187
        
188
        $next = null;
189 View Code Duplication
        for ($i = $current + 1; $i < $count; $i++) {
0 ignored issues
show
Duplication introduced by Mikael Roos
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...
190
            $isSectionHeader = $values[$i]["sectionHeader"];
191
            $isLinkable = $values[$i]["linkable"]; // ?? null;
192
            $isInternal = $values[$i]["internal"];
193
            if (($isSectionHeader && !$isLinkable) || $isInternal) {
194
                continue;
195
            }
196
            $next = $values[$i];
197
            $next["route"] = $index2Key[$i];
198
            break;
199
        }
200
201
        return [$next, $previous];
202
    }
203
204
205
206
    /**
207
     * Order toc items.
208
     *
209
     * @param string $baseRoute route to use to find __toc__.
210
     * @param string $meta on how to order toc.
211
     *
212
     * @return void.
0 ignored issues
show
Documentation introduced by Mikael Roos
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...
213
     */
214
    private function orderToc($baseRoute, $meta)
215
    {
216
        $defaults = [
217
            "orderby" => "section",
218
            "orderorder" => "asc",
219
        ];
220
        $options = array_merge($defaults, $meta);
221
        $orderby = $options["orderby"];
222
        $order   = $options["orderorder"];
223
        $toc = $this->meta[$baseRoute]["__toc__"];
224
225
        uksort($toc, function ($a, $b) use ($toc, $orderby, $order) {
226
                $a = $toc[$a][$orderby];
227
                $b = $toc[$b][$orderby];
228
229
                $asc = $order == "asc" ? 1 : -1;
230
                
231
            if ($a == $b) {
232
                return 0;
233
            } elseif ($a > $b) {
234
                return $asc;
235
            }
236
                return -$asc;
237
        });
238
239
        $this->meta[$baseRoute]["__toc__"] = $toc;
240
    }
241
242
243
    /**
244
     * Limit and paginate toc items.
245
     *
246
     * @param string &$toc      array with current toc.
247
     * @param string &$meta     on how to order and limit toc.
248
     * @param string $baseRoute prepend to next & previous urls.
249
     *
250
     * @return void.
0 ignored issues
show
Documentation introduced by Mikael Roos
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...
251
     */
252
    private function limitToc(&$toc, &$meta, $baseRoute = null)
253
    {
254
        $defaults = [
255
            "items" => 7,
256
            "offset" => 0,
257
        ];
258
        $options = array_merge($defaults, $meta);
259
260
        // Check if pagination is currently used
261
        if ($this->currentPage) {
262
            $options["offset"] = ($this->currentPage - 1) * $options["items"];
0 ignored issues
show
Bug introduced by Mikael Roos
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...
263
        }
264
265
        $meta["totalItems"] = count($toc);
266
        $meta["currentPage"] = (int) floor($options["offset"] / $options["items"]) + 1;
267
        $meta["totalPages"] = (int) floor($meta["totalItems"] / $options["items"] + 1);
268
269
        // Next and previous page
270
        $pagination = $this->config["pagination"];
0 ignored issues
show
Bug introduced by Mikael Roos
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...
271
        $meta["nextPageUrl"] = null;
272
        $meta["previousPageUrl"] = null;
273
        $baseRoute = isset($baseRoute)
274
            ? $baseRoute
275
            : $this->baseRoute;
0 ignored issues
show
Bug introduced by Mikael Roos
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...
276
277
        if ($meta["currentPage"] > 1 && $meta["totalPages"] > 1) {
278
            $previousPage = $meta["currentPage"] - 1;
279
            $previous = "";
280
            if ($previousPage != 1) {
281
                $previous = "$pagination/$previousPage";
282
            }
283
            $meta["previousPageUrl"] = "$baseRoute/$previous";
284
        }
285
286
        if ($meta["currentPage"] < $meta["totalPages"]) {
287
            $nextPage = $meta["currentPage"] + 1;
288
            $meta["nextPageUrl"] = "$baseRoute/$pagination/$nextPage";
289
        }
290
291
292
        // Only use slice of toc
293
        $startSlice = ($meta["currentPage"] - 1) * $options["items"];
294
        $toc = array_slice($toc, $startSlice, $options["items"]);
295
        $meta["displayedItems"] = count($toc);
296
    }
297
}
298