Completed
Push — master ( a30fc0...84b57d )
by Gino
01:44
created

ComponentAbstract::getComponent()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 2
1
<?php
2
3
namespace GinoPane\BlogTaxonomy\Components;
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\Components
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
    public 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
    public function setPostUrls(ArrayAccess $posts)
60
    {
61
        // Add a "url" helper attribute for linking to each post and category
62
        if ($posts && $posts->count() && !empty($this->postPage)) {
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, Symfony\Component\Finder...rator\InnerNameIterator, Symfony\Component\Finder...rator\InnerSizeIterator, Symfony\Component\Finder...rator\InnerTypeIterator, Symfony\Component\Finder...or\MockFileListIterator.

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
            $blogPostComponent = $this->getComponent('blogPost', $this->postPage);
64
            $blogCategoriesComponent = $this->getComponent('blogCategories', $this->categoryPage ?? '');
65
66
            $posts->each(function($post) use ($blogPostComponent, $blogCategoriesComponent) {
67
                /** @var Post $post */
68
                $post->setUrl(
69
                    $this->postPage,
70
                    $this->controller,
71
                    [
72
                        'slug' => $this->urlProperty($blogPostComponent, 'slug')
73
                    ]
74
                );
75
76
                if (!empty($this->categoryPage) && $post->categories->count()) {
77
                    $post->categories->each(function ($category) use ($blogCategoriesComponent) {
78
                        /** @var Category $category */
79
                        $category->setUrl(
80
                            $this->categoryPage,
81
                            $this->controller,
82
                            [
83
                                'slug' => $this->urlProperty($blogCategoriesComponent, 'slug')
84
                            ]
85
                        );
86
                    });
87
                }
88
            });
89
        }
90
    }
91
92
    /**
93
     * A helper function to return property value
94
     *
95
     * @param ComponentBase|null $component
96
     * @param string $name
97
     *
98
     * @return string|null
99
     */
100
    protected function urlProperty(ComponentBase $component = null, string $name)
101
    {
102
        return $component ? $component->propertyName($name, $name) : null;
103
    }
104
105
    /**
106
     * Returns page property defaulting to the value from defineProperties() array with fallback
107
     * to explicitly passed default value
108
     *
109
     * @param string $property
110
     * @param $default
111
     *
112
     * @return mixed
113
     */
114
    public function getProperty(string $property, $default = null)
115
    {
116
        return $this->property($property, $this->defineProperties()[$property]['default'] ?? $default);
117
    }
118
119
    /**
120
     * @param string $componentName
121
     * @param string $page
122
     * @return ComponentBase|null
123
     */
124
    protected function getComponent(string $componentName, string $page)
125
    {
126
        $component = null;
127
128
        $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...
129
130
        if (!is_null($page)) {
131
            $component = $page->getComponent($componentName);
132
        }
133
134
        if (!empty($component) && is_callable([$this->controller, 'setComponentPropertiesFromParams'])) {
135
            $this->controller->setComponentPropertiesFromParams($component);
136
        }
137
138
        return $component;
139
    }
140
}
141