OrganizationMicrodata.php
1.62 KB
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
<?php
namespace frontend\microdata;
use yii\base\BaseObject;
class OrganizationMicrodata extends  Microdata
{
	public $brand=null;
	public $aggregateRating=null;
	public $offers=null;
	public $description=null;
	public $npm=null;
	public $type=null;
	public $url=null;
	public $logo=null;
	public $contactPoint=null;
	public $telephone=null;
	public $contactType=null;
	# массив, который составляет из себя реально существующие пары свойство/значение
	# !!! так же тут нету пар с пустым значением
	public $constructArray=[];
	public function __construct(array $config = [])
	{
		# обрезаю входящие свойства, работаем только с реально существующими
		foreach ($config as $key=>$value){
			if(!property_exists(self::class,$key))
			{
				unset($config[$key]);
			}
			elseif($value==null || $value===false || $value=='')
			{
				unset($config[$key]);
			}
		}
		$this->constructArray=$config;
		parent::__construct($config);
	}
	public function toJson(): string
	{
		$resultJson=" <script type=\"application/ld+json\">";
		$finalArray=[];
		foreach ($this->constructArray as $key=>$value)
		{
			if($key=='type' || $key=='context')$key='@'.$key;
			$finalArray[$key]=$value;
		}
		$resultJson1=json_encode($finalArray,JSON_UNESCAPED_UNICODE);
		$resultJson1=str_replace('\/','/',$resultJson1);
		$resultJson.=$resultJson1;
		$resultJson.='</script>';
		return $resultJson;
	}
	function add($key,$value)
	{
		if ($value!==null)
			$this->constructArray[$key]=$value;
	}
}