-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathInternalBaseBlock.php
698 lines (618 loc) · 17.8 KB
/
InternalBaseBlock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
<?php
namespace luya\cms\base;
use luya\admin\base\TypesInterface;
use luya\cms\frontend\blockgroups\MainGroup;
use luya\helpers\ArrayHelper;
use luya\helpers\FileHelper;
use luya\helpers\Html;
use luya\helpers\Url;
use yii\base\BaseObject;
use yii\helpers\Inflector;
/**
* Concret Block implementation based on BlockInterface.
*
* This is an use case for the block implemenation as InternBaseBlock fro
* two froms of implementations.
*
* + {{\luya\cms\base\PhpBlock}}
*
* @author Basil Suter <basil@nadar.io>
* @since 1.0.0
*/
abstract class InternalBaseBlock extends BaseObject implements BlockInterface, TypesInterface, \ArrayAccess
{
/**
* @var string Defines the injector config type `var`.
*/
public const INJECTOR_VAR = 'var';
/**
* @var string Defines the injector config type `cfg`.
*/
public const INJECTOR_CFG = 'cfg';
/**
* @var bool Enable or disable the block caching
*/
public $cacheEnabled = false;
/**
* @var int The cache lifetime for this block in seconds (3600 = 1 hour), only affects when cacheEnabled is true. 0 means never expire.
*/
public $cacheExpiration = 3600;
/**
* @var bool Choose whether block is a layout/container/segmnet/section block or not, Container elements will be optically displayed
* in a different way for a better user experience. Container block will not display isDirty colorizing.
*/
public $isContainer = false;
/**
* @var string Containing the name of the environment (used to find the view files to render). The
* module(Name) can be started with the Yii::getAlias() prefix `@`, otherwhise the `@` will be
* added automatically. Since version 3.1.0 its possible to set `null` or empty string in order to lookup
* view files in the same folder where the block is located. With version 4.0 null is the default value.
*
* - `app`: The alias mode allows you to map the view files to a certain alias
* - `@app`: Either alias with prefixed @ or not is possible
* - `null`: Empty or null will lookup the view files in the same folder where block is located (sub folder views).
*/
public $module = null;
/**
* Returns the configuration array.
*
* An array with either `var`, `cfg` or `placeholder`. An example with vars
* with a required text input:
*
* ```php
* return [
* 'vars' => [
* [
* 'var' => 'userInputText',
* 'label' => 'Description of userInputText',
* 'type' => self::TYPE_TEXT,
* 'required' => true,
* ]
* ]
* ];
* ```
*
* @see [[app-block-types.md]]
* @return array
*/
abstract public function config();
/**
* {@inheritDoc}
*/
public function setup()
{
}
private $_injectorObjects;
/**
* Setup injectors.
*/
protected function injectorSetup()
{
if ($this->_injectorObjects === null) {
foreach ($this->injectors() as $varName => $injector) {
$injector->setContext($this);
$injector->varName = $varName;
$injector->setup();
$this->_injectorObjects[$injector->varName] = $injector;
}
}
}
/**
* {@inheritDoc}
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->_injectorObjects[$offset] = $value;
}
/**
* {@inheritDoc}
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->_injectorObjects[$offset]);
}
/**
* {@inheritDoc}
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
unset($this->_injectorObjects[$offset]);
}
/**
* Array Access Get
*
* @param string $offset The name of the registered Injector name.
* @return \luya\cms\base\BaseBlockInjector
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->_injectorObjects[$offset] ?? null;
}
/**
* @inheritdoc
*/
public function getIsCacheEnabled()
{
return $this->cacheEnabled;
}
/**
* @inheritdoc
*/
public function getCacheExpirationTime()
{
return $this->cacheExpiration;
}
/**
* @inheritdoc
*/
public function getIsDirtyDialogEnabled()
{
return true;
}
/**
* @inheritdoc
*/
public function getIsContainer()
{
return $this->isContainer;
}
/**
* Contains the class name for the block group class
*
* @return string The classname on which the block should be stored in.
* @since 1.0.0
*/
public function blockGroup()
{
return MainGroup::class;
}
/**
* Injectors are like huge helper objects which are going to automate functions, configs and variable assignement.
*
* An example of an Injector which builds a select dropdown and assigns the active query data into the extra vars `foobar`.
*
* ```php
* public function injectors()
* {
* return [
* 'foobar' => new cms\injector\ActiveQueryCheckboxInjector([
* 'query' => MyModel::find()->where(['id' => 1]),
* 'type' => self::INJECTOR_VAR, // could be self::INJECTOR_CFG,
* 'varLabel' => 'The Field Label',
* ]);
* ];
* }
* ```
*
* Now the generated injector ActiveQueryCheckbox is going to grab all informations from the defined query and assign
* them into the extra var foobar. Now you can access `$this->extraValue('foobar')` which returns all seleced rows from the checkbox
* you have assigend.
*
* In order to access the injectors object api you can use the ArrayAccess getter method like `$this['foobar']` and you can access the public
* method for this Injector.
*/
public function injectors()
{
return [];
}
/**
* Return link for usage in ajax request, the link will call the defined callback inside
* this block. All callback methods must start with `callback`. An example for a callback method:.
*
* ```php
* public function callbackTestAjax($arg1)
* {
* return 'hello callback test ajax with argument: arg1 ' . $arg1;
* }
* ```
*
* The above defined callback link can be created with the follow code:
*
* ```php
* $this->createAjaxLink('TestAjax', ['arg1' => 'My Value for Arg1']);
* ```
*
* The most convient way to assign the variable is via extraVars
*
* ```php
* public function extraVars()
* {
* return [
* 'ajaxLinkToTestAjax' => $this->createAjaxLink('TestAjax', ['arg1' => 'Value for Arg1']),
* ];
* }
* ```
*
* @param string $callbackName The callback name in uppercamelcase to call. The method must exists in the block class.
* @param array $params A list of parameters who have to match the argument list in the method.
*
* @return string
*/
public function createAjaxLink($callbackName, array $params = [])
{
$params['callback'] = Inflector::camel2id($callbackName);
$params['id'] = $this->getEnvOption('id', 0);
return Url::toAjax('cms/block/index', $params);
}
/**
* Contains the icon
*/
public function icon()
{
return;
}
/**
* Returns true if block is active in backend.
*
* @return bool
*/
public function isAdminContext()
{
return ($this->getEnvOption('context', false) === 'admin') ? true : false;
}
/**
* Returns true if block is active in frontend.
*
* @return bool
*/
public function isFrontendContext()
{
return ($this->getEnvOption('context', false) === 'frontend') ? true : false;
}
private array $_envOptions = [];
/**
* Sets a key => value pair in env options.
*
* @param string $key The string to be set as key
* @param mixed $value The value that will be stored associated with the given key
*/
public function setEnvOption($key, $value)
{
$this->_envOptions[$key] = $value;
}
/**
* Returns all environment/context informations where the block have been placed.
*
* @see {{PhpBlockView::env()}} for all possible values.
* @return array Returns an array with key value parings.
*/
public function getEnvOptions()
{
return $this->_envOptions;
}
/**
* Get a env option by $key. If $key does not exist it will return given $default or false.
*
* @param $key
*
* @return mixed
*/
public function getEnvOption($key, mixed $default = false)
{
return (array_key_exists($key, $this->_envOptions)) ? $this->_envOptions[$key] : $default;
}
private array $_placeholderValues = [];
/**
* @inheritdoc
*/
public function setPlaceholderValues(array $placeholders)
{
$this->_placeholderValues = $placeholders;
}
/**
* @inheritdoc
*/
public function getPlaceholderValues()
{
return $this->_placeholderValues;
}
/**
*
* @param unknown $placholder
* @return boolean
*/
public function getPlaceholderValue($placholder)
{
return $this->getPlaceholderValues()[$placholder] ?? false;
}
private array $_varValues = [];
/**
* @inheritdoc
*/
public function setVarValues(array $values)
{
foreach ($values as $key => $value) {
$this->_varValues[$key] = $value;
}
}
/**
*
* @return array
*/
public function getVarValues()
{
return $this->_varValues;
}
/**
* Get var value.
*
* If the key does not exist in the array, is an empty string or null the default value will be returned.
*
* @param string $key The name of the key you want to retrieve
* @param mixed $default A default value that will be returned if the key isn't found or empty.
* @return mixed
*/
public function getVarValue($key, mixed $default = false)
{
return (isset($this->_varValues[$key]) && $this->_varValues[$key] != '') ? $this->_varValues[$key] : $default;
}
private array $_cfgValues = [];
/**
* @inheritdoc
*/
public function setCfgValues(array $values)
{
foreach ($values as $key => $value) {
$this->_cfgValues[$key] = $value;
}
}
/**
*
* @return array
*/
public function getCfgValues()
{
return $this->_cfgValues;
}
/**
* Get cfg value.
*
* If the key does not exist in the array, is an empty string or null the default value will be returned.
*
* @param string $key The name of the key you want to retrieve
* @param mixed $default A default value that will be returned if the key isn't found or empty.
* @return mixed
*/
public function getCfgValue($key, mixed $default = false)
{
return (isset($this->_cfgValues[$key]) && $this->_cfgValues[$key] != '') ? $this->_cfgValues[$key] : $default;
}
/**
* Define additional variables.
*
* @return array
*/
public function extraVars()
{
return [];
}
/**
* Add an extra var entry.
*
* If the extra var is defined in extraVars() the key will be overriden.
* @param string $key
* @param mixed $value
*/
public function addExtraVar($key, mixed $value)
{
$this->_extraVars[$key] = $value;
}
private array $_extraVars = [];
/**
* @inheritdoc
*/
public function getExtraVarValues()
{
$this->_extraVars = ArrayHelper::merge($this->extraVars(), $this->_extraVars);
return $this->_extraVars;
}
private bool $_assignExtraVars = false;
/**
*
* @param string $key
* @param string $default
* @return string|mixed
*/
public function getExtraValue($key, $default = false)
{
if (!$this->_assignExtraVars) {
$this->getExtraVarValues();
$this->_assignExtraVars = true;
}
return $this->_extraVars[$key] ?? $default;
}
/**
* Returns an array with additional help informations for specific field (var or cfg).
*
* @return array An array where the key is the cfg/var field var name and the value the helper text.
*/
public function getFieldHelp()
{
return [];
}
private array $_vars = [];
/**
* @inheritdoc
*/
public function getConfigVarsExport()
{
$config = $this->config();
if (isset($config['vars'])) {
foreach ($config['vars'] as $item) {
$iteration = count($this->_vars) + 500;
$this->_vars[$iteration] = (new BlockVar($item))->toArray();
}
}
ksort($this->_vars);
return array_values($this->_vars);
}
/**
* Add a var variable to the config.
*
* @param boolean Whether the variable should be append to the end instead of prepanding.
*/
public function addVar(array $varConfig, $append = false)
{
$count = count($this->_vars);
$iteration = $append ? $count + 1000 : $count;
$this->_vars[$iteration] = (new BlockVar($varConfig))->toArray();
}
/**
* @inheritdoc
*/
public function getConfigPlaceholdersExport()
{
$array = array_key_exists('placeholders', $this->config()) ? $this->config()['placeholders'] : [];
$holders = [];
foreach ($array as $holder) {
if (isset($holder['var'])) {
$holders[] = $holder;
} else {
foreach ($holder as $columnHolder) {
$holders[] = $columnHolder;
}
}
}
return $holders;
}
/**
* @inheritdoc
*/
public function getConfigPlaceholdersByRowsExport()
{
$array = array_key_exists('placeholders', $this->config()) ? $this->config()['placeholders'] : [];
$rows = [];
foreach ($array as $holder) {
if (isset($holder['var'])) {
$holder['cols'] = 12;
$rows[] = [$holder];
} else {
$rows[] = $holder;
}
}
return $rows;
}
private array $_cfgs = [];
/**
* @inheritdoc
*/
public function getConfigCfgsExport()
{
$config = $this->config();
if (isset($config['cfgs'])) {
foreach ($config['cfgs'] as $item) {
$iteration = count($this->_cfgs) + 500;
$this->_cfgs[$iteration] = (new BlockCfg($item))->toArray();
}
}
ksort($this->_cfgs);
return array_values($this->_cfgs);
}
/**
* Add a cfg variable to the config.
*
* @param boolean Whether the variable should be append to the end instead of prepanding.
*/
public function addCfg(array $cfgConfig, $append = false)
{
$count = count($this->_cfgs);
$iteration = $append ? $count + 1000 : $count;
$this->_cfgs[$iteration] = (new BlockCfg($cfgConfig))->toArray();
}
/**
* Returns the name of the php file to be rendered.
*
* @return string The name of the php file (example.php)
*/
public function getViewFileName($extension)
{
$className = $this::class;
if (preg_match('/\\\\([\w]+)$/', $className, $matches)) {
$className = $matches[1];
}
return $className.'.'.$extension;
}
/**
* Make sure the module contains its alias prefix @
*
* @return string The module name with alias prefix @.
*/
protected function ensureModule()
{
$moduleName = $this->module;
if (!str_starts_with($moduleName, '@')) {
$moduleName = '@'.$moduleName;
}
return $moduleName;
}
/**
* Configure Variations.
*
* ```php
* TextBlock::variations()
* ->add('bold', 'Bold Font with Markdown')->cfgs(['cssClass' => 'bold-font-class'])->vars(['textType' => 1])
* ->add('italic', 'Italic Font')->cfgs(['cssClass' => 'italic-font-class'])
* ->register(),
* VideoBlock::variations()
* ->add('bold', 'Bold Videos')->cfgs([])->register(),
* ```
*
* @return \luya\cms\base\BlockVariationRegister
*/
public static function variations()
{
/** @phpstan-ignore-next-line */
return (new BlockVariationRegister(new static()));
}
/**
* @inheritDoc
*/
public function onRegister()
{
}
/**
* @inheritDoc
*/
public function onRegisterFromCache()
{
}
/**
* @inheritDoc
*/
public function renderAdminPreview()
{
$image = $this->getPreviewImageSource();
if ($image) {
return Html::img($image);
}
return false;
}
/**
* Path to the preview image.
* @since 1.0.8
*/
protected function getPreviewImageSource()
{
$imageName = $this->getViewFileName('jpg');
$reflector = new \ReflectionClass($this);
$dirPath = dirname($reflector->getFileName(), 2);
$imagePath = $dirPath . '/images/blocks/' . $imageName;
// file get content resolved Yii aliases.
$data = FileHelper::getFileContent($imagePath);
if ($data) {
return 'data:image/jpg;base64,' . base64_encode($data);
}
return false;
}
/**
* @inheritDoc
*/
public function placeholderRenderIteration(BlockInterface $block)
{
return $block->renderFrontend();
}
}