-
Notifications
You must be signed in to change notification settings - Fork 12
/
Crawler.php
executable file
·70 lines (60 loc) · 1.35 KB
/
Crawler.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
<?php
namespace yii2mod\linkpreview;
use Embed\Adapters\Adapter;
use Embed\Embed;
use Embed\Exceptions\InvalidUrlException;
use yii\base\InvalidConfigException;
use yii\base\Object;
use yii\helpers\ArrayHelper;
/**
* Class Crawler
*
* @package yii2mod\linkpreview
*/
class Crawler extends Object
{
/**
* @var string content given from the widget
*/
public $content;
/**
* @var array Embed config
*/
public $config = [];
/**
* @var string url regex
*/
public $regexUrl = '/https?\:\/\/[^\" ]+/i';
/**
* Return page info
*
* @return array|Adapter
*
* @throws InvalidConfigException
*/
public function getPageInfo()
{
if (empty($this->content)) {
throw new InvalidConfigException("The 'content' property is required.");
}
$url = $this->getUrlFromContent();
if (!empty($url)) {
try {
return Embed::create($url, $this->config);
} catch (InvalidUrlException $e) {
// Invalid url
}
}
return [];
}
/**
* Get link from content
*
* @return mixed|null
*/
protected function getUrlFromContent()
{
preg_match($this->regexUrl, $this->content, $matches);
return ArrayHelper::getValue($matches, 0);
}
}