<?php

/*
 * JsonLdParser
 * Copyright 2019 TopWebStudio. All Rights Reserved.
 * Distribution allowed only with licensing permission
 * contact@topwebstudio.com  
 */

namespace Topwebstudio\Parsers;

class JsonLdParser extends Parser {

    protected $items;

    const JSON_COMMENT_PATTERN = '#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#';

    public function __construct($content) {
        $this->content = $content;
    }

    public function parseDom() {
        $dom = new \DOMDocument();
        @$dom->loadHTML($this->content);

        $xpath = new \DOMXPath($dom);
        $jsonLDDocs = $xpath->query('//*[local-name(.) = "script"][@type = "application/ld+json"]');

        foreach ($jsonLDDocs as $jsonLDDoc) {
            $jsonLDDocSource = preg_replace(self::JSON_COMMENT_PATTERN, '', $jsonLDDoc->textContent);
            $this->items[] = $this->parseDocument($jsonLDDocSource);
        }
    }

    protected function parseDocument($jsonLDDocSource) {
        $jsonLDDoc = @json_decode(preg_replace("/\n\r+/", '', $jsonLDDocSource), true);

        if (is_array($jsonLDDoc)) {
            return $jsonLDDoc;
        }

        return array();
    }

    public function getParsedData() {
        $this->parseDom();

        $this->recursive_ksort($this->items);

        return $this->items;
    }

}
