Completed
Push — master ( 5939e9...7f76f6 )
by Gino
01:38
created

ComponentAbstract::urlProperty()   A

Complexity

Conditions 4
Paths 3

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 3
nop 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
    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 (!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
            $blogPostComponent = $this->getComponent('blogPost', $this->postPage);
64
            $blogPostsComponent = $this->getComponent('blogPosts', $this->categoryPage ?? '');
65
66
            $posts->each(function($post) use ($blogPostComponent, $blogPostsComponent) {
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 ($blogPostsComponent) {
78
                        /** @var Category $category */
79
                        $category->setUrl(
80
                            $this->categoryPage,
81
                            $this->controller,
82
                            [
83
                                'slug' => $this->urlProperty($blogPostsComponent, 'categoryFilter')
84
                            ]
85
                        );
86
                    });
87
                }
88
            });
89
        }
90
    }
91
92
    /**
93
     * A helper function to get the real URL parameter name. For example, slug for posts
94
     * can be injected as :post into URL. Real argument is necessary if you want to generate
95
     * valid URLs for such pages
96
     *
97
     * @param ComponentBase|null $component
98
     * @param string $name
99
     *
100
     * @return string|null
101
     */
102
    protected function urlProperty(ComponentBase $component = null, string $name = '')
103
    {
104
        $property = null;
105
106
        if ($component !== null && ($property = $component->property($name))) {
107
            preg_match('/{{ :([^ ]+) }}/', $property, $matches);
108
109
            if (isset($matches[1])) {
110
                $property = $matches[1];
111
            }
112
        } else {
113
            $property = $name;
114
        }
115
116
        return $property;
117
    }
118
119
    /**
120
     * Returns page property defaulting to the value from defineProperties() array with fallback
121
     * to explicitly passed default value
122
     *
123
     * @param string $property
124
     * @param $default
125
     *
126
     * @return mixed
127
     */
128
    public function getProperty(string $property, $default = null)
129
    {
130
        return $this->property($property, $this->defineProperties()[$property]['default'] ?? $default);
131
    }
132
133
    /**
134
     * @param string $componentName
135
     * @param string $page
136
     * @return ComponentBase|null
137
     */
138
    protected function getComponent(string $componentName, string $page)
139
    {
140
        $component = null;
141
142
        $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...
143
144
        if ($page !== null) {
145
            $component = $page->getComponent($componentName);
146
        }
147
148
        return $component;
149
    }
150
}
151