/
EmbedContainer.php
138 lines (118 loc) · 2.99 KB
/
EmbedContainer.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
<?php
namespace SilverStripe\View\Embed;
use Embed\Extractor;
use Embed\Embed;
use Psr\Http\Message\UriInterface;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Manifest\ModuleResourceLoader;
/**
* This class acts as a wrapper around the third party requirement embed/embed v4
*/
class EmbedContainer implements Embeddable
{
use Injectable;
private static $dependencies = [
'embed' => '%$' . Embed::class,
];
public Embed $embed;
private ?Extractor $extractor = null;
private string $url;
private array $options = [];
public function __construct(string $url)
{
$this->url = $url;
}
/**
* @return int
*/
public function getWidth()
{
$code = $this->getExtractor()->code;
return $code ? ($code->width ?: 100) : 100;
}
/**
* @return int
*/
public function getHeight()
{
$code = $this->getExtractor()->code;
return $code ? ($code->height ?: 100) : 100;
}
/**
* @return string
*/
public function getPreviewURL()
{
$extractor = $this->getExtractor();
// Use thumbnail url
if ($extractor->image) {
return (string) $extractor->image;
}
// Default media
return ModuleResourceLoader::resourceURL(
'silverstripe/asset-admin:client/dist/images/icon_file.png'
);
}
/**
* @return string
*/
public function getName()
{
$extractor = $this->getExtractor();
if ($extractor->title) {
return $extractor->title;
}
if ($extractor->url instanceof UriInterface) {
return basename($extractor->url->getPath() ?? '');
}
return '';
}
/**
* @return string
*/
public function getType()
{
$html = $this->getExtractor()->code->html ?? '';
if (strpos($html ?? '', '<video') !== false) {
return 'video';
}
if (strpos($html ?? '', '<audio') !== false) {
return 'audio';
}
foreach (['iframe', 'blockquote', 'pre', 'script', 'style'] as $richTag) {
if (strpos($html ?? '', "<{$richTag}") !== false) {
return 'rich';
}
}
if (strpos($html ?? '', '<img') !== false) {
return 'photo';
}
return 'link';
}
/**
* @return bool
*/
public function validate()
{
return !empty($this->getExtractor()->code->html ?? '');
}
public function getOptions(): array
{
return $this->options;
}
public function setOptions(array $options): self
{
$this->options = $options;
return $this;
}
/**
* Calling this method will trigger the HTTP call(s) to the remote url
*/
public function getExtractor(): Extractor
{
if (!$this->extractor) {
$this->extractor = $this->embed->get($this->url);
}
return $this->extractor;
}
}