-
Notifications
You must be signed in to change notification settings - Fork 1
/
OpenGraph.php
97 lines (87 loc) · 2.59 KB
/
OpenGraph.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
<?php
namespace fgh151\opengraph;
use Yii;
use yii\web\View;
/**
*
* Class OpenGraph
* Подключение:
* 'components' => [
* 'opengraph' => [
* 'class' => 'fgh151\opengraph\OpenGraph',
* ],
* //....
* ],
* Использование:
* Перед рендером вызвать:
* Yii::$app->opengraph->title = 'My_Article';
* Yii::$app->opengraph->description = 'My_Article_Description';
* Yii::$app->opengraph->image = 'http://image.for.my/article';
*/
class OpenGraph{
public $title;
public $siteName;
public $url;
public $description;
public $type;
public $locale;
public $image;
public function __construct(){
$this->title = Yii::$app->name;
$this->siteName = Yii::$app->name;
$this->url = Yii::$app->request->absoluteUrl;
$this->description = null;
$this->type = 'article';
$this->locale = str_replace('-','_',Yii::$app->language);
$this->image = null;
Yii::$app->getView()->on(View::EVENT_BEFORE_RENDER, [$this, 'addTags']);
}
/**
* Register og tags
*/
public function addTags()
{
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:title',
'content'=>$this->title
], 'og:title');
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:site_name',
'content'=>$this->siteName
], 'og:site_name');
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:url',
'content'=>$this->url
], 'og:url');
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:type',
'content'=>$this->type
], 'og:type');
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:locale',
'content'=>$this->locale
], 'og:locale');
if($this->description!==null){
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:description',
'content'=>$this->description
], 'og:description');
}
if($this->image!==null){
Yii::$app->controller->getView()->registerMetaTag([
'property'=>'og:image',
'content'=>$this->image
], 'og:image');
}
}
/**
* @param array $tags
*/
public function set(array $tags){
foreach($tags as $property=>$content){
if(property_exists($this, $property)){
$this->$property = $content;
}
}
}
}