Passed
Pull Request — master (#12)
by
unknown
04:20
created

CpFieldInspect::init()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 63
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 7
eloc 27
c 5
b 1
f 0
nc 13
nop 0
dl 0
loc 63
rs 8.5546

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
 * CP Field Inspect plugin for Craft CMS 3.x
4
 *
5
 * Inspect field handles and easily edit field settings
6
 *
7
 * @link      http://mmikkel.no
8
 * @copyright Copyright (c) 2017 Mats Mikkel Rummelhoff
9
 */
10
11
namespace mmikkel\cpfieldinspect;
12
13
use Craft;
14
use craft\base\Plugin;
15
use craft\db\Query;
16
use craft\db\Table;
17
use craft\events\PluginEvent;
18
use craft\helpers\ArrayHelper;
19
use craft\helpers\UrlHelper;
20
use craft\services\Plugins;
21
22
use yii\base\Event;
23
24
/**
25
 * Craft plugins are very much like little applications in and of themselves. We’ve made
26
 * it as simple as we can, but the training wheels are off. A little prior knowledge is
27
 * going to be required to write a plugin.
28
 *
29
 * For the purposes of the plugin docs, we’re going to assume that you know PHP and SQL,
30
 * as well as some semi-advanced concepts like object-oriented programming and PHP namespaces.
31
 *
32
 * https://craftcms.com/docs/plugins/introduction
33
 *
34
 * @author    Mats Mikkel Rummelhoff
35
 * @package   CpFieldInspect
36
 * @since     1.0.0
37
 *
38
 *
39
 * Plugin icon credit: CUSTOMIZE SEARCH by creative outlet from the Noun Project
40
 *
41
 */
42
43
/**
44
 * Class CpFieldInspect
45
 * @package mmikkel\cpfieldinspect
46
 *
47
 */
48
class CpFieldInspect extends Plugin
49
{
50
    // Static Properties
51
    // =========================================================================
52
53
    /**
54
     * Static property that is an instance of this plugin class so that it can be accessed via
55
     * CpFieldInspect::$plugin
56
     *
57
     * @var CpFieldInspect
58
     */
59
    public static $plugin;
60
61
    // Public Methods
62
    // =========================================================================
63
64
    /**
65
     * Set our $plugin static property to this class so that it can be accessed via
66
     * CpFieldInspect::$plugin
67
     *
68
     * Called after the plugin class is instantiated; do any one-time initialization
69
     * here such as hooks and events.
70
     *
71
     * If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
72
     * you do not need to load it in your init() method.
73
     *
74
     */
75
    public function init()
76
    {
77
        parent::init();
78
        self::$plugin = $this;
79
80
        $request = Craft::$app->getRequest();
81
        // this will break the fields and plugins initialization
82
        // https://github.com/craftcms/cms/issues/4944
83
        // https://github.com/mmikkel/CpFieldInspect-Craft/issues/11
84
        // $fields = Craft::$app->getFields()->getAllFields();
85
        if (/*!$user->getIsAdmin() || */ !$request->getIsCpRequest() || $request->getIsConsoleRequest()) {
86
            return;
87
        }
88
89
        // this is hacky and ugly but I don't know an alternative... we can't populate the user yet ¯\_(ツ)_/¯
90
        $session = Craft::$app->getSession();
91
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get(Craft::$app->getUser()->idParam) : null;
92
        if(empty($id) === true){
93
            return;
94
        }
95
        $isAdmin = (new Query())
96
            ->select('admin')
97
            ->from(Table::USERS)
98
            ->where(['id' => $id])
99
            ->scalar();
100
        if((bool)$isAdmin === false){
101
            return;
102
        }
103
104
        // Handler: EVENT_AFTER_LOAD_PLUGINS
105
        Event::on(
106
            Plugins::class,
107
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
108
            function () {
109
                $this->doIt();
110
            }
111
        );
112
113
        /**
114
         * Logging in Craft involves using one of the following methods:
115
         *
116
         * Craft::trace(): record a message to trace how a piece of code runs. This is mainly for development use.
117
         * Craft::info(): record a message that conveys some useful information.
118
         * Craft::warning(): record a warning message that indicates something unexpected has happened.
119
         * Craft::error(): record a fatal error that should be investigated as soon as possible.
120
         *
121
         * Unless `devMode` is on, only Craft::warning() & Craft::error() will log to `craft/storage/logs/web.log`
122
         *
123
         * It's recommended that you pass in the magic constant `__METHOD__` as the second parameter, which sets
124
         * the category to the method (prefixed with the fully qualified class name) where the constant appears.
125
         *
126
         * To enable the Yii debug toolbar, go to your user account in the AdminCP and check the
127
         * [] Show the debug toolbar on the front end & [] Show the debug toolbar on the Control Panel
128
         *
129
         * http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
130
         */
131
        Craft::info(
132
            Craft::t(
133
                'cp-field-inspect',
134
                '{name} plugin loaded',
135
                ['name' => $this->name]
136
            ),
137
            __METHOD__
138
        );
139
    }
140
141
    // Protected Methods
142
    // =========================================================================
143
144
    /**
145
     * @return bool
146
     * @throws \yii\base\Exception
147
     * @throws \yii\base\InvalidConfigException
148
     */
149
    protected function doIt()
150
    {
151
152
        $request = Craft::$app->getRequest();
153
154
        if ($request->getIsAjax()) {
155
156
            if (!$request->getIsPost()) {
157
                return;
158
            }
159
160
            $segments = $request->getSegments();
161
            $actionSegment = $segments[count($segments) - 1];
162
163
            if ($actionSegment !== 'get-editor-html') {
164
                return false;
165
            }
166
167
            Craft::$app->getView()->registerJs('Craft.CpFieldInspectPlugin.initElementEditor();');
168
169
        } else {
170
171
            $redirectUrl = \implode('?', \array_filter([\implode('/', $request->getSegments()), $request->getQueryStringWithoutPath()]));
172
173
            $data = [
174
                'fields' => [],
175
                'entryTypeIds' => [],
176
                'baseEditFieldUrl' => \rtrim(UrlHelper::cpUrl('settings/fields/edit'), '/'),
177
                'baseEditEntryTypeUrl' => \rtrim(UrlHelper::cpUrl('settings/sections/sectionId/entrytypes'), '/'),
178
                'baseEditGlobalSetUrl' => \rtrim(UrlHelper::cpUrl('settings/globals'), '/'),
179
                'baseEditCategoryGroupUrl' => \rtrim(UrlHelper::cpUrl('settings/categories'), '/'),
180
                'baseEditCommerceProductTypeUrl' => \rtrim(UrlHelper::cpUrl('commerce/settings/producttypes'), '/'),
181
                'redirectUrl' => Craft::$app->getSecurity()->hashData($redirectUrl),
182
            ];
183
184
            $sectionIds = Craft::$app->getSections()->getAllSectionIds();
185
            foreach ($sectionIds as $sectionId) {
186
                $entryTypes = Craft::$app->getSections()->getEntryTypesBySectionId($sectionId);
187
                $data['entryTypeIds'][(string)$sectionId] = [];
188
                foreach ($entryTypes as $entryType) {
189
                    $data['entryTypeIds'][(string)$sectionId][] = $entryType->id;
190
                }
191
            }
192
193
194
            // this will break the fields and plugins initialization
195
            // https://github.com/craftcms/cms/issues/4944
196
            // https://github.com/mmikkel/CpFieldInspect-Craft/issues/11
197
            // $fields = Craft::$app->getFields()->getAllFields();
198
199
            // query for the fields myself because otherwise it will mess up the users field layout
200
            $fields = (new Query())
201
                ->select([
202
                             'fields.id',
203
                             'fields.handle',
204
                         ])
205
                ->from(['{{%fields}} fields'])
206
                ->where(['context' => 'global'])
207
                ->orderBy(['fields.name' => SORT_ASC, 'fields.handle' => SORT_ASC])
208
                ->all();
209
210
211
            $data['fields'] = ArrayHelper::index($fields, 'id');
212
            $view = Craft::$app->getView();
213
            $view->registerAssetBundle(CpFieldInspectBundle::class);
214
            $view->registerJs('Craft.CpFieldInspectPlugin.init(' . \json_encode($data) . ');');
215
        }
216
    }
217
218
}
219