Block::showID()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Cita\Modular\Model;
4
5
use SilverStripe\Forms\CompositeField;
6
use SilverStripe\Forms\GridField\GridFieldConfig_RecordViewer;
7
use SilverStripe\Forms\GridField\GridField;
8
use SilverStripe\ORM\DataObject;
9
use SilverStripe\Forms\CheckboxField;
10
use SilverStripe\Versioned\Versioned;
11
use SilverStripe\Forms\LiteralField;
12
use Psr\SimpleCache\CacheInterface;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\Core\Flushable;
15
use SilverStripe\Forms\FieldList;
16
use Page;
17
18
/**
19
 * Description
20
 *
21
 * @package silverstripe
22
 * @subpackage mysite
23
 */
24
class Block extends DataObject implements Flushable
25
{
26
    private static $cache_enabled = false;
27
28
    /**
29
     * Defines the database table name
30
     * @var string
31
     */
32
    private static $table_name  =   'Cita_Modular_Block';
33
34
    /**
35
     * Singular name for CMS
36
     * @var string
37
     */
38
    private static $singular_name = 'Block';
39
40
    private static $icon_class = 'font-icon-help-circled';
41
42
    /**
43
     * Database fields
44
     * @var array
45
     */
46
    private static $db = [
47
        'Anchor' => 'Varchar(16)',
48
        'Title' => 'Varchar(128)',
49
        'TitleDisplayRule' => 'Enum("Show,Sr-only,No output")',
50
    ];
51
52
    /**
53
     * Defines summary fields commonly used in table columns
54
     * as a quick overview of the data for this dataobject
55
     * @var array
56
     */
57
    private static $summary_fields = [
58
        'showID' => 'Anchor',
59
        'singular_name' => 'Type',
60
        'Title' => 'Title',
61
        'BlockSummary' => 'Summary',
62
    ];
63
64
    /**
65
     * Belongs_many_many relationship
66
     * @var array
67
     */
68
    private static $belongs_many_many = [
69
        'Pages' => Page::class,
70
        'FlexBlocks' => FlexBlock::class . '.ModularBlocks'
71
    ];
72
73
    /**
74
     * Defines a default list of filters for the search context
75
     * @var array
76
     */
77
    private static $searchable_fields = [
78
        'Title'
79
    ];
80
81
    /**
82
     * Defines extension names and parameters to be applied
83
     *  to this object upon construction.
84
     *  @var array
85
     */
86
    private static $extensions = [
87
        Versioned::class,
88
    ];
89
90
    public function showID()
91
    {
92
        if (!empty($this->Anchor)) {
93
            return $this->Anchor;
94
        }
95
96
        return strtolower('modular-block-' . $this->ID);
97
    }
98
99
    public function getType()
100
    {
101
        return '<span style="white-space: nowrap; display: flex; align-items: center;">
102
            <i
103
                style="font-size: 24px; display: inline-block; margin-right: 0.25em;"
104
                class="' . $this->config()->icon_class . '"
105
            ></i>' .
106
            $this->singular_name() .
107
        '</span>';
108
    }
109
110
    /**
111
     * CMS Fields
112
     * @return FieldList
113
     */
114
    public function getCMSFields()
115
    {
116
        $fields = parent::getCMSFields();
117
118
        // this is to hold the place for Title field, which we are going to replace with a composite field later
119
        $fields->insertBefore('Title', LiteralField::create('PosHolder', ''));
120
121
        $anchorField = $fields->fieldByName('Root.Main.Anchor');
122
        $titleField = $fields->dataFieldByName('Title');
123
        $ruleField = $fields->dataFieldByName('TitleDisplayRule');
124
125
        $fields->removeByName(['Title', 'Plain', 'Pages', 'FlexBlocks', 'TitleDisplayRule']);
126
127
        $fields->addFieldToTab(
128
            'Root.Main',
129
            CompositeField::create(
130
                [
131
                    $titleField->setTitle(null),
132
                    $ruleField->setTitle(null),
133
                ]
134
            )->setName('ModularTitleHolder')->setTitle('Title'),
135
            'PosHolder'
136
        );
137
138
        $fields->removeByName(['PosHolder']);
139
140
        if (!empty($anchorField)) {
141
            $anchorField
142
                ->setDescription(
143
                    'This will be used as the HTML\'s "id" attribute.
144
                    If left blank, it will fall back to use the block\'s default id' .
145
                    ($this->exists() ? (': modular-block-' . $this->ID) : '')
146
                )
147
            ;
148
149
            $fields->addFieldToTab(
150
                'Root.Configurations',
151
                $anchorField
152
            );
153
        }
154
155
        if ($this->exists()) {
156
            $fields->addFieldToTab(
157
                'Root.Used on Pages',
158
                GridField::create(
159
                    'Pages',
160
                    'Pages',
161
                    $this->Pages(),
162
                    GridFieldConfig_RecordViewer::create()
163
                )
164
            );
165
        }
166
167
        return $fields;
168
    }
169
170
    public function getPlain()
171
    {
172
        return '';
173
    }
174
175
    public function getBlockSummary()
176
    {
177
        return '';
178
    }
179
180
    public function OutputTitle()
181
    {
182
        return $this->TitleDisplayRule !== 'No output';
183
    }
184
185
    public function getCacheInvalidator()
186
    {
187
        $prefix = str_replace('\\', '_' , strtolower(__CLASS__));
188
189
        return $prefix . '__' . ($this->exists() ? ($this->ID . '__' . strtotime($this->LastEdited)) : time());
190
    }
191
192
    public function Renderer($heading = 2)
193
    {
194
        if (!$this->config()->cache_enabled) {
195
            return $this->customise(['Heading' => $heading])->renderWith([$this->ClassName, Block::class]);
196
        }
197
198
        $cache = Injector::inst()->get(CacheInterface::class . '.ModularBlocks');
199
        $key = $this->CacheInvalidator;
200
201
        if ($cache->has($key)) {
202
            return $cache->get($key);
203
        }
204
205
        $html = $this->customise(['Heading' => $heading, 'cached' => true])->renderWith([$this->ClassName, Block::class]);
206
        $cache->set($key, $html);
207
208
        return $html;
209
    }
210
211
    public function getTitleFieldClasses()
212
    {
213
        if (empty($this->TitleDisplayRule) || $this->TitleDisplayRule == 'Show') {
214
            return '';
215
        }
216
217
        return strtolower($this->TitleDisplayRule);
218
    }
219
220
    public function forTemplate()
221
    {
222
        return $this->Renderer();
223
    }
224
225
    public function invalidateCache()
226
    {
227
        Injector::inst()->get(CacheInterface::class . '.ModularBlocks')->delete($this->CacheInvalidator);
228
    }
229
230
    public static function flush()
231
    {
232
        Injector::inst()->get(CacheInterface::class . '.ModularBlocks')->clear();
233
    }
234
235
    /**
236
     * Event handler called after writing to the database.
237
     *
238
     * @uses DataExtension->onAfterWrite()
239
     */
240
    public function onAfterWrite()
241
    {
242
        parent::onAfterWrite();
243
244
        if ($this->FlexBlocks()->exists()) {
245
            foreach ($this->FlexBlocks() as $flexblock) {
246
                $flexblock->invalidateCache();
247
            }
248
        }
249
    }
250
}
251