✨ Add Imgur Collector
This commit is contained in:
parent
f92dc419e5
commit
7cfce96dd0
@ -11,7 +11,8 @@
|
||||
"require": {
|
||||
"fabpot/goutte": "^4.0",
|
||||
"ext-imagick": "*",
|
||||
"samwilson/phpflickr": "^4.14"
|
||||
"samwilson/phpflickr": "^4.14",
|
||||
"ext-curl": "*"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
73
src/Collector/ImgurCollector.php
Normal file
73
src/Collector/ImgurCollector.php
Normal file
@ -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
Block a user