/
ModelWithContent.php
699 lines (611 loc) · 18.8 KB
/
ModelWithContent.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
699
<?php
namespace Kirby\Cms;
use Closure;
use Kirby\Data\Data;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Form\Form;
use Kirby\Toolkit\Str;
use Throwable;
/**
* ModelWithContent
*
* @package Kirby Cms
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier GmbH
* @license https://getkirby.com/license
*/
abstract class ModelWithContent extends Model
{
/**
* The content
*
* @var \Kirby\Cms\Content
*/
public $content;
/**
* @var \Kirby\Cms\Translations
*/
public $translations;
/**
* Returns the blueprint of the model
*
* @return \Kirby\Cms\Blueprint
*/
abstract public function blueprint();
/**
* Returns an array with all blueprints that are available
*
* @param string|null $inSection
* @return array
*/
public function blueprints(string $inSection = null): array
{
$blueprints = [];
$blueprint = $this->blueprint();
$sections = $inSection !== null ? [$blueprint->section($inSection)] : $blueprint->sections();
foreach ($sections as $section) {
if ($section === null) {
continue;
}
foreach ((array)$section->blueprints() as $blueprint) {
$blueprints[$blueprint['name']] = $blueprint;
}
}
return array_values($blueprints);
}
/**
* Executes any given model action
*
* @param string $action
* @param array $arguments
* @param \Closure $callback
* @return mixed
*/
abstract protected function commit(string $action, array $arguments, Closure $callback);
/**
* Returns the content
*
* @param string|null $languageCode
* @return \Kirby\Cms\Content
* @throws \Kirby\Exception\InvalidArgumentException If the language for the given code does not exist
*/
public function content(string $languageCode = null)
{
// single language support
if ($this->kirby()->multilang() === false) {
if (is_a($this->content, 'Kirby\Cms\Content') === true) {
return $this->content;
}
return $this->setContent($this->readContent())->content;
// multi language support
} else {
// only fetch from cache for the default language
if ($languageCode === null && is_a($this->content, 'Kirby\Cms\Content') === true) {
return $this->content;
}
// get the translation by code
if ($translation = $this->translation($languageCode)) {
$content = new Content($translation->content(), $this);
} else {
throw new InvalidArgumentException('Invalid language: ' . $languageCode);
}
// only store the content for the current language
if ($languageCode === null) {
$this->content = $content;
}
return $content;
}
}
/**
* Returns the absolute path to the content file
*
* @internal
* @param string|null $languageCode
* @param bool $force
* @return string
* @throws \Kirby\Exception\InvalidArgumentException If the language for the given code does not exist
*/
public function contentFile(string $languageCode = null, bool $force = false): string
{
$extension = $this->contentFileExtension();
$directory = $this->contentFileDirectory();
$filename = $this->contentFileName();
// overwrite the language code
if ($force === true) {
if (empty($languageCode) === false) {
return $directory . '/' . $filename . '.' . $languageCode . '.' . $extension;
} else {
return $directory . '/' . $filename . '.' . $extension;
}
}
// add and validate the language code in multi language mode
if ($this->kirby()->multilang() === true) {
if ($language = $this->kirby()->languageCode($languageCode)) {
return $directory . '/' . $filename . '.' . $language . '.' . $extension;
} else {
throw new InvalidArgumentException('Invalid language: ' . $languageCode);
}
} else {
return $directory . '/' . $filename . '.' . $extension;
}
}
/**
* Returns an array with all content files
*
* @return array
*/
public function contentFiles(): array
{
if ($this->kirby()->multilang() === true) {
$files = [];
foreach ($this->kirby()->languages()->codes() as $code) {
$files[] = $this->contentFile($code);
}
return $files;
} else {
return [
$this->contentFile()
];
}
}
/**
* Prepares the content that should be written
* to the text file
*
* @internal
* @param array $data
* @param string|null $languageCode
* @return array
*/
public function contentFileData(array $data, string $languageCode = null): array
{
return $data;
}
/**
* Returns the absolute path to the
* folder in which the content file is
* located
*
* @internal
* @return string|null
*/
public function contentFileDirectory(): ?string
{
return $this->root();
}
/**
* Returns the extension of the content file
*
* @internal
* @return string
*/
public function contentFileExtension(): string
{
return $this->kirby()->contentExtension();
}
/**
* Needs to be declared by the final model
*
* @internal
* @return string
*/
abstract public function contentFileName(): string;
/**
* Decrement a given field value
*
* @param string $field
* @param int $by
* @param int $min
* @return static
*/
public function decrement(string $field, int $by = 1, int $min = 0)
{
$value = (int)$this->content()->get($field)->value() - $by;
if ($value < $min) {
$value = $min;
}
return $this->update([$field => $value]);
}
/**
* Returns all content validation errors
*
* @return array
*/
public function errors(): array
{
$errors = [];
foreach ($this->blueprint()->sections() as $section) {
$errors = array_merge($errors, $section->errors());
}
return $errors;
}
/**
* Increment a given field value
*
* @param string $field
* @param int $by
* @param int|null $max
* @return static
*/
public function increment(string $field, int $by = 1, int $max = null)
{
$value = (int)$this->content()->get($field)->value() + $by;
if ($max && $value > $max) {
$value = $max;
}
return $this->update([$field => $value]);
}
/**
* Checks if the model is locked for the current user
*
* @return bool
*/
public function isLocked(): bool
{
$lock = $this->lock();
return $lock && $lock->isLocked() === true;
}
/**
* Checks if the data has any errors
*
* @return bool
*/
public function isValid(): bool
{
return Form::for($this)->hasErrors() === false;
}
/**
* Returns the lock object for this model
*
* Only if a content directory exists,
* virtual pages will need to overwrite this method
*
* @return \Kirby\Cms\ContentLock|null
*/
public function lock()
{
$dir = $this->contentFileDirectory();
if (
$this->kirby()->option('content.locking', true) &&
is_string($dir) === true &&
file_exists($dir) === true
) {
return new ContentLock($this);
}
}
/**
* Returns the panel info of the model
* @since 3.6.0
*
* @return \Kirby\Panel\Model
*/
abstract public function panel();
/**
* Must return the permissions object for the model
*
* @return \Kirby\Cms\ModelPermissions
*/
abstract public function permissions();
/**
* Creates a string query, starting from the model
*
* @internal
* @param string|null $query
* @param string|null $expect
* @return mixed
*/
public function query(string $query = null, string $expect = null)
{
if ($query === null) {
return null;
}
try {
$result = Str::query($query, [
'kirby' => $this->kirby(),
'site' => is_a($this, 'Kirby\Cms\Site') ? $this : $this->site(),
static::CLASS_ALIAS => $this
]);
} catch (Throwable $e) {
return null;
}
if ($expect !== null && is_a($result, $expect) !== true) {
return null;
}
return $result;
}
/**
* Read the content from the content file
*
* @internal
* @param string|null $languageCode
* @return array
*/
public function readContent(string $languageCode = null): array
{
try {
return Data::read($this->contentFile($languageCode));
} catch (Throwable $e) {
return [];
}
}
/**
* Returns the absolute path to the model
*
* @return string|null
*/
abstract public function root(): ?string;
/**
* Stores the content on disk
*
* @internal
* @param array|null $data
* @param string|null $languageCode
* @param bool $overwrite
* @return static
*/
public function save(array $data = null, string $languageCode = null, bool $overwrite = false)
{
if ($this->kirby()->multilang() === true) {
return $this->saveTranslation($data, $languageCode, $overwrite);
} else {
return $this->saveContent($data, $overwrite);
}
}
/**
* Save the single language content
*
* @param array|null $data
* @param bool $overwrite
* @return static
*/
protected function saveContent(array $data = null, bool $overwrite = false)
{
// create a clone to avoid modifying the original
$clone = $this->clone();
// merge the new data with the existing content
$clone->content()->update($data, $overwrite);
// send the full content array to the writer
$clone->writeContent($clone->content()->toArray());
return $clone;
}
/**
* Save a translation
*
* @param array|null $data
* @param string|null $languageCode
* @param bool $overwrite
* @return static
* @throws \Kirby\Exception\InvalidArgumentException If the language for the given code does not exist
*/
protected function saveTranslation(array $data = null, string $languageCode = null, bool $overwrite = false)
{
// create a clone to not touch the original
$clone = $this->clone();
// fetch the matching translation and update all the strings
$translation = $clone->translation($languageCode);
if ($translation === null) {
throw new InvalidArgumentException('Invalid language: ' . $languageCode);
}
// get the content to store
$content = $translation->update($data, $overwrite)->content();
$kirby = $this->kirby();
$languageCode = $kirby->languageCode($languageCode);
// remove all untranslatable fields
if ($languageCode !== $kirby->defaultLanguage()->code()) {
foreach ($this->blueprint()->fields() as $field) {
if (($field['translate'] ?? true) === false) {
$content[$field['name']] = null;
}
}
// merge the translation with the new data
$translation->update($content, true);
}
// send the full translation array to the writer
$clone->writeContent($translation->content(), $languageCode);
// reset the content object
$clone->content = null;
// return the updated model
return $clone;
}
/**
* Sets the Content object
*
* @param array|null $content
* @return $this
*/
protected function setContent(array $content = null)
{
if ($content !== null) {
$content = new Content($content, $this);
}
$this->content = $content;
return $this;
}
/**
* Create the translations collection from an array
*
* @param array|null $translations
* @return $this
*/
protected function setTranslations(array $translations = null)
{
if ($translations !== null) {
$this->translations = new Collection();
foreach ($translations as $props) {
$props['parent'] = $this;
$translation = new ContentTranslation($props);
$this->translations->data[$translation->code()] = $translation;
}
}
return $this;
}
/**
* String template builder with automatic HTML escaping
* @since 3.6.0
*
* @param string|null $template Template string or `null` to use the model ID
* @param array $data
* @param string $fallback Fallback for tokens in the template that cannot be replaced
* @return string
*/
public function toSafeString(string $template = null, array $data = [], string $fallback = ''): string
{
return $this->toString($template, $data, $fallback, 'safeTemplate');
}
/**
* String template builder
*
* @param string|null $template Template string or `null` to use the model ID
* @param array $data
* @param string $fallback Fallback for tokens in the template that cannot be replaced
* @param string $handler For internal use
* @return string
*/
public function toString(string $template = null, array $data = [], string $fallback = '', string $handler = 'template'): string
{
if ($template === null) {
return $this->id() ?? '';
}
if ($handler !== 'template' && $handler !== 'safeTemplate') {
throw new InvalidArgumentException('Invalid toString handler'); // @codeCoverageIgnore
}
$result = Str::$handler($template, array_replace([
'kirby' => $this->kirby(),
'site' => is_a($this, 'Kirby\Cms\Site') ? $this : $this->site(),
static::CLASS_ALIAS => $this
], $data), ['fallback' => $fallback]);
return $result;
}
/**
* Returns a single translation by language code
* If no code is specified the current translation is returned
*
* @param string|null $languageCode
* @return \Kirby\Cms\ContentTranslation|null
*/
public function translation(string $languageCode = null)
{
return $this->translations()->find($languageCode ?? $this->kirby()->language()->code());
}
/**
* Returns the translations collection
*
* @return \Kirby\Cms\Collection
*/
public function translations()
{
if ($this->translations !== null) {
return $this->translations;
}
$this->translations = new Collection();
foreach ($this->kirby()->languages() as $language) {
$translation = new ContentTranslation([
'parent' => $this,
'code' => $language->code(),
]);
$this->translations->data[$translation->code()] = $translation;
}
return $this->translations;
}
/**
* Updates the model data
*
* @param array|null $input
* @param string|null $languageCode
* @param bool $validate
* @return static
* @throws \Kirby\Exception\InvalidArgumentException If the input array contains invalid values
*/
public function update(array $input = null, string $languageCode = null, bool $validate = false)
{
$form = Form::for($this, [
'ignoreDisabled' => $validate === false,
'input' => $input,
'language' => $languageCode,
]);
// validate the input
if ($validate === true) {
if ($form->isInvalid() === true) {
throw new InvalidArgumentException([
'fallback' => 'Invalid form with errors',
'details' => $form->errors()
]);
}
}
$arguments = [static::CLASS_ALIAS => $this, 'values' => $form->data(), 'strings' => $form->strings(), 'languageCode' => $languageCode];
return $this->commit('update', $arguments, function ($model, $values, $strings, $languageCode) {
// save updated values
$model = $model->save($strings, $languageCode, true);
// update model in siblings collection
$model->siblings()->add($model);
return $model;
});
}
/**
* Low level data writer method
* to store the given data on disk or anywhere else
*
* @internal
* @param array $data
* @param string|null $languageCode
* @return bool
*/
public function writeContent(array $data, string $languageCode = null): bool
{
return Data::write(
$this->contentFile($languageCode),
$this->contentFileData($data, $languageCode)
);
}
/**
* Deprecated!
*/
/**
* Returns the panel icon definition
*
* @deprecated 3.6.0 Use `->panel()->image()` instead
* @todo Add `deprecated()` helper warning in 3.7.0
* @todo Remove in 3.8.0
*
* @internal
* @param array|null $params
* @return array|null
* @codeCoverageIgnore
*/
public function panelIcon(array $params = null): ?array
{
return $this->panel()->image($params);
}
/**
* @deprecated 3.6.0 Use `->panel()->image()` instead
* @todo Add `deprecated()` helper warning in 3.7.0
* @todo Remove in 3.8.0
*
* @internal
* @param string|array|false|null $settings
* @return array|null
* @codeCoverageIgnore
*/
public function panelImage($settings = null): ?array
{
return $this->panel()->image($settings);
}
/**
* Returns an array of all actions
* that can be performed in the Panel
* This also checks for the lock status
*
* @deprecated 3.6.0 Use `->panel()->options()` instead
* @todo Add `deprecated()` helper warning in 3.7.0
* @todo Remove in 3.8.0
*
* @param array $unlock An array of options that will be force-unlocked
* @return array
* @codeCoverageIgnore
*/
public function panelOptions(array $unlock = []): array
{
return $this->panel()->options($unlock);
}
}