Test Failed
Push — develop ( 833c7b...9196d8 )
by Paul
08:20
created

Block   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
eloc 24
dl 0
loc 52
ccs 0
cts 31
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A app() 0 3 1
A register() 0 11 2
A hasVisibleFields() 0 3 1
A render() 0 13 3
A buildEmptyBlock() 0 7 1
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Blocks;
4
5
use GeminiLabs\SiteReviews\Contracts\PluginContract;
6
use GeminiLabs\SiteReviews\Contracts\ShortcodeContract;
7
use GeminiLabs\SiteReviews\Helpers\Str;
8
use GeminiLabs\SiteReviews\Modules\Html\Builder;
9
10
abstract class Block
11
{
12
    public function app(): PluginContract
13
    {
14
        return glsr();
15
    }
16
17
    public function register(): void
18
    {
19
        if (!function_exists('register_block_type_from_metadata')) {
20
            return;
21
        }
22
        $block = (new \ReflectionClass($this))->getShortName();
23
        $block = str_replace('_block', '', Str::snakeCase($block));
24
        register_block_type_from_metadata($this->app()->path("assets/blocks/{$block}"), [
25
            'editor_style' => "{$this->app()->id}/blocks",
26
            'render_callback' => [$this, 'render'],
27
            'style' => $this->app()->id,
28
        ]);
29
    }
30
31
    public function render(array $attributes): string
32
    {
33
        if ('edit' === filter_input(INPUT_GET, 'context')) {
34
            if (!$this->hasVisibleFields($attributes)) {
35
                return $this->buildEmptyBlock(
36
                    _x('You have hidden all of the fields for this block.', 'admin-text', 'site-reviews')
37
                );
38
            }
39
        }
40
        preg_match_all('/(\w+)="([^"]*)"/', get_block_wrapper_attributes(), $matches, PREG_SET_ORDER);
41
        $atts = array_column($matches, 2, 1);
42
        $attributes['class'] = $atts['class'] ?? '';
43
        return $this->shortcode()->build($attributes, 'block');
44
    }
45
46
    abstract public function shortcode(): ShortcodeContract;
47
48
    protected function buildEmptyBlock(string $text): string
49
    {
50
        return glsr(Builder::class)->div([
51
            'class' => 'block-editor-warning',
52
            'text' => glsr(Builder::class)->p([
53
                'class' => 'block-editor-warning__message',
54
                'text' => $text,
55
            ]),
56
        ]);
57
    }
58
59
    protected function hasVisibleFields(array $attributes): bool
60
    {
61
        return $this->shortcode()->hasVisibleFields($attributes);
62
    }
63
}
64