ArticleMicrodata.php 1.65 KB
<?php

namespace frontend\microdata;

use yii\base\BaseObject;
use frontend\microdata\Microdata;


class ArticleMicrodata extends Microdata
{


    # массив, который составляет из себя реально существующие пары свойство/значение
    # !!! так же тут нету пар с пустым значением
    public $constructArray=[];
	public $mainEntityOfPage = null;
	public $headLine = null;
	public $image = null;
	public $datePublished = null;
	public $dateModified = null;
	public $author = null;
	public $publisher = null;
	public $description = null;
	public $headline = null;
    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\">";

        $test=[];
        foreach ($this->constructArray as $key=>$value)
        {
	        if ($key == 'type' || $key == 'context') $key = '@' . $key;
            $test[$key]=$value;
        }
        $resultJson1=json_encode($test);
        $resultJson1=str_replace('\/','/',$resultJson1);
        $resultJson.=$resultJson1;
        $resultJson.='</script>';
        return $resultJson;
    }



}