ComponentAbstract   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 0
dl 0
loc 127
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setUrls() 0 12 3
A setPostUrls() 0 19 6
A setPostUrl() 0 7 1
A urlProperty() 0 16 4
A getProperty() 0 4 1
A getComponent() 0 12 2
1
<?php
2
3
namespace GinoPane\BlogTaxonomy\Classes;
4
5
use ArrayAccess;
6
use Cms\Classes\Page;
7
use Cms\Classes\Theme;
8
use Cms\Classes\Controller;
9
use RainLab\Blog\Models\Post;
10
use Cms\Classes\ComponentBase;
11
use RainLab\Blog\Models\Category;
12
use October\Rain\Database\Collection;
13
14
/**
15
 * Class ComponentAbstract
16
 *
17
 * @package GinoPane\BlogTaxonomy\Classes
18
 */
19
abstract class ComponentAbstract extends ComponentBase
0 ignored issues
show
Coding Style introduced by
ComponentAbstract does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
20
{
21
    /**
22
     * Reference to the page name for linking to posts
23
     *
24
     * @var string
25
     */
26
    protected $postPage;
27
28
    /**
29
     * Reference to the page name for linking to categories
30
     *
31
     * @var string
32
     */
33
    protected $categoryPage;
34
35
    /**
36
     * @param Collection $items
37
     * @param string $urlPage
38
     * @param Controller $controller
39
     * @param array $modelUrlParams
40
     */
41
    protected function setUrls(
42
        Collection $items,
43
        string $urlPage,
44
        Controller $controller,
45
        array $modelUrlParams = array()
46
    ) {
47
        if ($items) {
48
            foreach ($items as $item) {
49
                $item->setUrl($urlPage, $controller, $modelUrlParams);
50
            }
51
        }
52
    }
53
54
    /**
55
     * Set Urls to posts
56
     *
57
     * @param ArrayAccess $posts
58
     */
59
    protected function setPostUrls(ArrayAccess $posts)
60
    {
61
        // Add a "url" helper attribute for linking to each post and category
62
        if (!empty($this->postPage) && $posts && $posts->count()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ArrayAccess as the method count() does only exist in the following implementations of said interface: ArrayIterator, ArrayObject, CachingIterator, PDepend\Source\AST\ASTArtifactList, PDepend\Source\AST\ASTCl...erfaceReferenceIterator, Phar, PharData, RecursiveArrayIterator, RecursiveCachingIterator, SplDoublyLinkedList, SplFixedArray, SplObjectStorage, SplQueue, SplStack.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
63
            $posts->each(function ($post) {
64
                $this->setPostUrl($post);
65
66
                if (!empty($this->categoryPage) && $post->categories->count()) {
67
                    $post->categories->each(function ($category) {
68
                        /** @var Category $category */
69
                        $category->setUrl(
70
                            $this->categoryPage,
71
                            $this->controller
72
                        );
73
                    });
74
                }
75
            });
76
        }
77
    }
78
79
    protected function setPostUrl(Post $post)
80
    {
81
        $post->setUrl(
82
            $this->postPage,
83
            $this->controller
84
        );
85
    }
86
87
    /**
88
     * A helper function to get the real URL parameter name. For example, slug for posts
89
     * can be injected as :post into URL. Real argument is necessary if you want to generate
90
     * valid URLs for such pages
91
     *
92
     * @param ComponentBase|null $component
93
     * @param string $name
94
     *
95
     * @return string|null
96
     */
97
    protected function urlProperty(ComponentBase $component = null, string $name = '')
98
    {
99
        $property = null;
100
101
        if ($component !== null && ($property = $component->property($name))) {
102
            preg_match('/{{ :([^ ]+) }}/', $property, $matches);
103
104
            if (isset($matches[1])) {
105
                $property = $matches[1];
106
            }
107
        } else {
108
            $property = $name;
109
        }
110
111
        return $property;
112
    }
113
114
    /**
115
     * Returns page property defaulting to the value from defineProperties() array with fallback
116
     * to explicitly passed default value
117
     *
118
     * @param string $property
119
     * @param $default
120
     *
121
     * @return mixed
122
     */
123
    public function getProperty(string $property, $default = null)
124
    {
125
        return $this->property($property, $this->defineProperties()[$property]['default'] ?? $default);
126
    }
127
128
    /**
129
     * @param string $componentName
130
     * @param string $page
131
     * @return ComponentBase|null
132
     */
133
    protected function getComponent(string $componentName, string $page)
134
    {
135
        $component = null;
136
137
        $page = Page::load(Theme::getActiveTheme(), $page);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $page. This often makes code more readable.
Loading history...
138
139
        if ($page !== null) {
140
            $component = $page->getComponent($componentName);
141
        }
142
143
        return $component;
144
    }
145
}
146