GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 0322d9...a68f9e )
by Leonardo
03:48
created

AbstractBlock::getScriptPublicPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQLAPI\GraphQLAPI\Blocks;
6
7
use Error;
8
use GraphQLAPI\GraphQLAPI\General\GeneralUtils;
9
use GraphQLAPI\GraphQLAPI\General\EditorHelpers;
10
use GraphQLAPI\GraphQLAPI\Security\UserAuthorization;
11
use GraphQLAPI\GraphQLAPI\BlockCategories\AbstractBlockCategory;
12
use GraphQLAPI\GraphQLAPI\EditorScripts\HasDocumentationScriptTrait;
13
14
/**
15
 * Base class for a Gutenberg block, within a multi-block plugin.
16
 * The JS/CSS assets for each block is contained in folder {pluginDir}/blocks/{blockName}, and follows
17
 * the architecture from @wordpress/create-block package
18
 *
19
 * @see https://developer.wordpress.org/block-editor/packages/packages-create-block/
20
 * (this package provides the scaffolding for a single-block plugin,
21
 * so the plugin .php file is ignored registering a single block is ignored, and everything else is used)
22
 */
23
abstract class AbstractBlock
24
{
25
    use HasDocumentationScriptTrait;
26
27
    /**
28
     * Execute this function to initialize the block
29
     *
30
     * @return void
31
     */
32
    public function initialize(): void
33
    {
34
        \add_action('init', [$this, 'initBlock']);
35
    }
36
37
    /**
38
     * Plugin dir
39
     *
40
     * @return string
41
     */
42
    abstract protected function getPluginDir(): string;
43
    /**
44
     * Plugin URL
45
     *
46
     * @return string
47
     */
48
    abstract protected function getPluginURL(): string;
49
    /**
50
     * Block namespace
51
     *
52
     * @return string
53
     */
54
    abstract protected function getBlockNamespace(): string;
55
    /**
56
     * Block name
57
     *
58
     * @return string
59
     */
60
    abstract protected function getBlockName(): string;
61
62
    /**
63
     * If the block is dynamic, it will return the server-side HTML through function `renderBlock`
64
     */
65
    protected function isDynamicBlock(): bool
66
    {
67
        return false;
68
    }
69
    /**
70
     * Produce the HTML for dynamic blocks
71
     */
72
    public function renderBlock(array $attributes, string $content): string
73
    {
74
        return '';
75
    }
76
    /**
77
     * Do not output the content, and show an error message to the visitor
78
     */
79
    public function renderUnauthorizedAccess(): string
80
    {
81
        return sprintf(
82
            '<p>%s</p>',
83
            \__('You are not authorized to see this content', 'graphql-api')
84
        );
85
    }
86
    /**
87
     * Register index.css
88
     *
89
     * @return boolean
90
     */
91
    protected function registerEditorCSS(): bool
92
    {
93
        return false;
94
    }
95
    /**
96
     * Register style-index.css
97
     *
98
     * @return boolean
99
     */
100
    protected function registerCommonStyleCSS(): bool
101
    {
102
        return false;
103
    }
104
    /**
105
     * The block full name: namespace/blockName
106
     *
107
     * @return string
108
     */
109
    final public function getBlockFullName(): string
110
    {
111
        return sprintf(
112
            '%s/%s',
113
            $this->getBlockNamespace(),
114
            $this->getBlockName()
115
        );
116
    }
117
    /**
118
     * Block registration name: namespace-blockName
119
     *
120
     * @return string
121
     */
122
    final protected function getBlockRegistrationName(): string
123
    {
124
        return sprintf(
125
            '%s-%s',
126
            $this->getBlockNamespace(),
127
            $this->getBlockName()
128
        );
129
    }
130
    /**
131
     * Block registration name: namespace-blockName
132
     *
133
     * @return string
134
     */
135
    final protected function getBlockLocalizationName(): string
136
    {
137
        return GeneralUtils::dashesToCamelCase($this->getBlockRegistrationName());
138
    }
139
    /**
140
     * Block class name: wp-block-namespace-blockName
141
     *
142
     * @return string
143
     */
144
    protected function getBlockClassName(): string
145
    {
146
        return sprintf(
147
            'wp-block-%s',
148
            $this->getBlockRegistrationName()
149
        );
150
    }
151
152
    /**
153
     * Block align class
154
     */
155
    public function getAlignClass(): string
156
    {
157
        return 'aligncenter';
158
    }
159
160
    /**
161
     * Pass localized data to the block
162
     *
163
     * @return array
164
     */
165
    protected function getLocalizedData(): array
166
    {
167
        return $this->getDocsLocalizedData();
168
    }
169
170
    /**
171
     * Where is the block stored
172
     *
173
     * @return string
174
     */
175
    protected function getBlockDirURL(): string
176
    {
177
        return $this->getPluginURL() . '/blocks/' . $this->getBlockName() . '/';
178
    }
179
180
    /**
181
     * Where is the block stored
182
     *
183
     * @return string
184
     */
185
    protected function getBlockDir(): string
186
    {
187
        return $this->getPluginDir() . '/blocks/' . $this->getBlockName();
188
    }
189
190
    protected function getBlockCategory(): ?AbstractBlockCategory
191
    {
192
        return null;
193
    }
194
195
    /**
196
     * Post types for which to register the script
197
     *
198
     * @return array
199
     */
200
    protected function getAllowedPostTypes(): array
201
    {
202
        if ($blockCategory = $this->getBlockCategory()) {
203
            return $blockCategory->getPostTypes();
204
        }
205
        return [];
206
    }
207
208
    /**
209
     * Dependencies to load before the block
210
     *
211
     * @return array
212
     */
213
    protected function getBlockDependencies(): array
214
    {
215
        return [];
216
    }
217
218
    /**
219
     * Docs are bundled as chunks by webpack, and loaded lazily
220
     * The `publicPath` property for `config.output` must be provided
221
     * pointing to the generated chunks folder, otherwise it is
222
     * by default resolved as /wp-admin/..., producing a 404.
223
     *
224
     * The public path will be set under global variable `__webpack_public_path__` in JS
225
     *
226
     * @see https://v4.webpack.js.org/guides/public-path/#on-the-fly
227
     */
228
    protected function getScriptPublicPath(): string
229
    {
230
        return $this->getBlockDirURL() . 'build/';
231
    }
232
233
    /**
234
     * Registers all block assets so that they can be enqueued through the block editor
235
     * in the corresponding context.
236
     *
237
     * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/applying-styles-with-stylesheets/
238
     */
239
    public function initBlock(): void
240
    {
241
        /**
242
         * In the admin, if the block belongs to a category, and the category works only under certain CPTs,
243
         * then register the block only if we are on any of those CPTs.
244
         * Otherwise, the block would be registered but the category is not,
245
         * printing error console such as:
246
         * > The block "graphql-api/schema-configuration" must have a registered category.
247
         */
248
        if (\is_admin()) {
249
            if ($postTypes = $this->getAllowedPostTypes()) {
250
                if (!in_array(EditorHelpers::getEditingPostType(), $postTypes)) {
251
                    return;
252
                }
253
            }
254
        }
255
256
        $dir = $this->getBlockDir();
257
        $blockFullName = $this->getBlockFullName();
258
259
        $script_asset_path = "$dir/build/index.asset.php";
260
        if (!file_exists($script_asset_path)) {
261
            throw new Error(
262
                sprintf(
263
                    \__('You need to run `npm start` or `npm run build` for the "%s" block first.', 'graphql-api'),
264
                    $blockFullName
265
                )
266
            );
267
        }
268
269
        $url = $this->getBlockDirURL();
270
        $blockRegistrationName = $this->getBlockRegistrationName();
271
        $blockConfiguration = [];
272
273
        // Load the block scripts and styles
274
        $index_js     = 'build/index.js';
275
        $script_asset = require($script_asset_path);
276
        $scriptRegistrationName = $blockRegistrationName . '-block-editor';
277
        \wp_register_script(
278
            $scriptRegistrationName,
279
            $url . $index_js,
280
            array_merge(
281
                $script_asset['dependencies'],
282
                $this->getBlockDependencies()
283
            ),
284
            $script_asset['version']
285
        );
286
        $blockConfiguration['editor_script'] = $blockRegistrationName . '-block-editor';
287
288
        /**
289
         * Register editor CSS file
290
         */
291
        if ($this->registerEditorCSS()) {
292
            $editor_css = 'build/index.css';
293
            \wp_register_style(
294
                $blockRegistrationName . '-block-editor',
295
                $url . $editor_css,
296
                array(),
297
                filemtime("$dir/$editor_css")
298
            );
299
            $blockConfiguration['editor_style'] = $blockRegistrationName . '-block-editor';
300
        }
301
302
        /**
303
         * Register client/editor CSS file
304
         */
305
        if ($this->registerCommonStyleCSS()) {
306
            $style_css = 'build/style-index.css';
307
            \wp_register_style(
308
                $blockRegistrationName . '-block',
309
                $url . $style_css,
310
                array(),
311
                filemtime("$dir/$style_css")
312
            );
313
            $blockConfiguration['style'] = $blockRegistrationName . '-block';
314
        }
315
316
        /**
317
         * Register callback function for dynamic block
318
         */
319
        if ($this->isDynamicBlock()) {
320
            /**
321
             * Show only if the user has the right permission
322
             */
323
            if (UserAuthorization::canAccessSchemaEditor()) {
324
                $blockConfiguration['render_callback'] = [$this, 'renderBlock'];
325
            } else {
326
                $blockConfiguration['render_callback'] = [$this, 'renderUnauthorizedAccess'];
327
            }
328
        }
329
330
        /**
331
         * Localize the script with custom data
332
         * Execute on hook "wp_print_scripts" and not now,
333
         * because `getLocalizedData` might call EndpointHelpers::getAdminGraphQLEndpoint(),
334
         * which calls ComponentModelComponentConfiguration::namespaceTypesAndInterfaces(),
335
         * which is initialized during "wp"
336
         */
337
        \add_action('wp_print_scripts', function () use ($scriptRegistrationName) {
338
            if ($localizedData = $this->getLocalizedData()) {
339
                \wp_localize_script(
340
                    $scriptRegistrationName,
341
                    $this->getBlockLocalizationName(),
342
                    $localizedData
343
                );
344
            }
345
        });
346
347
        \register_block_type($blockFullName, $blockConfiguration);
348
349
        /**
350
         * Register the documentation (from under folder "docs/"), for the locale and the default language
351
         * IMPORTANT: Uncomment for webpack v5, to not duplicate the content of the docs inside build/index.js
352
         */
353
        // $this->initDocumentationScripts();
354
    }
355
356
    /**
357
     * Register the documentation (from under folder "docs/"), for the locale and the default language
358
     */
359
    protected function initDocumentationScripts(): void
360
    {
361
        $dir = $this->getBlockDir();
362
        $script_asset_path = "$dir/build/index.asset.php";
363
        $url = $this->getBlockDirURL();
364
        $script_asset = require($script_asset_path);
365
        $blockRegistrationName = $this->getBlockRegistrationName();
366
        $scriptRegistrationName = $blockRegistrationName . '-block-editor';
367
368
        $this->registerDocumentationScripts($scriptRegistrationName, $url, $script_asset['dependencies'], $script_asset['version']);
369
    }
370
}
371