/
Content.php
634 lines (524 loc) · 16.5 KB
/
Content.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
<?php
declare(strict_types=1);
namespace Bolt\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use Bolt\Configuration\Content\ContentType;
use Bolt\Enum\Statuses;
use Bolt\Repository\FieldRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\MaxDepth;
use Tightenco\Collect\Support\Collection as LaravelCollection;
/**
* @ApiResource(
* normalizationContext={"groups"={"get_content"}},
* collectionOperations={"get"},
* itemOperations={"get"}
* )
* @ApiFilter(SearchFilter::class)
* @ORM\Entity(repositoryClass="Bolt\Repository\ContentRepository")
* @ORM\Table(indexes={
* @ORM\Index(name="content_type_idx", columns={"content_type"}),
* @ORM\Index(name="status_idx", columns={"status"})
* })
* @ORM\HasLifecycleCallbacks
*/
class Content
{
use ContentLocalizeTrait;
use ContentExtrasTrait;
/**
* @var int
*
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
* @Groups("get_content")
*/
private $id;
/**
* @var string
*
* @ORM\Column(type="string", length=191)
* @Groups("get_content")
*/
private $contentType;
/**
* @var User
*
* @ORM\ManyToOne(targetEntity="Bolt\Entity\User", fetch="EAGER")
* @ORM\JoinColumn(nullable=true)
*/
private $author;
/**
* @var string
*
* @ORM\Column(type="string", length=191)
* @Groups("get_content")
*/
private $status;
/**
* @var \DateTime
*
* @ORM\Column(type="datetime")
* @Groups("get_content")
*/
private $createdAt;
/**
* @var \DateTime|null
*
* @ORM\Column(type="datetime", nullable=true)
* @Groups("get_content")
*/
private $modifiedAt = null;
/**
* @var \DateTime|null
*
* @ORM\Column(type="datetime", nullable=true)
* @Groups("get_content")
*/
private $publishedAt = null;
/**
* @var \DateTime|null
*
* @ORM\Column(type="datetime", nullable=true)
* @Groups("get_content")
*/
private $depublishedAt = null;
/**
* @var Collection|Field[]
*
* @ApiSubresource(maxDepth=1)
* @MaxDepth(1)
*
* @ORM\OneToMany(
* targetEntity="Bolt\Entity\Field",
* mappedBy="content",
* indexBy="id",
* fetch="EAGER",
* orphanRemoval=true,
* cascade={"persist"}
* )
* @ORM\OrderBy({"sortorder": "ASC"})
*/
private $fields;
/**
* @var ContentType|null
*/
private $contentTypeDefinition;
/**
* @var Collection|Taxonomy[]
* @MaxDepth(1)
*
* @ORM\ManyToMany(targetEntity="Bolt\Entity\Taxonomy", mappedBy="content", cascade={"persist"})
*/
private $taxonomies;
public function __construct(?ContentType $contentTypeDefinition = null)
{
$this->createdAt = new \DateTime();
$this->taxonomies = new ArrayCollection();
$this->fields = new ArrayCollection();
if ($contentTypeDefinition) {
$this->setContentType($contentTypeDefinition->getSlug());
$this->setDefinition($contentTypeDefinition);
}
}
public function __toString(): string
{
$contentName = $this->getDefinition() ? $this->getContentTypeName() : 'Content';
if ($this->getId()) {
return sprintf('%s #%d', $contentName, $this->getId());
}
return sprintf('New %s', $contentName);
}
public function setId(?int $id = null): void
{
$this->id = $id;
}
public function getId(): ?int
{
return $this->id;
}
/**
* @see \Bolt\Event\Listener\ContentFillListener
*/
public function setDefinitionFromContentTypesConfig(LaravelCollection $contentTypesConfig): void
{
$this->contentTypeDefinition = ContentType::factory($this->contentType, $contentTypesConfig);
}
public function setDefinition(ContentType $contentType): void
{
$this->contentTypeDefinition = $contentType;
}
public function getDefinition(): ?ContentType
{
return $this->contentTypeDefinition;
}
public function getSlug($locale = null): ?string
{
$slug = null;
if ($locale === null) {
// get slug with locale the slug already has
$slug = $this->getFieldValue('slug');
} else {
// get slug with the requested locale
$slug = $this->getField('slug')->setLocale($locale)->getParsedValue();
}
if ($slug === null) {
// if no slug exists for the current/requested locale, default back
$slug = $this
->getField('slug')
->setLocale($this->getField('slug')->getDefaultLocale())
->getParsedValue();
}
return $slug;
}
public function getContentType(): ?string
{
return $this->contentType;
}
public function setContentType(string $contentType): void
{
$this->contentType = $contentType;
}
public function getContentTypeSlug(): string
{
if ($this->getDefinition() === null) {
throw new \RuntimeException('Content not fully initialized');
}
return $this->getDefinition()->get('slug');
}
public function getContentTypeSingularSlug(): string
{
if ($this->getDefinition() === null) {
throw new \RuntimeException('Content not fully initialized');
}
return $this->getDefinition()->get('singular_slug');
}
public function getContentTypeName(): string
{
if ($this->getDefinition() === null) {
throw new \RuntimeException('Content not fully initialized');
}
return $this->getDefinition()->get('singular_name') ?: $this->getContentTypeSlug();
}
public function getIcon(): ?string
{
if ($this->getDefinition() === null) {
throw new \RuntimeException('Content not fully initialized');
}
return $this->getDefinition()->get('icon_one') ?: $this->getDefinition()->get('icon_many');
}
public function getAuthor(): ?User
{
return $this->author;
}
public function setAuthor(?User $author): void
{
$this->author = $author;
}
public function getStatus(): string
{
if (Statuses::isValid($this->status) === false) {
$this->status = $this->getDefinition()->get('default_status');
}
return $this->status;
}
public function setStatus(string $status): self
{
if (Statuses::isValid($status)) {
$this->status = $status;
}
return $this;
}
public function getCreatedAt(): ?\DateTime
{
return $this->convertToLocalFromDatabase($this->createdAt);
}
public function setCreatedAt(?\DateTime $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getModifiedAt(): ?\DateTime
{
return $this->convertToLocalFromDatabase($this->modifiedAt);
}
public function setModifiedAt(?\DateTime $modifiedAt): self
{
$this->modifiedAt = $modifiedAt;
return $this;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function updateModifiedAt(): void
{
$this->setModifiedAt(new \DateTime());
}
public function getPublishedAt(): ?\DateTime
{
return $this->convertToLocalFromDatabase($this->publishedAt);
}
public function setPublishedAt(?\DateTime $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
public function getDepublishedAt(): ?\DateTime
{
return $this->convertToLocalFromDatabase($this->depublishedAt);
}
public function setDepublishedAt(?\DateTime $depublishedAt): self
{
$this->depublishedAt = $depublishedAt;
return $this;
}
/**
* @return Collection|Field[]
*/
public function getRawFields(): Collection
{
return $this->fields;
}
/**
* @return Collection|Field[]
*/
public function getFields(): Collection
{
return $this->standaloneFieldsFilter();
}
/**
* @Groups("get_content")
*/
public function getFieldValues(bool $parsed = true): array
{
$fieldValues = [];
foreach ($this->getFields() as $field) {
$fieldValues[$field->getName()] = $field->getApiValue();
}
return $fieldValues;
}
/**
* @Groups("get_content")
*/
public function getTaxonomyValues(): array
{
$taxonomyValues = [];
foreach ($this->getTaxonomies() as $taxonomy) {
if (isset($taxonomyValues[$taxonomy->getType()]) === false) {
$taxonomyValues[$taxonomy->getType()] = [];
}
$taxonomyValues[$taxonomy->getType()][$taxonomy->getSlug()] = $taxonomy->getName();
}
return $taxonomyValues;
}
/**
* @return array|mixed|null
*/
public function getFieldValue(string $fieldName)
{
if ($this->hasField($fieldName) === false) {
return null;
}
return $this->getField($fieldName)->getParsedValue();
}
public function setFieldValue(string $fieldName, $value): void
{
if (! $this->hasField($fieldName)) {
$this->addFieldByName($fieldName);
}
$field = $this->getField($fieldName);
$field->setValue($value);
}
public function getField(string $fieldName): Field
{
if ($this->hasField($fieldName) === false) {
throw new \InvalidArgumentException(sprintf("Content does not have '%s' field", $fieldName));
}
return $this->standaloneFieldFilter($fieldName)->first();
}
public function hasField(string $fieldName, $matchTypes = false): bool
{
$query = $this->standaloneFieldFilter($fieldName);
// If the field doesn't exist, we can bail here
if ($query->isEmpty()) {
return false;
}
// If $matchTypes is `false`, we can state that we do have the field
if (! $matchTypes) {
return true;
}
// Otherwise, we need to ensure the types are the same
$fieldType = $query->first()->getType();
$definitionType = $this->contentTypeDefinition->get('fields')->get($fieldName)['type'] ?: 'undefined';
return $fieldType === $definitionType;
}
public function hasFieldDefined(string $fieldName): bool
{
return $this->contentTypeDefinition->get('fields')->has($fieldName);
}
public function addField(Field $field): self
{
if (! $field->hasParent() && $this->hasField($field->getName())) {
throw new \InvalidArgumentException(sprintf("Content already has '%s' field", $field->getName()));
}
$this->fields[] = $field;
$field->setContent($this);
return $this;
}
public function addFieldByName(string $fieldName): void
{
$definition = $this->contentTypeDefinition->get('fields')->get($fieldName);
$field = FieldRepository::factory($definition, $fieldName);
$this->addField($field);
}
public function removeField(Field $field): self
{
$this->fields->removeElement($field);
// set the owning side to null (unless already changed)
if ($field->getContent() === $this) {
$field->setContent(null);
}
return $this;
}
/**
* @Groups("get_content")
*/
public function getAuthorName(): ?string
{
if ($this->getAuthor() !== null) {
return $this->getAuthor()->getDisplayName();
}
return null;
}
public function getStatuses(): array
{
return Statuses::all();
}
public function getStatusOptions(): array
{
$options = [];
foreach (Statuses::all() as $option) {
$options[] = [
'key' => $option,
'value' => ucwords($option),
'selected' => $option === $this->getStatus(),
];
}
return $options;
}
public function hasTaxonomyDefined(string $taxonomyName): bool
{
return $this->contentTypeDefinition->get('taxonomy')->contains($taxonomyName);
}
/**
* @return Collection|Taxonomy[]
*/
public function getTaxonomies(?string $type = null): Collection
{
if ($type) {
return $this->taxonomies->filter(
function (Taxonomy $taxonomy) use ($type) {
return $taxonomy->getType() === $type;
}
);
}
return $this->taxonomies;
}
public function addTaxonomy(Taxonomy $taxonomy): self
{
if ($this->taxonomies->contains($taxonomy) === false) {
$this->taxonomies[] = $taxonomy;
$taxonomy->addContent($this);
}
return $this;
}
public function removeTaxonomy(Taxonomy $taxonomy): self
{
if ($this->taxonomies->contains($taxonomy)) {
$this->taxonomies->removeElement($taxonomy);
$taxonomy->removeContent($this);
}
return $this;
}
/**
* Generic getter for a record fields. Will return the field with $name.
*
* If $name is not found, throw an exception if it's invoked from code, and
* return null if invoked from within a template. In templates we need to be
* more lenient, in order to do things like `{% if record.foo %}..{% endif %}
*
* Note: We can not rely on `{% if record.foo is defined %}`, because it
* always returns `true` for object properties.
* See: https://craftcms.stackexchange.com/questions/2116/twig-is-defined-always-returning-true
*
* - {{ record.title }} => field named title
* - {{ record|title }} => value of guessed title field
* - {{ record.image }} => field named image
* - {{ record|image }} => value of guessed image field
*/
public function __call(string $name, array $arguments = [])
{
try {
$field = $this->getField($name);
} catch (\InvalidArgumentException $e) {
$backtrace = new LaravelCollection($e->getTrace());
if ($backtrace->contains('class', \Twig\Template::class)) {
// Invoked from within a Template render, so be lenient.
return null;
}
// Invoked from code, throw Exception
throw new \RuntimeException(sprintf('Invalid field name or method call on %s: %s', $this->__toString(), $name));
}
return $field->getTwigValue();
}
/**
* All date/timestamps are stored in the database in UTC. When retrieving
* them, we get the timestamp as-is in the DB with the current local
* timezone slapped onto it. This method converts it back to UTC, and
* then re-applies the current local timezone to it.
*/
private function convertToLocalFromDatabase(?\DateTime $dateTime): ?\DateTime
{
if (! $dateTime) {
return null;
}
$dateTimeUTC = new \DateTime($dateTime->format('Y-m-d H:i:s'), new \DateTimeZone('UTC'));
return $dateTimeUTC->setTimezone($dateTime->getTimezone());
}
private function standaloneFieldsFilter()
{
return $this->fields->filter(function (Field $field) {
return ! $field->hasParent();
});
}
private function standaloneFieldFilter(string $fieldName)
{
return $this->fields->filter(function (Field $field) use ($fieldName) {
return $field->getName() === $fieldName && ! $field->hasParent();
});
}
public function toArray(): array
{
$result = get_object_vars($this);
if ($this->author !== null) {
$result['author'] = [
'id' => $this->author->getId(),
'username' => $this->author->getUsername(),
];
}
$result['fields'] = $this->getFieldValues(false);
$result['taxonomies'] = $this->getTaxonomyValues();
$result['relations'] = [];
unset($result['contentTypeDefinition']);
unset($result['contentExtension']);
return $result;
}
}