File: /var/www/vhost/disk-apps/qas.sports-crowd.com/app/Http/Controllers/Api/YoutubeApiController.php
<?php
namespace App\Http\Controllers\Api;
use App\OfficialYoutube;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
class YoutubeApiController extends Controller
{
const API_URL = 'https://www.googleapis.com/youtube/v3';
public function get($take = 10)
{
return $this->feed($take);
}
private function feed($take)
{
if (!Cache::has('videos')) {
$videos = [];
$API_key = config('googleapis.youtube.key');
$channels = OfficialYoutube::where('active', 1)->orderBy('created_at', 'desc')->get();
foreach ($channels as $item) {
try {
$channelID = $item->channel;
$maxResults = $item->max_results ?? 10;
$results = json_decode(file_get_contents(self::API_URL . '/search?order=date&part=snippet&channelId=' . $channelID . '&maxResults=' . $maxResults . '&key=' . $API_key . ''));
if ($results && $results->items) {
foreach ($results->items as $data) {
$videos[] = (object) [
'link' => '',
'code' => $data->id->videoId,
'social_network_account_id' => $item->social_network_account_id
];
}
$item->videos = $videos;
$item->update();
}
} catch (\Throwable $th) {
if ($item->videos)
$videos = $item->videos;
}
if ($item->featured_videos) {
$featuredVideos = explode(',', $item->featured_videos);
$featuredVideos = array_map('trim', $featuredVideos);
$featuredVideos = array_reverse($featuredVideos);
foreach ($featuredVideos as $featuredVideo) {
$video = (object) [
'link' => '',
'code' => $featuredVideo,
'social_network_account_id' => $item->social_network_account_id
];
array_unshift($videos, $video);
}
}
}
if (!is_array($videos)) {
$videos = json_decode($videos, true);
}
Cache::put('videos', $videos, config('cache.short_time'));
} else {
$videos = Cache::get('videos');
}
$videos = array_slice($videos, 0, $take);
return $videos;
}
}