2 changed files with 75 additions and 1 deletions
@ -0,0 +1,73 @@
|
||||
<?php |
||||
|
||||
namespace Shikiryu\WebGobbler\Collector; |
||||
|
||||
use Shikiryu\WebGobbler\Collector; |
||||
|
||||
class ImgurCollector extends Collector |
||||
{ |
||||
|
||||
/** |
||||
* @return string |
||||
*/ |
||||
public function getName() |
||||
{ |
||||
return 'collector_imgur'; |
||||
} |
||||
|
||||
/** |
||||
* @return int |
||||
* @throws \JsonException |
||||
*/ |
||||
public function getRandomImage() |
||||
{ |
||||
return $this->getRandomImages(1); |
||||
} |
||||
|
||||
/** |
||||
* @param int $number |
||||
* |
||||
* @return int |
||||
* @throws \JsonException |
||||
*/ |
||||
public function getRandomImages(int $number) |
||||
{ |
||||
$word_to_search = $this->getConfig()->get('collector.keywords.keywords', false); |
||||
$url = sprintf('https://api.imgur.com/3/gallery/search?q=%s', $word_to_search); |
||||
$curl = curl_init(); |
||||
|
||||
curl_setopt_array($curl, array( |
||||
CURLOPT_URL => $url, |
||||
CURLOPT_RETURNTRANSFER => true, |
||||
CURLOPT_ENCODING => "", |
||||
CURLOPT_MAXREDIRS => 10, |
||||
CURLOPT_TIMEOUT => 0, |
||||
CURLOPT_FOLLOWLOCATION => true, |
||||
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, |
||||
CURLOPT_CUSTOMREQUEST => "GET", |
||||
CURLOPT_HTTPHEADER => [ |
||||
sprintf('Authorization: Client-ID %s', $this->getConfig()->get('collector.imgur.client_id')) |
||||
], |
||||
)); |
||||
|
||||
$response = curl_exec($curl); |
||||
|
||||
curl_close($curl); |
||||
$response = json_decode($response, true, 512, JSON_THROW_ON_ERROR); |
||||
$images = array_map(static function($image) { |
||||
return $image['images'][0]['link']; |
||||
}, $response['data']); |
||||
|
||||
$index_to_download = array_rand($images, $number); |
||||
if (!is_array($index_to_download)) { |
||||
$index_to_download = [$index_to_download]; |
||||
} |
||||
|
||||
foreach ($index_to_download as $image_index) { |
||||
$photo = $images[$image_index]; |
||||
file_put_contents($this->getPoolDirectory() . '/' . basename(parse_url($photo, PHP_URL_PATH)), file_get_contents($photo)); |
||||
} |
||||
|
||||
return $number; |
||||
} |
||||
} |
Loading…
Reference in new issue