1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Astrotomic\Stancy\Models; |
4
|
|
|
|
5
|
|
|
use Astrotomic\Stancy\Contracts\Sitemapable; |
6
|
|
|
use DateTime; |
7
|
|
|
use Exception; |
8
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
9
|
|
|
use Spatie\DataTransferObject\DataTransferObject; |
10
|
|
|
use Spatie\Feed\Feedable; |
11
|
|
|
use Spatie\Feed\FeedItem; |
12
|
|
|
use Spatie\Sitemap\Tags\Tag; |
13
|
|
|
|
14
|
|
|
abstract class PageData extends DataTransferObject implements Arrayable, Feedable, Sitemapable |
15
|
|
|
{ |
16
|
21 |
|
public static function make(array $data): self |
|
|
|
|
17
|
|
|
{ |
18
|
21 |
|
return new static($data); |
19
|
|
|
} |
20
|
|
|
|
21
|
1 |
|
public function toFeedItem(): FeedItem |
22
|
|
|
{ |
23
|
1 |
|
throw new Exception(sprintf('You have to define the transformation to a valid %s yourself if you want to use a feed.', FeedItem::class)); |
24
|
|
|
} |
25
|
|
|
|
26
|
1 |
|
public function toSitemapItem(): Tag |
27
|
|
|
{ |
28
|
1 |
|
throw new Exception(sprintf('You have to define the transformation to a valid %s yourself if you want to use a sitemap.', Tag::class)); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
// ToDo: https://github.com/spatie/data-transfer-object/issues/64 |
32
|
3 |
|
protected function parseArray(array $array): array |
|
|
|
|
33
|
|
|
{ |
34
|
3 |
|
foreach ($array as $key => $value) { |
35
|
3 |
|
if ($this->isDateTime($value)) { |
36
|
1 |
|
$array[$key] = $value->format(DATE_RFC3339); |
37
|
|
|
|
38
|
1 |
|
continue; |
39
|
|
|
} |
40
|
|
|
|
41
|
3 |
|
if ($this->isArrayable($value)) { |
42
|
1 |
|
$array[$key] = $value->toArray(); |
43
|
|
|
|
44
|
1 |
|
continue; |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
if ($this->isStringable($value)) { |
48
|
3 |
|
$array[$key] = $value->__toString(); |
49
|
|
|
|
50
|
3 |
|
continue; |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
if (is_array($value)) { |
54
|
3 |
|
$array[$key] = $this->parseArray($value); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
return $array; |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
protected function isDateTime($value): bool |
|
|
|
|
62
|
|
|
{ |
63
|
3 |
|
return $value instanceof DateTime; |
64
|
|
|
} |
65
|
|
|
|
66
|
3 |
|
protected function isArrayable($value): bool |
|
|
|
|
67
|
|
|
{ |
68
|
3 |
|
return $this->isObjectWithMethod($value, 'toArray'); |
69
|
|
|
} |
70
|
|
|
|
71
|
3 |
|
protected function isStringable($value): bool |
|
|
|
|
72
|
|
|
{ |
73
|
3 |
|
return $this->isObjectWithMethod($value, '__toString'); |
74
|
|
|
} |
75
|
|
|
|
76
|
3 |
|
protected function isObjectWithMethod($value, string $method): bool |
|
|
|
|
77
|
|
|
{ |
78
|
3 |
|
return is_object($value) && method_exists($value, $method) && is_callable([$value, $method]); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|