Skip to content

Instantly share code, notes, and snippets.

@firecentaur
Created June 15, 2020 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save firecentaur/021378b80fc3e01453e497ed53d54749 to your computer and use it in GitHub Desktop.
Save firecentaur/021378b80fc3e01453e497ed53d54749 to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Channel;
class ChannelCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'channel:list {url?}';
public $apiKey;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
$this->apiKey = env('YOUTUBE_API_KEY');
parent::__construct();
}
public function getYouTubeChannelIdByUserUrl($url)
{
$userId = null;
$str = '/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"\'<> #]+)/';
if (preg_match($str, $url, $match)) {
$userId = $match[1];
}
return $userId;
}
public function getYouTubeChannelIdByUrl($url)
{
$video_id = null;
$str = '/((http|https):\/\/)?(www\.|)youtube\.com\/channel\/([a-zA-Z0-9_\-]{1,})/';
if (strpos($url,'user')){
return 'user';
}else{
if (preg_match($str, $url, $match)) {
$video_id = $match[4];
}
}
return $video_id;
}
public function channelInfo($channelId,$parts,$userId = null)
{
$ytApiKey = $this->apiKey;
$queryString = "https://www.googleapis.com/youtube/v3/channels/";
$queryString .= "?part=$parts";
$queryString .= "&key={$ytApiKey}";
if ($userId!==null){
$queryString .= "&forUsername=$userId";
}else{
$queryString .= "&id=$channelId";
}
//check cache
$jsonResponse = @file_get_contents($queryString);
if ($jsonResponse === false) {
echo 'error';
return false;
}
return $jsonResponse;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$str="Please paste the channel id and press <enter>";
$url = $this->ask($str);
$channelId = $this->getYouTubeChannelIdByUrl($url);
if ($channelId === 'user') {
$channelType = 'User';
$userId = $this->getYouTubeChannelIdByUserUrl($url);
echo "\nUser Channel is $userId\n";
} else {
$channelType = 'Channel';
echo "\n Channel Id is $channelId\n";
}
$channelInfo = json_decode($this->channelInfo($channelId, 'contentDetails,snippet', $channelId));
$D=1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment