Completed
Push — master ( b28ef5...58dbbf )
by Mikael
02:32
created

TFBCLoadAdditionalContent::loadAdditionalContent()   C

Complexity

Conditions 14
Paths 25

Size

Total Lines 60
Code Lines 45

Duplication

Lines 13
Ratio 21.67 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 13
loc 60
rs 6.325
cc 14
eloc 45
nc 25
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);
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
                        $data = $this->getDataForAdditionalRoute($meta["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...
51
                        $views[$id]["data"] = array_merge_recursive_distinct($views[$id]["data"], $data);
52
                        break;
53
54
                    case "columns":
55
                        $columns = $meta["columns"];
56
                        foreach ($columns as $key => $value) {
57
                            $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...
58
                            $columns[$key] = $data;
59
                        }
60
                        $views[$id]["data"]["columns"] = $columns;
61
                        break;
62
63 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...
64
                        $baseRoute = dirname($routeIndex);
65
                        $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...
66
                        $this->orderAndlimitToc($toc, $meta);
67
                        $views[$id]["data"]["toc"] = $toc;
68
                        $views[$id]["data"]["meta"] = $meta;
69
                        break;
70
71
                    case "author":
72
                        if (isset($views["main"]["data"]["author"])) {
73
                            $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...
74
                        }
75
                        break;
76
77
                    default:
78
                        throw new Exception(t("Unsupported data/meta/type '!TYPE' for additional content.", ["!TYPE" => $meta["type"]]));
79
                }
80
            }
81
        }
82
    }
83
84
85
86
    /**
87
     * Find next and previous links of current content.
88
     *
89
     * @param string $routeIndex target route to find next and previous for.
90
     *
91
     * @return array with next and previous if found.
92
     */
93
    private function findNextAndPrevious($routeIndex)
94
    {
95
        $key = dirname($routeIndex);
96
        if (!isset($this->meta[$key]["__toc__"])) {
97
            return [null, null];
98
        }
99
100
        $toc = $this->meta[$key]["__toc__"];
101
        if (!isset($toc[$routeIndex])) {
102
            return [null, null];
103
        }
104
105
        $index2Key = array_keys($toc);
106
        $keys = array_flip($index2Key);
107
        $values = array_values($toc);
108
        $count = count($keys);
109
110
        $current = $keys[$routeIndex];
111
        $previous = null;
112 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...
113
            $isSectionHeader = $values[$i]["sectionHeader"];
114
            $isInternal = $values[$i]["internal"];
115
            if ($isSectionHeader || $isInternal) {
116
                continue;
117
            }
118
            $previous = $values[$i];
119
            $previous["route"] = $index2Key[$i];
120
            break;
121
        }
122
        
123
        $next = null;
124 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...
125
            $isSectionHeader = $values[$i]["sectionHeader"];
126
            $isInternal = $values[$i]["internal"];
127
            if ($isSectionHeader || $isInternal) {
128
                continue;
129
            }
130
            $next = $values[$i];
131
            $next["route"] = $index2Key[$i];
132
            break;
133
        }
134
135
        return [$next, $previous];
136
    }
137
138
139
140
    /**
141
     * Order and limit toc items.
142
     *
143
     * @param string &$toc  array with current toc.
144
     * @param string &$meta on how to order and limit toc.
145
     *
146
     * @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...
147
     */
148
    private function orderAndlimitToc(&$toc, &$meta)
149
    {
150
        $defaults = [
151
            "items" => 7,
152
            "offset" => 0,
153
            "orderby" => "section",
154
            "orderorder" => "asc",
155
        ];
156
        $options = array_merge($defaults, $meta);
157
        $orderby = $options["orderby"];
158
        $order   = $options["orderorder"];
159
160
        $meta["totalItems"] = count($toc);
161
162
        // TODO support pagination by adding entries to $meta
163
164
        uksort($toc, function ($a, $b) use ($toc, $orderby, $order) {
165
            $a = $toc[$a][$orderby];
166
            $b = $toc[$b][$orderby];
167
168
            if ($order == "asc") {
169
                return strcmp($a, $b);
170
            }
171
            return strcmp($b, $a);
172
        });
173
174
        $toc = array_slice($toc, $options["offset"], $options["items"]);
175
        $meta["displayedItems"] = count($toc);
176
    }
177
}
178