Completed
Push — master ( c9a850...5b89fe )
by Mikael
02:53
created

TFBCLoadAdditionalContent::limitToc()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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