<?php

class DmozService
{

    private $site;
    private $parser;

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

    public function get()
    {
        $data = file_get_contents_curl('http://www.dmoz.org/search?q=' . $this->site);

        if(! $data){
            return [];
        }

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

        $find3 = $html->find('a[href=http://' . $this->site . '/]', 0);
        $find2 = $html->find('a[href=http://www.' . $this->site . '/]', 0);
        $find1 = $html->find('a[href=http://www.' . $this->site . ']', 0);

        if ($find1) {
            $element = $find1;
        } elseif ($find2) {
            $element = $find2;
        } elseif ($find3) {
            $element = $find3;
        } else {
            $element = false;
        }

        if ($element) {

            preg_match("/\">(.*?)<\/a>/mis", $element->parent()->innertext, $title);
            preg_match("/<\/a> - (.*?)<div/mis", $element->parent()->innertext, $description);
            $categoryLink = urldecode($element->parent()->find('.ref a')[0]->getAttribute('href'));
            $category = $element->parent()->find('.ref a')[0]->plaintext;
            $found = [
                'title'         => html_entity_decode(trim($title[1])),
                'description'   => html_entity_decode(trim($description[1])),
                'category_link' => 'http://dmoz.org/' . $categoryLink,
                'category'      => $category
            ];

            return $found;
        }

        return [];
    }
}