<?php
use \ForceUTF8\Encoding;

class MetaService
{

    private $source;
    private $parser;
    private $metaData = [
        'site_title'        => '',
        'site_keywords'     => '',
        'site_description'  => '',
        'site_content_type' => '',
        'others'            => []
    ];

    public function __construct($source, $parser)
    {
        $this->source = $source;
        $this->parser = $parser;
    }

    public function get()
    {
        $this->getMetas();

        return $this->metaData;
    }

    private function getMetas()
    {

        $html = $this->parser->str_get_html($this->source);

        if(! $html){
            return false;
        }

        $title = $html->find('title', 0);

        if(isset($title->plaintext)){
            $this->metaData['site_title'] = Encoding::toUTF8($title->plaintext);
        }

        $metas = $html->find('meta');
        $charset = false;
        foreach($metas as $meta){
            if($charset === false && array_key_exists('http-equiv', $meta->attr) && Str::lower($meta->attr['http-equiv']) == 'content-type'){
                preg_match("/charset=(.*)/", $meta->content, $matched);
                if($matched){
                    $charset = true;
                    $this->metaData['site_content_type'] = Str::lower($matched[1]);
                }
            }

            if($charset === false && isset($meta->charset)){
                $this->metaData['site_content_type'] = Str::lower($meta->charset);
            }
            if(isset($meta->name) && in_array(strtolower($meta->name), Config::get('app.meta_tags_filter'))){
                if(Str::lower($meta->name) == 'keywords'){
                    $this->metaData['site_keywords'] = Encoding::toUTF8($meta->content);
                }
                elseif(Str::lower($meta->name) == 'description'){
                    $this->metaData['site_description'] = Encoding::toUTF8($meta->content);
                }
                else{
                    $this->metaData['others'][] = [
                        'name'    => Str::lower($meta->name),
                        'content' => Encoding::toUTF8($meta->content)
                    ];
                }
            }
        }
    }

} 