<?php
namespace Razzwan;
class ImagesHandler
{
@var
protected $links = [];
@var
protected $domain = false;
@var
protected $count;
@var
protected $resource;
@param @return
public function getResource($url)
{
$url = $this->makeUrl($url);
if(!$this->domain){
$this->domain = $this->getDomain($url);
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
]);
if($this->resource = curl_exec($ch)){
return true;
}
return false;
}
http://, @param @return
public function makeUrl($url)
{
if(substr($url, 0, 7) == 'http://' || substr($url, 0, 8) == 'https://'){
return $url;
} else {
return'http://' . $url;
}
}
@param @return
public function findLinks($resource)
{
$match = [];
preg_match_all(
"/< *a *href *= *[\"|\'] *(.*?) *[\"|\']/is",
$resource,
$match
);
return $this->clearLinks(array_unique($match[1]), $this->domain);
}
@param @return
public function addLinks($resource)
{
$links = $this->findLinks($resource);
$this->links = array_merge($this->links, $links);
return $this->links = array_unique($this->links);
}
@param @return
public function getDomain($url)
{
if($this->domain){
return $this->domain;
}
$math = [];
preg_match("/https?:\/\/[0-9a-z\.]*/i", $url, $math);
return $this->domain = array_shift($math);
}
@param @param @return
public function clearLinks(array $arr = [], $domain)
{
$links = [];
foreach($arr as $key => $val){
$links[$key] = trim(str_replace($domain, '', $val));
if(preg_match('/^http/', $links[$key]) || strlen($links[$key]) == 1){
unset($links[$key]);
}
}
return array_unique($links);
}
@param @throws @return
public function getAllLinks($url)
{
if($this->getResource($url)){
$this->addLinks($this->resource);
if($this->links[$this->count]){
$this->getAllLinks($this->domain . $this->links[$this->count]);
}
return $this->links;
} else {
throw new \Exception(
sprintf(
"Ресурс %s недоступен",
$this->resource
)
);
}
}
}