Passed
Push — master ( 1a35bc...d06049 )
by M. Mikkel
11:03
created

CpFieldInspect::renderEditSourceLink()   B

Complexity

Conditions 9
Paths 25

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 20
c 0
b 0
f 0
nc 25
nop 1
dl 0
loc 28
rs 8.0555
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\ElementInterface;
15
use craft\base\Plugin;
16
use craft\elements\Asset;
17
use craft\events\PluginEvent;
18
use craft\helpers\UrlHelper;
19
use craft\services\Plugins;
20
21
use yii\base\Event;
22
23
/**
24
 * Craft plugins are very much like little applications in and of themselves. We’ve made
25
 * it as simple as we can, but the training wheels are off. A little prior knowledge is
26
 * going to be required to write a plugin.
27
 *
28
 * For the purposes of the plugin docs, we’re going to assume that you know PHP and SQL,
29
 * as well as some semi-advanced concepts like object-oriented programming and PHP namespaces.
30
 *
31
 * https://craftcms.com/docs/plugins/introduction
32
 *
33
 * @author    Mats Mikkel Rummelhoff
34
 * @package   CpFieldInspect
35
 * @since     1.0.0
36
 *
37
 *
38
 * Plugin icon credit: CUSTOMIZE SEARCH by creative outlet from the Noun Project
39
 *
40
 */
41
42
/**
43
 * Class CpFieldInspect
44
 * @package mmikkel\cpfieldinspect
45
 *
46
 */
47
class CpFieldInspect extends Plugin
48
{
49
    // Static Properties
50
    // =========================================================================
51
52
    /**
53
     * Static property that is an instance of this plugin class so that it can be accessed via
54
     * CpFieldInspect::$plugin
55
     *
56
     * @var CpFieldInspect
57
     */
58
    public static $plugin;
59
60
    // Public Methods
61
    // =========================================================================
62
63
    /**
64
     * Set our $plugin static property to this class so that it can be accessed via
65
     * CpFieldInspect::$plugin
66
     *
67
     * Called after the plugin class is instantiated; do any one-time initialization
68
     * here such as hooks and events.
69
     *
70
     * If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
71
     * you do not need to load it in your init() method.
72
     *
73
     */
74
    public function init()
75
    {
76
        parent::init();
77
        self::$plugin = $this;
78
79
        $request = Craft::$app->getRequest();
80
81
        if (!$request->getIsCpRequest() || $request->getIsConsoleRequest()) {
82
            return;
83
        }
84
85
        // Handler: EVENT_AFTER_LOAD_PLUGINS
86
        Event::on(
87
            Plugins::class,
88
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
89
            function () {
90
                $this->doIt();
91
            }
92
        );
93
94
        /**
95
         * Logging in Craft involves using one of the following methods:
96
         *
97
         * Craft::trace(): record a message to trace how a piece of code runs. This is mainly for development use.
98
         * Craft::info(): record a message that conveys some useful information.
99
         * Craft::warning(): record a warning message that indicates something unexpected has happened.
100
         * Craft::error(): record a fatal error that should be investigated as soon as possible.
101
         *
102
         * Unless `devMode` is on, only Craft::warning() & Craft::error() will log to `craft/storage/logs/web.log`
103
         *
104
         * It's recommended that you pass in the magic constant `__METHOD__` as the second parameter, which sets
105
         * the category to the method (prefixed with the fully qualified class name) where the constant appears.
106
         *
107
         * To enable the Yii debug toolbar, go to your user account in the AdminCP and check the
108
         * [] Show the debug toolbar on the front end & [] Show the debug toolbar on the Control Panel
109
         *
110
         * http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
111
         */
112
        Craft::info(
113
            Craft::t(
114
                'cp-field-inspect',
115
                '{name} plugin loaded',
116
                ['name' => $this->name]
117
            ),
118
            __METHOD__
119
        );
120
    }
121
122
    /**
123
     * @param array $context
124
     * @return string
125
     * @throws \Twig\Error\LoaderError
126
     * @throws \Twig\Error\RuntimeError
127
     * @throws \Twig\Error\SyntaxError
128
     * @throws \Twig_Error_Loader
129
     * @throws \yii\base\Exception
130
     */
131
    public function renderEditSourceLink(array $context)
132
    {
133
        $entry = $context['entry'] ?? null;
134
        if ($entry) {
135
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-entry-type-link', $context);
136
        }
137
        $asset = ($context['element'] ?? null) && $context['element'] instanceof Asset ? $context['element'] : null;
138
        if ($asset) {
139
            $context['asset'] = $context['element'];
140
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-volume-link', $context);
141
        }
142
        $globalSet = $context['globalSet'] ?? null;
143
        if ($globalSet) {
144
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-globalset-link', $context);
145
        }
146
        $user = $context['user'] ?? null;
147
        if ($user) {
148
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-users-link', $context);
149
        }
150
        $category = $context['category'] ?? null;
151
        if ($category) {
152
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-category-group-link', $context);
153
        }
154
        $product = $context['product'] ?? null;
155
        if ($product) {
156
            return Craft::$app->getView()->renderTemplate('cp-field-inspect/edit-commerce-product-type-link', $context);
157
        }
158
        return '';
159
    }
160
161
    // Protected Methods
162
    // =========================================================================
163
164
    /**
165
     * @throws \yii\base\Exception
166
     * @throws \yii\base\InvalidConfigException
167
     */
168
    protected function doIt()
169
    {
170
171
        $user = Craft::$app->getUser();
172
        if (!$user->getIsAdmin()) {
173
            return;
174
        }
175
176
        // Template hooks
177
        $view = Craft::$app->getView();
178
        $view->hook('cp.assets.edit.meta', [$this, 'renderEditSourceLink']);
179
        $view->hook('cp.entries.edit.meta', [$this, 'renderEditSourceLink']);
180
        $view->hook('cp.globals.edit.content', [$this, 'renderEditSourceLink']);
181
        $view->hook('cp.users.edit.details', [$this, 'renderEditSourceLink']);
182
        $view->hook('cp.categories.edit.details', [$this, 'renderEditSourceLink']);
183
        $view->hook('cp.commerce.product.edit.details', [$this, 'renderEditSourceLink']);
184
        $view->hook('cp.commerce.order.edit.main-pane', [$this, 'renderEditSourceLink']);
185
186
        $request = Craft::$app->getRequest();
187
188
        if ($request->getIsAjax()) {
189
190
            if (!$request->getIsPost()) {
191
                return;
192
            }
193
194
            $segments = $request->getActionSegments();
195
            if (empty($segments) || !\is_array($segments) || $segments[count($segments) - 1] !== 'get-editor-html') {
196
                return;
197
            }
198
199
            Craft::$app->getView()->registerJs('Craft.CpFieldInspectPlugin.initElementEditor();');
200
201
        } else {
202
203
            $redirectUrl = \implode('?', \array_filter([\implode('/', $request->getSegments()), $request->getQueryStringWithoutPath()]));
204
205
            $data = [
206
                'fields' => [],
207
                'redirectUrl' => Craft::$app->getSecurity()->hashData($redirectUrl),
208
            ];
209
210
            $fields = Craft::$app->getFields()->getAllFields();
211
212
            foreach ($fields as $field) {
213
214
                $data['fields'][$field->handle] = [
215
                    'id' => $field->id,
216
                    'handle' => $field->handle,
217
                ];
218
            }
219
220
            $view->registerAssetBundle(CpFieldInspectBundle::class);
221
            $view->registerJs('Craft.CpFieldInspectPlugin.init(' . \json_encode($data) . ');');
222
        }
223
    }
224
225
}
226