Completed
Push — master ( 8bc312...e53390 )
by Gino
02:00
created

Plugin::extendPostsController()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 60
Code Lines 39

Duplication

Lines 8
Ratio 13.33 %

Importance

Changes 0
Metric Value
dl 8
loc 60
rs 9.5555
c 0
b 0
f 0
cc 3
eloc 39
nc 1
nop 0

How to fix   Long Method   

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 GinoPane\BlogTaxonomy;
4
5
use Event;
6
use Backend;
7
use System\Classes\PluginBase;
8
use Backend\Classes\Controller;
9
use GinoPane\BlogTaxonomy\Models\Tag;
10
use GinoPane\BlogTaxonomy\Models\Series;
11
use Backend\Behaviors\RelationController;
12
use RainLab\Blog\Models\Post as PostModel;
13
use GinoPane\BlogTaxonomy\Components\TagList;
14
use GinoPane\BlogTaxonomy\Components\TagPosts;
15
use GinoPane\BlogTaxonomy\Components\SeriesList;
16
use GinoPane\BlogTaxonomy\Components\SeriesPosts;
17
use GinoPane\BlogTaxonomy\Components\RelatedPosts;
18
use RainLab\Blog\Controllers\Posts as PostsController;
19
use GinoPane\BlogTaxonomy\Components\SeriesNavigation;
20
use RainLab\Blog\Controllers\Categories as CategoriesController;
21
22
/**
23
 * Class Plugin
24
 *
25
 * @package GinoPane\BlogTaxonomy
26
 */
27
class Plugin extends PluginBase
28
{
29
    const LOCALIZATION_KEY = 'ginopane.blogtaxonomy::lang.';
30
31
    const DIRECTORY_KEY = 'ginopane/blogtaxonomy';
32
33
    const REQUIRED_PLUGIN = 'RainLab.Blog';
34
35
    /**
36
     * @var array   Require the RainLab.Blog plugin
37
     */
38
    public $require = [self::REQUIRED_PLUGIN];
39
40
    /**
41
     * Returns information about this plugin
42
     *
43
     * @return  array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
44
     */
45
    public function pluginDetails()
46
    {
47
        return [
48
            'name'        => self::LOCALIZATION_KEY . 'plugin.name',
49
            'description' => self::LOCALIZATION_KEY . 'plugin.description',
50
            'author'      => 'Gino Pane',
51
            'icon'        => 'icon-tags',
52
            'homepage'    => 'https://github.com/ginopane/oc-blog-taxonomy'
53
        ];
54
    }
55
56
    /**
57
     * Register components
58
     *
59
     * @return  array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<*,string>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
60
     */
61
    public function registerComponents()
62
    {
63
        return [
64
            TagList::class          => 'tagList',
65
            TagPosts::class         => 'postsWithTag',
66
            RelatedPosts::class     => 'relatedPosts',
67
            SeriesList::class       => 'seriesList',
68
            SeriesPosts::class      => 'postsInSeries',
69
            SeriesNavigation::class => 'seriesNavigation',
70
        ];
71
    }
72
73
    /**
74
     * Boot method, called right before the request route
75
     */
76
    public function boot()
77
    {
78
        // extend the post model
79
        $this->extendModel();
80
81
        // extend posts functionality
82
        $this->extendPostsController();
83
84
        // extend categories functionality
85
        $this->extendCategoriesController();
86
    }
87
88
    /**
89
     * Register plugin navigation
90
     */
91
    public function registerNavigation()
92
    {
93
        // Extend the navigation
94
        Event::listen('backend.menu.extendItems', function ($manager) {
95
            $manager->addSideMenuItems(self::REQUIRED_PLUGIN, 'blog', [
96
                'series' => [
97
                    'label' => self::LOCALIZATION_KEY . 'navigation.series',
98
                    'icon' => 'icon-list-alt',
99
                    'code' => 'series',
100
                    'owner' => self::REQUIRED_PLUGIN,
101
                    'url' => Backend::url(self::DIRECTORY_KEY . '/series')
102
                ],
103
104
                'tags' => [
105
                    'label' => self::LOCALIZATION_KEY . 'navigation.tags',
106
                    'icon'  => 'icon-tags',
107
                    'code'  => 'tags',
108
                    'owner' => self::REQUIRED_PLUGIN,
109
                    'url'   => Backend::url(self::DIRECTORY_KEY . '/tags')
110
                ]
111
            ]);
112
        });
113
    }
114
115
    /**
116
     * Extend RainLab Post model
117
     */
118
    private function extendModel()
119
    {
120
        PostModel::extend(function ($model) {
121
            $model->belongsToMany['tags'] = [
122
                Tag::class,
123
                'table' => Tag::CROSS_REFERENCE_TABLE_NAME,
124
                'order' => 'name'
125
            ];
126
127
            $model->belongsTo['series'] = [
128
                Series::class,
129
                'key' => Series::TABLE_NAME . "_id"
130
            ];
131
        });
132
    }
133
134
    /**
135
     * Extends post controller functionality
136
     */
137
    private function extendPostsController()
138
    {
139
        PostsController::extendFormFields(function ($form, $model) {
140
            if (!$model instanceof PostModel) {
0 ignored issues
show
Bug introduced by
The class RainLab\Blog\Models\Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
141
                return;
142
            }
143
144
            $tab = self::LOCALIZATION_KEY . 'navigation.taxonomy';
145
146
            $categoriesConfig = $form->getField('categories')->config;
147
            $categoriesConfig['tab'] = $tab;
148
            $categoriesConfig['mode'] = 'relation';
149
            $categoriesConfig['type'] = 'taglist';
150
            $categoriesConfig['label'] = 'Categories';
151
            $categoriesConfig['comment'] = "rainlab.blog::lang.post.categories_comment";
152
            $categoriesConfig['placeholder'] = self::LOCALIZATION_KEY . 'placeholders.tags';
153
            unset($categoriesConfig['commentAbove']);
154
155
            $form->removeField('categories');
156
157
            $form->addSecondaryTabFields([
158
                'categories' => $categoriesConfig,
159
                'tags' => [
160
                    'label' => self::LOCALIZATION_KEY . 'form.tags.label',
161
                    'comment' => self::LOCALIZATION_KEY . 'form.tags.comment',
162
                    'mode' => 'relation',
163
                    'tab' => $tab,
164
                    'type' => 'taglist',
165
166
                    /**
167
                     * Placeholders are not supported yet by the core.
168
                     * PR is waiting: https://github.com/octobercms/october/pull/3453
169
                     */
170
                    'placeholder' => self::LOCALIZATION_KEY . 'placeholders.tags',
171
                ],
172
                'series' => [
173
                    'label' => self::LOCALIZATION_KEY . 'form.series.label',
174
                    'tab' => $tab,
175
                    'type' => 'relation',
176
                    'nameFrom' => 'title',
177
                    'comment' => self::LOCALIZATION_KEY . 'form.series.comment',
178
                    'emptyOption' => self::LOCALIZATION_KEY . 'placeholders.series'
179
                ],
180
            ]);
181
        });
182
183
        PostsController::extend(function (Controller $controller) {
184
            $controller->implement[] = RelationController::class;
185
            $relationConfig = '$/' . self::DIRECTORY_KEY . '/controllers/series/config_posts_relation.yaml';
186
187 View Code Duplication
            if (property_exists($controller, 'relationConfig')) {
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...
188
                $controller->relationConfig = $controller->mergeConfig(
189
                    $controller->relationConfig,
190
                    $relationConfig
191
                );
192
            } else {
193
                $controller->addDynamicProperty('relationConfig', $relationConfig);
194
            }
195
        });
196
    }
197
198
    /**
199
     * Extends categories controller functionality
200
     */
201
    private function extendCategoriesController()
202
    {
203
        CategoriesController::extend(function (Controller $controller) {
204
            $controller->implement[] = RelationController::class;
205
            $relationConfig = '$/' . self::DIRECTORY_KEY . '/controllers/category/config_relation.yaml';
206
207 View Code Duplication
            if (property_exists($controller, 'relationConfig')) {
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...
208
                $controller->relationConfig = $controller->mergeConfig(
209
                    $controller->relationConfig,
210
                    $relationConfig
211
                );
212
            } else {
213
                $controller->addDynamicProperty('relationConfig', $relationConfig);
214
            }
215
216
            $formConfig = '$/' . self::DIRECTORY_KEY . '/controllers/category/config_form.yaml';
217
218
            if (property_exists($controller, 'formConfig')) {
219
                $controller->formConfig = $controller->mergeConfig(
220
                    $controller->formConfig,
221
                    $formConfig
222
                );
223
            } else {
224
                $controller->addDynamicProperty('formConfig', $formConfig);
225
            }
226
        });
227
    }
228
}
229