Completed
Push — master ( a49358...a99fa5 )
by Mikael
03:35
created

TFBCLoadAdditionalContent::orderToc()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
rs 8.5806
cc 4
eloc 18
nc 1
nop 2
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);
0 ignored issues
show
Unused Code introduced by
$baseRoute is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

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