Laravel 5.2 Update (#106)

* Adopt PSR-2 coding style

The Laravel framework adopts the PSR-2 coding style in version 5.1.
Laravel apps *should* adopt this coding style as well. Read the
[PSR-2 coding style guide][1] for more details and check out [PHPCS][2]
to use as a code formatting tool.

[1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
[2]: https://github.com/squizlabs/PHP_CodeSniffer

* Adopt PHP short array syntax

Laravel 5 adopted the short array syntax which became available in
PHP 5.4.

* Remove SelfHandling from Jobs

Jobs are self handling by default in Laravel 5.2.

* Add new exceptions to `$dontReport` property

* Shift core files

* Shift Middleware

Laravel 5.2 adjusts the `Guard` object used within middleware. In
addition, new `can` and `throttles` middleware were added.

* Shift Input to Request facade

Laravel 5.2 no longer registers the `Input` facade by default. Laravel
now prefers using the `Request` facade or the `$request` object within
*Controllers* instead. Review the [HTTP Requests][1] documentation for
more details.

[1]: https://laravel.com/docs/5.2/requests

* Shift configuration

Laravel 5.2 introduces the `env` app configuration option and removes
the `pretend` mail configuration option. In addition, a few of the
default `providers` and `aliases` bindings were removed.

* Shift Laravel dependencies

* Shift cleanup

* Updated composer.lock

* Updated Middleware to 5.2

* Config update for Laravel 5.2

* [Laravel 5.2] Updated validation strings

* Updated auth config

* Updated to use middleware groups

* Added laravel 5.2 sessions migration
This commit is contained in:
Laravel Shift 2016-09-29 18:26:31 -04:00 committed by Adam Lavin
parent 9b31b48f37
commit 00f24a5c12
244 changed files with 40326 additions and 40363 deletions

1
.gitignore vendored
View file

@ -3,6 +3,7 @@
/public/build
/logs
Homestead.yaml
/public/storage
.env
.vagrant
_ide_helper.php

View file

@ -77,11 +77,15 @@ class AlbumDownloader
if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) {
$masterFormatName = $track->getMasterFormatName();
$zip->addLargeFile($track->getFileFor($masterFormatName),
$directory . $track->getDownloadFilenameFor($masterFormatName));
$zip->addLargeFile(
$track->getFileFor($masterFormatName),
$directory . $track->getDownloadFilenameFor($masterFormatName)
);
} else {
$zip->addLargeFile($track->getFileFor($this->_format),
$directory . $track->getDownloadFilenameFor($this->_format));
$zip->addLargeFile(
$track->getFileFor($this->_format),
$directory . $track->getDownloadFilenameFor($this->_format)
);
}
$notes .=

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Commands;
abstract class CommandBase
{
private $_listeners = array();
private $_listeners = [];
public function listen($listener)
{
@ -47,5 +47,5 @@ abstract class CommandBase
/**
* @return CommandResponse
*/
public abstract function execute();
abstract public function execute();
}

View file

@ -44,7 +44,6 @@ class CommandResponse
if (is_array($validatorOrMessages)) {
$response->_messages = $validatorOrMessages;
$response->_validator = null;
} else {
$response->_validator = $validatorOrMessages;
}
@ -102,7 +101,6 @@ class CommandResponse
{
if ($this->_validator !== null) {
return $this->_validator->messages()->getMessages();
} else {
return $this->_messages;
}

View file

@ -100,16 +100,12 @@ class CreateCommentCommand extends CommandBase
// Recount the track's comments, if this is a track comment
if ($this->_type === 'track') {
$entity = Track::find($this->_id);
} elseif ($this->_type === 'album') {
$entity = Album::find($this->_id);
} elseif ($this->_type === 'playlist') {
$entity = Playlist::find($this->_id);
} elseif ($this->_type === 'user') {
$entity = User::find($this->_id);
} else {
App::abort(400, 'This comment is being added to an invalid entity!');
}

View file

@ -35,7 +35,8 @@ class DeleteGenreCommand extends CommandBase
private $_genreToDelete;
private $_destinationGenre;
public function __construct($genreId, $destinationGenreId) {
public function __construct($genreId, $destinationGenreId)
{
$this->_genreToDelete = Genre::find($genreId);
$this->_destinationGenre = Genre::find($destinationGenreId);
}
@ -43,7 +44,8 @@ class DeleteGenreCommand extends CommandBase
/**
* @return bool
*/
public function authorize() {
public function authorize()
{
return Gate::allows('delete', $this->_genreToDelete);
}
@ -51,7 +53,8 @@ class DeleteGenreCommand extends CommandBase
* @throws \Exception
* @return CommandResponse
*/
public function execute() {
public function execute()
{
$rules = [
'genre_to_delete' => 'required',
'destination_genre' => 'required',

View file

@ -35,7 +35,8 @@ class DeleteShowSongCommand extends CommandBase
private $_songToDelete;
private $_destinationSong;
public function __construct($songId, $destinationSongId) {
public function __construct($songId, $destinationSongId)
{
$this->_songToDelete = ShowSong::find($songId);
$this->_destinationSong = ShowSong::find($destinationSongId);
}
@ -43,7 +44,8 @@ class DeleteShowSongCommand extends CommandBase
/**
* @return bool
*/
public function authorize() {
public function authorize()
{
return Gate::allows('delete', $this->_destinationSong);
}
@ -51,7 +53,8 @@ class DeleteShowSongCommand extends CommandBase
* @throws \Exception
* @return CommandResponse
*/
public function execute() {
public function execute()
{
$rules = [
'song_to_delete' => 'required',
'destination_song' => 'required',

View file

@ -84,13 +84,10 @@ class GenerateTrackFilesCommand extends CommandBase
if ($isLossyUpload) {
if ($codecString === 'mp3') {
$masterFormat = 'MP3';
} else if (Str::startsWith($codecString, 'aac')) {
$masterFormat = 'AAC';
} else if ($codecString === 'vorbis') {
$masterFormat = 'OGG Vorbis';
} else {
$this->track->delete();
return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]);
@ -156,7 +153,6 @@ class GenerateTrackFilesCommand extends CommandBase
}
$this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack));
}
} catch (InvalidEncodeOptionsException $e) {
// Only delete the track if the track is not being replaced
if ($this->isReplacingTrack) {
@ -167,7 +163,6 @@ class GenerateTrackFilesCommand extends CommandBase
}
return CommandResponse::fail(['track' => [$e->getMessage()]]);
}
} catch (\Exception $e) {
if ($this->isReplacingTrack) {
$this->track->version_upload_status = Track::STATUS_ERROR;

View file

@ -35,7 +35,6 @@ use Poniverse\Ponyfm\Models\User;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ParseTrackTagsCommand extends CommandBase
{
private $track;
@ -107,7 +106,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param Track
* @return Track
*/
private function unsetNullVariables($track) {
private function unsetNullVariables($track)
{
$vars = $track->getAttributes();
foreach ($vars as $key => $value) {
@ -125,7 +125,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $genreName
* @return int
*/
protected function getGenreId(string $genreName) {
protected function getGenreId(string $genreName)
{
$existingGenre = Genre::withTrashed()
->where('name', $genreName)->first();
@ -165,7 +166,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param integer|null $coverId
* @return int|null
*/
protected function getAlbumId(int $artistId, $albumName, $coverId = null) {
protected function getAlbumId(int $artistId, $albumName, $coverId = null)
{
if (null !== $albumName) {
$album = Album::firstOrNew([
'user_id' => $artistId,
@ -194,7 +196,8 @@ class ParseTrackTagsCommand extends CommandBase
* @return array the "processed" and raw tags extracted from the file
* @throws \Exception
*/
protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec) {
protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec)
{
//==========================================================================================================
// Extract the original tags.
//==========================================================================================================
@ -208,16 +211,12 @@ class ParseTrackTagsCommand extends CommandBase
if ($audioCodec === 'mp3') {
list($parsedTags, $rawTags) = $this->getId3Tags($allTags);
} elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} elseif (in_array($audioCodec, ['vorbis', 'flac'])) {
list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
} elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} else {
// Assume the file is untagged if it's in an unknown format.
$parsedTags = [
@ -255,7 +254,6 @@ class ParseTrackTagsCommand extends CommandBase
if ($genreName !== null) {
$parsedTags['genre_id'] = $this->getGenreId($genreName);
} else {
$parsedTags['genre_id'] = null;
}
@ -270,10 +268,8 @@ class ParseTrackTagsCommand extends CommandBase
if ($image['image_mime'] === 'image/png') {
$extension = 'png';
} elseif ($image['image_mime'] === 'image/jpeg') {
$extension = 'jpg';
} else {
throw new BadRequestHttpException('Unknown cover format embedded in the track file!');
}
@ -289,7 +285,6 @@ class ParseTrackTagsCommand extends CommandBase
$cover = Image::upload($imageFile, $artist);
$coverId = $cover->id;
} else {
// no cover art was found - carry on
}
@ -318,7 +313,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags
* @return array
*/
protected function getId3Tags($rawTags) {
protected function getId3Tags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) {
$tags = $rawTags['tags']['id3v2'];
} elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) {
@ -364,7 +360,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags
* @return array
*/
protected function getAtomTags($rawTags) {
protected function getAtomTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) {
$tags = $rawTags['tags']['quicktime'];
} else {
@ -379,7 +376,6 @@ class ParseTrackTagsCommand extends CommandBase
if (isset($tags['release_date'])) {
$releaseDate = $this->parseDateString($tags['release_date'][0]);
} elseif (isset($tags['creation_date'])) {
$releaseDate = $this->parseDateString($tags['creation_date'][0]);
} else {
@ -408,7 +404,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags
* @return array
*/
protected function getVorbisTags($rawTags) {
protected function getVorbisTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) {
$tags = $rawTags['tags']['vorbiscomment'];
} else {
@ -452,7 +449,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $dateString
* @return null|Carbon
*/
protected function parseDateString(string $dateString) {
protected function parseDateString(string $dateString)
{
switch (Str::length($dateString)) {
// YYYY
case 4:
@ -475,7 +473,6 @@ class ParseTrackTagsCommand extends CommandBase
// If not, give up.
try {
return Carbon::createFromFormat(Carbon::ISO8601, $dateString);
} catch (\InvalidArgumentException $e) {
return null;
}

View file

@ -94,10 +94,8 @@ class SaveAccountSettingsCommand extends CommandBase
if (isset($this->_input['avatar_id'])) {
$this->_user->avatar_id = $this->_input['avatar_id'];
} elseif (isset($this->_input['avatar'])) {
$this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id;
} else {
$this->_user->avatar_id = null;
}

View file

@ -25,7 +25,7 @@ use Carbon\Carbon;
use Config;
use Gate;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User;
use Validator;
@ -73,7 +73,7 @@ class UploadTrackCommand extends CommandBase
int $version = 1,
$track = null
) {
$userSlug = Input::get('user_slug', null);
$userSlug = Request::get('user_slug', null);
$this->_artist =
$userSlug !== null
? User::where('slug', $userSlug)->first()
@ -94,9 +94,9 @@ class UploadTrackCommand extends CommandBase
*/
public function execute()
{
$trackFile = Input::file('track', null);
$trackFile = Request::file('track', null);
if (!$this->_isReplacingTrack) {
$coverFile = Input::file('cover', null);
$coverFile = Request::file('cover', null);
}
if (null === $trackFile) {
@ -114,7 +114,7 @@ class UploadTrackCommand extends CommandBase
$this->_track->user_id = $this->_artist->id;
// The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand
// if the file contains a title tag.
$this->_track->title = Input::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME));
$this->_track->title = Request::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME));
// The duration/version of the track cannot be changed until the encoding is successful
$this->_track->duration = $audio->getDuration();
$this->_track->current_version = $this->_version;
@ -131,7 +131,7 @@ class UploadTrackCommand extends CommandBase
}
$trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version);
$input = Input::all();
$input = Request::all();
$input['track'] = $trackFile;
if (!$this->_isReplacingTrack) {
$input['cover'] = $coverFile;
@ -180,7 +180,7 @@ class UploadTrackCommand extends CommandBase
if (!$this->_isReplacingTrack) {
// If json_decode() isn't called here, Laravel will surround the JSON
// string with quotes when storing it in the database, which breaks things.
$this->_track->metadata = json_decode(Input::get('metadata', null));
$this->_track->metadata = json_decode(Request::get('metadata', null));
}
$autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault);
$this->_track->source = $this->_customTrackSource ?? 'direct_upload';

View file

@ -108,8 +108,12 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($track->filename), 'ingram')) {
$this->info('This is an official song remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, true,
$parsedTags);
list($trackType, $linkedSongIds) = $this->classifyTrack(
$track->filename,
$officialSongs,
true,
$parsedTags
);
// If it has "remix" in the name, it's definitely a remix.
@ -117,13 +121,21 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) {
$this->info('This is some kind of remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false,
$parsedTags);
list($trackType, $linkedSongIds) = $this->classifyTrack(
$track->filename,
$officialSongs,
false,
$parsedTags
);
// No idea what this is. Have the pony at the terminal figure it out!
} else {
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false,
$parsedTags);
list($trackType, $linkedSongIds) = $this->classifyTrack(
$track->filename,
$officialSongs,
false,
$parsedTags
);
}
}
@ -144,7 +156,6 @@ class ClassifyMLPMA extends Command
echo PHP_EOL;
}
}
/**
@ -169,19 +180,15 @@ class ClassifyMLPMA extends Command
if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) {
$linkedSongIds = [$officialSongs[0]->id];
} else {
if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) {
$this->question('Multiple official songs matched! Please enter the ID of the correct one.');
} else {
if (sizeof($officialSongs) > 0) {
$this->question('This looks like a remix of an official song!');
$this->question('Press "r" if the match above is right!');
} else {
$this->question('Exactly what kind of track is this?');
}
}
$this->question('If this is a medley, multiple song ID\'s can be separated by commas. ');

View file

@ -76,13 +76,10 @@ class ClearTrackCache extends Command
if (count($trackFiles) === 0) {
$this->info('No tracks found. Exiting.');
} else {
if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) {
$count = 0;
foreach ($trackFiles as $trackFile) {
// Set expiration to null (so can be re-cached upon request)
$trackFile->expires_at = null;
$trackFile->update();
@ -94,14 +91,11 @@ class ClearTrackCache extends Command
$this->info('Deleted ' . $trackFile->getFile());
}
}
$this->info($count . ' files deleted. Deletion complete. Exiting.');
} else {
$this->info('Deletion cancelled. Exiting.');
}
}
}
}

View file

@ -144,7 +144,6 @@ class FixMLPMAImages extends Command
$imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']);
$cover = Image::upload($imageFile, $artistId, true);
$coverId = $cover->id;
} else {
$this->comment('No cover art found!');
}

View file

@ -101,8 +101,10 @@ class MigrateOldData extends Command
if (!$user->uses_gravatar) {
try {
$coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png';
$coverId = Image::upload(new UploadedFile($coverFile,
$user->id.'_.png'), $user->id)->id;
$coverId = Image::upload(new UploadedFile(
$coverFile,
$user->id.'_.png'
), $user->id)->id;
DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]);
} catch (\Exception $e) {
$this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage());
@ -176,10 +178,14 @@ class MigrateOldData extends Command
$coverId = null;
if ($track->cover) {
try {
$coverFile = $this->getIdDirectory('tracks',
$track->id).'/'.$track->id.'_'.$track->cover.'.png';
$coverId = Image::upload(new UploadedFile($coverFile,
$track->id.'_'.$track->cover.'.png'), $track->user_id)->id;
$coverFile = $this->getIdDirectory(
'tracks',
$track->id
).'/'.$track->id.'_'.$track->cover.'.png';
$coverId = Image::upload(new UploadedFile(
$coverFile,
$track->id.'_'.$track->cover.'.png'
), $track->user_id)->id;
} catch (\Exception $e) {
$this->error('Could copy track cover '.$track->id.' because '.$e->getMessage());
}
@ -396,5 +402,4 @@ class MigrateOldData extends Command
return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir;
}
}

View file

@ -76,12 +76,10 @@ class PoniverseApiSetup extends Command
'auth' => [$username, $password],
'query' => ['app' => 'Pony.fm']
]);
} catch (ClientException $e) {
if ($e->getResponse()->getStatusCode() === 401) {
$this->error('Incorrect username or password! Please try again.');
exit();
} else {
var_dump($e->getResponse()->getBody());
throw $e;
@ -100,16 +98,20 @@ class PoniverseApiSetup extends Command
}
protected function setEnvironmentVariable($key, $oldValue, $newValue) {
protected function setEnvironmentVariable($key, $oldValue, $newValue)
{
$path = base_path('.env');
// Detect the specific "null" value.
if ($oldValue === null)
if ($oldValue === null) {
$oldValue = 'null';
}
if (file_exists($path)) {
file_put_contents($path, str_replace(
"$key=".$oldValue, "$key=".$newValue, file_get_contents($path)
"$key=".$oldValue,
"$key=".$newValue,
file_get_contents($path)
));
} else {
$this->error('Please run `vagrant up`!');

View file

@ -59,10 +59,11 @@ class RebuildFilesizes extends Command
{
$this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rebuild the filesize cache? [y|N]',
false)
if ($this->option('force') || $this->confirm(
'Are you sure you want to rebuild the filesize cache? [y|N]',
false
)
) {
TrackFile::chunk(200, function ($trackFiles) {
$this->info('========== Start Chunk ==========');
@ -79,11 +80,9 @@ class RebuildFilesizes extends Command
}
$this->info('=========== End Chunk ===========');
});
$this->info('Rebuild complete. Exiting.');
} else {
$this->info('Rebuild cancelled. Exiting.');
}

View file

@ -59,7 +59,6 @@ class RebuildTags extends Command
if ($this->argument('trackId')) {
$track = Track::findOrFail($this->argument('trackId'));
$tracks = [$track];
} else {
$tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get();
}

View file

@ -81,7 +81,6 @@ class RebuildTrack extends Command
$this->error("Something went wrong!");
print_r($result->getMessages());
}
} else {
$this->info("Re-encoding this track's files - there should be a line of output for each format!");
@ -94,7 +93,8 @@ class RebuildTrack extends Command
}
}
private function printTrackInfo(Track $track) {
private function printTrackInfo(Track $track)
{
$this->comment("Track info:");
$this->comment(" Title: {$track->title}");
$this->comment(" Uploaded at: {$track->created_at}");

View file

@ -67,10 +67,11 @@ class RebuildTrackCache extends Command
$this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.');
$this->info('***');
if ($this->option('force') || $this->confirm('Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?',
false)
if ($this->option('force') || $this->confirm(
'Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?',
false
)
) {
//==========================================================================================================
// Delete previously cached track files
//==========================================================================================================
@ -252,7 +253,6 @@ class RebuildTrackCache extends Command
$this->output->newLine(1);
$this->info('Rebuild complete. Exiting.');
} else {
$this->info('Rebuild cancelled. Exiting.');
}

View file

@ -61,7 +61,6 @@ class VersionFiles extends Command
$this->info('This will only version track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) {
TrackFile::chunk(200, function ($trackFiles) {
$this->info('========== Start Chunk ==========');
@ -81,15 +80,12 @@ class VersionFiles extends Command
} else {
$this->error('ID ' . $trackFile->id . ' was unable to be renamed');
}
}
$this->info('=========== End Chunk ===========');
});
$this->info('Rebuild complete. Exiting.');
} else {
$this->info('Rebuild cancelled. Exiting.');
}

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
*
* @package Poniverse\Ponyfm\Contracts
*/
interface Commentable extends GeneratesNotifications {
interface Commentable extends GeneratesNotifications
{
/**
* This method returns an Eloquent relation to the entity's comments.
*

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
*
* @package Poniverse\Ponyfm\Contracts
*/
interface Favouritable extends GeneratesNotifications {
interface Favouritable extends GeneratesNotifications
{
/**
* This method returns an Eloquent relation to the entity's favourites.
*

View file

@ -29,7 +29,8 @@ use Poniverse\Ponyfm\Models\User;
*
* @package Poniverse\Ponyfm\Contracts
*/
interface GeneratesNotifications {
interface GeneratesNotifications
{
/**
* Returns a human-friendly string (lowercase & singular) representing this
* type of resource.

View file

@ -33,7 +33,8 @@ use Poniverse\Ponyfm\Models\User;
* type of notification, add a method for it to this interface and every class
* that implements it. Your IDE should be able to help with this.
*/
interface NotificationHandler {
interface NotificationHandler
{
/**
* @param Track $track
* @return void

View file

@ -20,7 +20,8 @@
namespace Poniverse\Ponyfm\Contracts;
interface Searchable {
interface Searchable
{
/**
* Returns this model in Elasticsearch-friendly form. The array returned by
* this method should match the current mapping for this model's ES type.

View file

@ -22,6 +22,8 @@ namespace Poniverse\Ponyfm\Exceptions;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Validation\ValidationException;
use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler;
class Handler extends ExceptionHandler
@ -32,6 +34,8 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
ValidationException::class,
HttpException::class,
];
@ -45,7 +49,7 @@ class Handler extends ExceptionHandler
*/
public function report(Exception $e)
{
return parent::report($e);
parent::report($e);
}
/**

View file

@ -29,4 +29,6 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
* This exception indicates that an access token we attempted to introspect
* through the Poniverse API is expired or otherwise unusable.
*/
class InvalidAccessTokenException extends AccessDeniedHttpException {};
class InvalidAccessTokenException extends AccessDeniedHttpException
{
};

View file

@ -22,4 +22,6 @@ namespace Poniverse\Ponyfm\Exceptions;
use InvalidArgumentException;
class InvalidEncodeOptionsException extends InvalidArgumentException {}
class InvalidEncodeOptionsException extends InvalidArgumentException
{
}

View file

@ -31,4 +31,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
* contain tracks for which no lossless master is available (and thus, lossless
* `TrackFiles` don't exist for).
*/
class TrackFileNotFoundException extends ModelNotFoundException {}
class TrackFileNotFoundException extends ModelNotFoundException
{
}

View file

@ -19,10 +19,13 @@
*/
namespace Poniverse\Ponyfm\Facades;
use Illuminate\Support\Facades\Facade;
class Notification extends Facade {
protected static function getFacadeAccessor() {
class Notification extends Facade
{
protected static function getFacadeAccessor()
{
return 'notification';
}
}

View file

@ -28,7 +28,8 @@ use Response;
class TracksController extends ApiControllerBase
{
public function postUploadTrack() {
public function postUploadTrack()
{
session_write_close();
$response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true));
@ -53,13 +54,13 @@ class TracksController extends ApiControllerBase
}
public function getUploadStatus($trackId) {
public function getUploadStatus($trackId)
{
$track = Track::findOrFail($trackId);
$this->authorize('edit', $track);
if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json([
'message' => $track->published_at
@ -68,7 +69,6 @@ class TracksController extends ApiControllerBase
'edit_url' => action('ContentController@getTracks', ['id' => $trackId]),
'track_url' => $track->url
], 201);
} else {
// something went wrong
return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500);

View file

@ -26,7 +26,7 @@ use Poniverse\Ponyfm\Commands\SaveAccountSettingsCommand;
use Poniverse\Ponyfm\Models\User;
use Gate;
use Auth;
use Input;
use Illuminate\Support\Facades\Request;
use Response;
class AccountController extends ApiControllerBase
@ -77,6 +77,6 @@ class AccountController extends ApiControllerBase
public function postSave(User $user)
{
return $this->execute(new SaveAccountSettingsCommand(Input::all(), $user));
return $this->execute(new SaveAccountSettingsCommand(Request::all(), $user));
}
}

View file

@ -30,7 +30,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth;
use Gate;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User;
use Response;
use Poniverse\Ponyfm\Models\Track;
@ -39,12 +39,12 @@ class AlbumsController extends ApiControllerBase
{
public function postCreate()
{
return $this->execute(new CreateAlbumCommand(Input::all()));
return $this->execute(new CreateAlbumCommand(Request::all()));
}
public function postEdit($id)
{
return $this->execute(new EditAlbumCommand($id, Input::all()));
return $this->execute(new EditAlbumCommand($id, Request::all()));
}
public function postDelete($id)
@ -75,7 +75,7 @@ class AlbumsController extends ApiControllerBase
App::abort(404);
}
if (Input::get('log')) {
if (Request::get('log')) {
ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW);
$album->view_count++;
}
@ -96,7 +96,6 @@ class AlbumsController extends ApiControllerBase
try {
/** @var Album $album */
$album = Album::with('tracks.trackFiles')->findOrFail($id);
} catch (ModelNotFoundException $e) {
return $this->notFound('Album not found!');
}
@ -121,8 +120,8 @@ class AlbumsController extends ApiControllerBase
public function getIndex()
{
$page = 1;
if (Input::has('page')) {
$page = Input::get('page');
if (Request::has('page')) {
$page = Request::get('page');
}
$query = Album::summary()
@ -144,8 +143,10 @@ class AlbumsController extends ApiControllerBase
$albums[] = Album::mapPublicAlbumSummary($album);
}
return Response::json(["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200);
return Response::json(
["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
}
public function getOwned(User $user)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User;
use Poniverse\Ponyfm\Models\Follower;
use App;
use Input;
use Illuminate\Support\Facades\Request;
use Response;
use ColorThief\ColorThief;
use Helpers;
@ -209,8 +209,8 @@ class ArtistsController extends ApiControllerBase
public function getIndex()
{
$page = 1;
if (Input::has('page')) {
$page = Input::get('page');
if (Request::has('page')) {
$page = Request::get('page');
}
$query = User::where('track_count', '>', 0);
@ -227,12 +227,15 @@ class ArtistsController extends ApiControllerBase
$users[] = User::mapPublicUserSummary($user);
}
return Response::json(["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200);
return Response::json(
["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
}
public function postIndex() {
$name = Input::json('username');
public function postIndex()
{
$name = Request::json('username');
return $this->execute(new CreateUserCommand($name, $name, null, true));
}
}

View file

@ -24,14 +24,14 @@ use App;
use Poniverse\Ponyfm\Commands\CreateCommentCommand;
use Poniverse\Ponyfm\Models\Comment;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input;
use Illuminate\Support\Facades\Request;
use Response;
class CommentsController extends ApiControllerBase
{
public function postCreate($type, $id)
{
return $this->execute(new CreateCommentCommand($type, $id, Input::all()));
return $this->execute(new CreateCommentCommand($type, $id, Request::all()));
}
public function getIndex($type, $id)

View file

@ -27,14 +27,14 @@ use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track;
use Auth;
use Input;
use Illuminate\Support\Facades\Request;
use Response;
class FavouritesController extends ApiControllerBase
{
public function postToggle()
{
return $this->execute(new ToggleFavouriteCommand(Input::get('type'), Input::get('id')));
return $this->execute(new ToggleFavouriteCommand(Request::get('type'), Request::get('id')));
}
public function getTracks()
@ -58,8 +58,7 @@ class FavouritesController extends ApiControllerBase
$tracks = [];
foreach ($query->get() as $fav) {
if ($fav->track == null) // deleted track
{
if ($fav->track == null) { // deleted track
continue;
}
@ -86,8 +85,7 @@ class FavouritesController extends ApiControllerBase
$albums = [];
foreach ($query->get() as $fav) {
if ($fav->album == null) // deleted album
{
if ($fav->album == null) { // deleted album
continue;
}
@ -115,8 +113,7 @@ class FavouritesController extends ApiControllerBase
$playlists = [];
foreach ($query->get() as $fav) {
if ($fav->playlist == null) // deleted playlist
{
if ($fav->playlist == null) { // deleted playlist
continue;
}

View file

@ -22,12 +22,12 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Poniverse\Ponyfm\Commands\ToggleFollowingCommand;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input;
use Illuminate\Support\Facades\Request;
class FollowController extends ApiControllerBase
{
public function postToggle()
{
return $this->execute(new ToggleFollowingCommand(Input::get('type'), Input::get('id')));
return $this->execute(new ToggleFollowingCommand(Request::get('type'), Request::get('id')));
}
}

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateGenreCommand;
use Poniverse\Ponyfm\Commands\DeleteGenreCommand;
use Poniverse\Ponyfm\Commands\RenameGenreCommand;
@ -28,7 +28,6 @@ use Poniverse\Ponyfm\Models\Genre;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response;
class GenresController extends ApiControllerBase
{
public function getIndex()
@ -48,20 +47,20 @@ class GenresController extends ApiControllerBase
public function postCreate()
{
$command = new CreateGenreCommand(Input::get('name'));
$command = new CreateGenreCommand(Request::get('name'));
return $this->execute($command);
}
public function putRename($genreId)
{
$command = new RenameGenreCommand($genreId, Input::get('name'));
$command = new RenameGenreCommand($genreId, Request::get('name'));
return $this->execute($command);
}
public function deleteGenre($genreId)
{
$command = new DeleteGenreCommand($genreId, Input::get('destination_genre_id'));
$command = new DeleteGenreCommand($genreId, Request::get('destination_genre_id'));
return $this->execute($command);
}
}

View file

@ -21,7 +21,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Notification;
use Poniverse\Ponyfm\Models\Subscription;
@ -56,7 +56,7 @@ class NotificationsController extends ApiControllerBase
*/
public function putMarkAsRead()
{
$notificationIds = Input::json('notification_ids');
$notificationIds = Request::json('notification_ids');
$numberOfUpdatedRows = Auth::user()
->notifications()
->whereIn('id', $notificationIds)
@ -74,7 +74,7 @@ class NotificationsController extends ApiControllerBase
*/
public function postSubscribe()
{
$input = json_decode(Input::json('subscription'));
$input = json_decode(Request::json('subscription'));
if ($input != 'null') {
$existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id)
@ -104,7 +104,7 @@ class NotificationsController extends ApiControllerBase
*/
public function postUnsubscribe()
{
$input = json_decode(Input::json('subscription'));
$input = json_decode(Request::json('subscription'));
$existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User;
use Response;
use Poniverse\Ponyfm\Models\Track;
@ -40,12 +40,12 @@ class PlaylistsController extends ApiControllerBase
{
public function postCreate()
{
return $this->execute(new CreatePlaylistCommand(Input::all()));
return $this->execute(new CreatePlaylistCommand(Request::all()));
}
public function postEdit($id)
{
return $this->execute(new EditPlaylistCommand($id, Input::all()));
return $this->execute(new EditPlaylistCommand($id, Request::all()));
}
public function postDelete($id)
@ -55,27 +55,29 @@ class PlaylistsController extends ApiControllerBase
public function postAddTrack($id)
{
return $this->execute(new AddTrackToPlaylistCommand($id, Input::get('track_id')));
return $this->execute(new AddTrackToPlaylistCommand($id, Request::get('track_id')));
}
public function postRemoveTrack($id)
{
return $this->execute(new RemoveTrackFromPlaylistCommand($id, Input::get('track_id')));
return $this->execute(new RemoveTrackFromPlaylistCommand($id, Request::get('track_id')));
}
public function getIndex()
{
$page = Input::has('page') ? Input::get('page') : 1;
$page = Request::has('page') ? Request::get('page') : 1;
$query = Playlist::summary()
->with('user',
->with(
'user',
'user.avatar',
'tracks',
'tracks.cover',
'tracks.user',
'tracks.user.avatar',
'tracks.album',
'tracks.album.user')
'tracks.album.user'
)
->userDetails()
// A playlist with only one track is not much of a list.
->where('track_count', '>', 1)
@ -117,7 +119,7 @@ class PlaylistsController extends ApiControllerBase
App::abort('404');
}
if (Input::get('log')) {
if (Request::get('log')) {
ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW);
$playlist->view_count++;
}
@ -221,8 +223,8 @@ class PlaylistsController extends ApiControllerBase
*/
private function applyOrdering($query)
{
if (Input::has('order')) {
$order = \Input::get('order');
if (Request::has('order')) {
$order = \Request::get('order');
$parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]);
}

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Elasticsearch;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Library\Search;
use Response;
@ -30,7 +30,7 @@ class SearchController extends ApiControllerBase
{
public function getSearch(Search $search)
{
$results = $search->searchAllContent(Input::query('query'));
$results = $search->searchAllContent(Request::query('query'));
return Response::json([
'results' => $results,

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateShowSongCommand;
use Poniverse\Ponyfm\Commands\DeleteShowSongCommand;
use Poniverse\Ponyfm\Commands\RenameShowSongCommand;
@ -28,7 +28,6 @@ use Poniverse\Ponyfm\Models\ShowSong;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response;
class ShowSongsController extends ApiControllerBase
{
public function getIndex()
@ -49,20 +48,20 @@ class ShowSongsController extends ApiControllerBase
public function postCreate()
{
$command = new CreateShowSongCommand(Input::get('title'));
$command = new CreateShowSongCommand(Request::get('title'));
return $this->execute($command);
}
public function putRename($songId)
{
$command = new RenameShowSongCommand($songId, Input::get('title'));
$command = new RenameShowSongCommand($songId, Request::get('title'));
return $this->execute($command);
}
public function deleteSong($songId)
{
$command = new DeleteShowSongCommand($songId, Input::get('destination_song_id'));
$command = new DeleteShowSongCommand($songId, Request::get('destination_song_id'));
return $this->execute($command);
}
}

View file

@ -32,7 +32,8 @@ use Carbon\Carbon;
class StatsController extends ApiControllerBase
{
private function getStatsData($id, $hourly = false) {
private function getStatsData($id, $hourly = false)
{
$playRange = "'1 MONTH'";
if ($hourly) {
@ -51,7 +52,8 @@ class StatsController extends ApiControllerBase
return $statQuery;
}
private function sortTrackStatsArray($query, $hourly = false) {
private function sortTrackStatsArray($query, $hourly = false)
{
$now = Carbon::now();
$playsArray = [];
$output = [];
@ -104,7 +106,8 @@ class StatsController extends ApiControllerBase
}
}
public function getTrackStats($id) {
public function getTrackStats($id)
{
$cachedOutput = Cache::remember('track_stats'.$id, 5, function () use ($id) {
try {
$track = Track::published()->findOrFail($id);

View file

@ -37,12 +37,18 @@ class TaxonomiesController extends ApiControllerBase
->orderBy('name')
->get()
->toArray(),
'track_types' => TrackType::select('track_types.*',
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count'))
'track_types' => TrackType::select(
'track_types.*',
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')
)
->where('id', '!=', TrackType::UNCLASSIFIED_TRACK)
->get()->toArray(),
'show_songs' => ShowSong::select('title', 'id', 'slug',
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count'))->orderBy('title')->get()->toArray()
'show_songs' => ShowSong::select(
'title',
'id',
'slug',
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count')
)->orderBy('title')->get()->toArray()
], 200);
}
}

View file

@ -23,7 +23,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth;
use File;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\DeleteTrackCommand;
use Poniverse\Ponyfm\Commands\EditTrackCommand;
use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand;
@ -55,10 +55,8 @@ class TracksController extends ApiControllerBase
if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201);
} else {
// something went wrong
return Response::json(['error' => 'Processing failed!'], 500);
@ -72,7 +70,7 @@ class TracksController extends ApiControllerBase
public function postEdit($id)
{
return $this->execute(new EditTrackCommand($id, Input::all()));
return $this->execute(new EditTrackCommand($id, Request::all()));
}
public function postUploadNewVersion($trackId)
@ -97,10 +95,8 @@ class TracksController extends ApiControllerBase
if ($track->version_upload_status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->version_upload_status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201);
} else {
// something went wrong
return Response::json(['error' => 'Processing failed!'], 500);
@ -151,7 +147,7 @@ class TracksController extends ApiControllerBase
return $this->notFound('Track not found!');
}
if (Input::get('log')) {
if (Request::get('log')) {
ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW);
$track->view_count++;
}
@ -209,8 +205,8 @@ class TracksController extends ApiControllerBase
$page = 1;
$perPage = 45;
if (Input::has('page')) {
$page = Input::get('page');
if (Request::has('page')) {
$page = Request::get('page');
}
if ($all) {
@ -295,8 +291,8 @@ class TracksController extends ApiControllerBase
*/
private function applyOrdering($query)
{
if (Input::has('order')) {
$order = \Input::get('order');
if (Request::has('order')) {
$order = \Request::get('order');
$parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]);
}
@ -312,8 +308,8 @@ class TracksController extends ApiControllerBase
*/
private function applyFilters($query, $unknown = false)
{
if (Input::has('is_vocal')) {
$isVocal = \Input::get('is_vocal');
if (Request::has('is_vocal')) {
$isVocal = \Request::get('is_vocal');
if ($isVocal == 'true') {
$query->whereIsVocal(true);
} else {
@ -321,20 +317,20 @@ class TracksController extends ApiControllerBase
}
}
if (Input::has('in_album')) {
if (Input::get('in_album') == 'true') {
if (Request::has('in_album')) {
if (Request::get('in_album') == 'true') {
$query->whereNotNull('album_id');
} else {
$query->whereNull('album_id');
}
}
if (Input::has('genres')) {
$query->whereIn('genre_id', Input::get('genres'));
if (Request::has('genres')) {
$query->whereIn('genre_id', Request::get('genres'));
}
if (Input::has('types') && !$unknown) {
$query->whereIn('track_type_id', Input::get('types'));
if (Request::has('types') && !$unknown) {
$query->whereIn('track_type_id', Request::get('types'));
}
if ($unknown) {
@ -351,14 +347,14 @@ class TracksController extends ApiControllerBase
$query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id');
}
if (Input::has('songs')) {
if (Request::has('songs')) {
// DISTINCT is needed here to avoid duplicate results
// when a track is associated with multiple show songs.
$query->distinct();
$query->join('show_song_track', function ($join) {
$join->on('tracks.id', '=', 'show_song_track.track_id');
});
$query->whereIn('show_song_track.show_song_id', Input::get('songs'));
$query->whereIn('show_song_track.show_song_id', Request::get('songs'));
}
return $query;

View file

@ -32,11 +32,13 @@ class ArtistsController extends Controller
return View::make('artists.index');
}
public function getFavourites($slug) {
public function getFavourites($slug)
{
return $this->getProfile($slug);
}
public function getContent($slug) {
public function getContent($slug)
{
return $this->getProfile($slug);
}
@ -53,7 +55,7 @@ class ArtistsController extends Controller
public function getShortlink($id)
{
$user = User::find($id);
if (!$user || $user->disabled_at !== NULL) {
if (!$user || $user->disabled_at !== null) {
App::abort('404');
}

View file

@ -24,7 +24,7 @@ use Poniverse\Ponyfm\Models\User;
use Auth;
use Config;
use DB;
use Input;
use Illuminate\Support\Facades\Request;
use Poniverse;
use Redirect;
@ -60,23 +60,29 @@ class AuthController extends Controller
Config::get('poniverse.urls')['token'],
'authorization_code',
[
'code' => Input::query('code'),
'code' => Request::query('code'),
'redirect_uri' => action('AuthController@getOAuth')
]);
]
);
if ($code['code'] != 200) {
if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) {
return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt'));
}
return Redirect::to('/')->with('message',
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.');
return Redirect::to('/')->with(
'message',
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'
);
}
$this->poniverse->setAccessToken($code['result']['access_token']);
$poniverseUser = $this->poniverse->getUser();
$token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where('service', '=',
'poniverse')->first();
$token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where(
'service',
'=',
'poniverse'
)->first();
$setData = [
'access_token' => $code['result']['access_token'],

View file

@ -21,11 +21,12 @@
namespace Poniverse\Ponyfm\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController
class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests, AuthorizesRequests;
}

View file

@ -153,12 +153,16 @@ class TracksController extends Controller
if (Config::get('app.sendfile')) {
$response->header('X-Sendfile', $filename);
$response->header('Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"');
$response->header(
'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
} else {
$response->header('X-Accel-Redirect', $filename);
$response->header('Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"');
$response->header(
'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
}
$time = gmdate(filemtime($filename));

View file

@ -31,12 +31,17 @@ class Kernel extends HttpKernel
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class,
\Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class,
]
];
/**
@ -48,8 +53,10 @@ class Kernel extends HttpKernel
'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class,
'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class,
// 'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class,
'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View file

@ -46,7 +46,8 @@ class AuthenticateOAuth
*/
private $session;
public function __construct(Poniverse $poniverse, Guard $auth, Store $session) {
public function __construct(Poniverse $poniverse, Guard $auth, Store $session)
{
$this->poniverse = $poniverse;
$this->auth = $auth;
$this->session = $session;

View file

@ -37,7 +37,8 @@ class DisabledAccountCheck
*
* @param Guard $auth
*/
public function __construct(Guard $auth) {
public function __construct(Guard $auth)
{
$this->auth = $auth;
}

View file

@ -43,7 +43,6 @@ class JsonExceptions
{
try {
$response = $next($request);
} catch (HttpException $e) {
return \Response::json([
'message' => $e->getMessage()

View file

@ -21,40 +21,24 @@
namespace Poniverse\Ponyfm\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Auth\AuthManager;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next)
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->check()) {
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}

View file

@ -55,9 +55,15 @@ Route::get('/login', 'AuthController@getLogin');
Route::post('/auth/logout', 'AuthController@postLogout');
Route::get('/auth/oauth', 'AuthController@getOAuth');
Route::get('/about', function() { return View::make('pages.about'); });
Route::get('/faq', function() { return View::make('pages.faq'); });
Route::get('/mlpforums-advertising-program', function() { return View::make('pages.mlpforums-advertising-program'); });
Route::get('/about', function () {
return View::make('pages.about');
});
Route::get('/faq', function () {
return View::make('pages.faq');
});
Route::get('/mlpforums-advertising-program', function () {
return View::make('pages.mlpforums-advertising-program');
});
Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+');

View file

@ -24,12 +24,11 @@ use Auth;
use DB;
use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track;
use SerializesModels;
class DeleteGenre extends Job implements SelfHandling, ShouldQueue
class DeleteGenre extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;

View file

@ -24,12 +24,11 @@ use Auth;
use DB;
use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track;
use SerializesModels;
class DeleteShowSong extends Job implements SelfHandling, ShouldQueue
class DeleteShowSong extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;

View file

@ -25,7 +25,6 @@ use Carbon\Carbon;
use Config;
use DB;
use File;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
@ -36,7 +35,7 @@ use Poniverse\Ponyfm\Models\TrackFile;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
class EncodeTrackFile extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
@ -70,8 +69,7 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
*/
public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false)
{
if (
(!$isForUpload && $trackFile->is_master) ||
if ((!$isForUpload && $trackFile->is_master) ||
($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless'])
) {
throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process.");
@ -97,7 +95,6 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!');
return;
} elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.');
return;

View file

@ -44,7 +44,8 @@ abstract class Job
* method. It ensures that we don't lose the in-memory database during
* testing by disconnecting from it - which causes tests to fail.
*/
protected function beforeHandle() {
protected function beforeHandle()
{
if (App::environment() !== 'testing') {
DB::reconnect();
}

View file

@ -23,14 +23,13 @@ namespace Poniverse\Ponyfm\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver;
use Poniverse\Ponyfm\Models\User;
use SerializesModels;
class SendNotifications extends Job implements SelfHandling, ShouldQueue
class SendNotifications extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;

View file

@ -26,10 +26,9 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Contracts\Searchable;
use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use SerializesModels;
class UpdateSearchIndexForEntity extends Job implements SelfHandling, ShouldQueue
class UpdateSearchIndexForEntity extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;

View file

@ -26,7 +26,6 @@ use DB;
use Log;
use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track;
use SerializesModels;
@ -39,7 +38,7 @@ use SerializesModels;
*
* @package Poniverse\Ponyfm\Jobs
*/
class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue
class UpdateTagsForRenamedGenre extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
@ -77,7 +76,6 @@ class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue
Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds.");
$this->release(30);
return;
} else {
Cache::forever($this->lockKey, true);
}

View file

@ -25,7 +25,6 @@ use Cache;
use Log;
use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track;
use SerializesModels;
@ -38,7 +37,7 @@ use SerializesModels;
*
* @package Poniverse\Ponyfm\Jobs
*/
class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQueue
class UpdateTagsForRenamedShowSong extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
@ -76,7 +75,6 @@ class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQu
Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds.");
$this->release(30);
return;
} else {
Cache::forever($this->lockKey, true);
}

View file

@ -20,7 +20,8 @@
class Assets
{
public static function scriptIncludes(string $area) {
public static function scriptIncludes(string $area)
{
$scriptTags = '';
if ('app' === $area) {

View file

@ -20,7 +20,7 @@
class AudioCache
{
private static $_movieCache = array();
private static $_movieCache = [];
public static function get(string $filename):FFmpegMovie
{

View file

@ -28,5 +28,4 @@ class File extends \Illuminate\Support\Facades\File
return $response;
}
}

View file

@ -47,7 +47,7 @@ class Helpers
return '0 MB';
}
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
@ -82,7 +82,8 @@ class Helpers
* @param array[int] $rgb RGB values in an array
* @return string
*/
public static function rgb2hex($rgb) {
public static function rgb2hex($rgb)
{
$hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);

View file

@ -25,10 +25,12 @@ use Poniverse\Ponyfm\Contracts\NotificationHandler;
use Poniverse\Ponyfm\Library\Notifications\RecipientFinder;
use Poniverse\Ponyfm\Models\User;
abstract class AbstractDriver implements NotificationHandler {
abstract class AbstractDriver implements NotificationHandler
{
private $recipientFinder;
public function __construct() {
public function __construct()
{
$this->recipientFinder = new RecipientFinder(get_class($this));
}
@ -41,7 +43,8 @@ abstract class AbstractDriver implements NotificationHandler {
* @param array $notificationData
* @return User[] collection of {@link User} objects
*/
protected function getRecipients(string $notificationType, array $notificationData) {
protected function getRecipients(string $notificationType, array $notificationData)
{
return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData);
}
}

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use Config;
use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Models\Activity;
@ -30,7 +29,8 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User;
use Minishlink\WebPush\WebPush;
class NativeDriver extends AbstractDriver {
class NativeDriver extends AbstractDriver
{
/**
* Method for sending notifications to devices
*
@ -40,9 +40,9 @@ class NativeDriver extends AbstractDriver {
private function pushNotifications(Activity $activity, $recipients)
{
if (Config::get('ponyfm.gcm_key') != 'default') {
$apiKeys = array(
$apiKeys = [
'GCM' => Config::get('ponyfm.gcm_key'),
);
];
$webPush = new WebPush($apiKeys);
@ -72,7 +72,8 @@ class NativeDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function publishedNewTrack(Track $track) {
public function publishedNewTrack(Track $track)
{
$activity = Activity::where('user_id', $track->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_TRACK)
->where('resource_id', $track->id)
@ -85,7 +86,8 @@ class NativeDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function publishedNewPlaylist(Playlist $playlist) {
public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::where('user_id', $playlist->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST)
->where('resource_id', $playlist->id)
@ -94,7 +96,8 @@ class NativeDriver extends AbstractDriver {
$this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args()));
}
public function newFollower(User $userBeingFollowed, User $follower) {
public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::where('user_id', $follower->id)
->where('activity_type', Activity::TYPE_NEW_FOLLOWER)
->where('resource_id', $userBeingFollowed->id)
@ -106,7 +109,8 @@ class NativeDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function newComment(Comment $comment) {
public function newComment(Comment $comment)
{
$activity = Activity::where('user_id', $comment->user_id)
->where('activity_type', Activity::TYPE_NEW_COMMENT)
->where('resource_id', $comment->id)
@ -118,7 +122,8 @@ class NativeDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) {
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::where('user_id', $favouriter->id)
->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED)
->where('resource_id', $entityBeingFavourited->id)

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use ArrayAccess;
use Carbon\Carbon;
use Poniverse\Ponyfm\Contracts\Favouritable;
@ -31,14 +30,16 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User;
class PonyfmDriver extends AbstractDriver {
class PonyfmDriver extends AbstractDriver
{
/**
* A helper method for bulk insertion of notification records.
*
* @param int $activityId
* @param User[] $recipients collection of {@link User} objects
*/
private function insertNotifications(int $activityId, $recipients) {
private function insertNotifications(int $activityId, $recipients)
{
$notifications = [];
foreach ($recipients as $recipient) {
$notifications[] = [
@ -52,7 +53,8 @@ class PonyfmDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function publishedNewTrack(Track $track) {
public function publishedNewTrack(Track $track)
{
$activity = Activity::create([
'created_at' => Carbon::now(),
'user_id' => $track->user_id,
@ -67,7 +69,8 @@ class PonyfmDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function publishedNewPlaylist(Playlist $playlist) {
public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::create([
'created_at' => Carbon::now(),
'user_id' => $playlist->user_id,
@ -79,7 +82,8 @@ class PonyfmDriver extends AbstractDriver {
$this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args()));
}
public function newFollower(User $userBeingFollowed, User $follower) {
public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::create([
'created_at' => Carbon::now(),
'user_id' => $follower->id,
@ -94,7 +98,8 @@ class PonyfmDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function newComment(Comment $comment) {
public function newComment(Comment $comment)
{
$activity = Activity::create([
'created_at' => Carbon::now(),
'user_id' => $comment->user_id,
@ -109,7 +114,8 @@ class PonyfmDriver extends AbstractDriver {
/**
* @inheritdoc
*/
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) {
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::create([
'created_at' => Carbon::now(),
'user_id' => $favouriter->id,

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -39,45 +38,52 @@ use Poniverse\Ponyfm\Models\User;
* All the heavy lifting happens asynchronously in the {@link SendNotifications}
* job and the notification drivers.
*/
class NotificationManager implements NotificationHandler {
class NotificationManager implements NotificationHandler
{
use DispatchesJobs;
private function dispatchNotification(string $notificationType, array $notificationData) {
private function dispatchNotification(string $notificationType, array $notificationData)
{
$this->dispatch((new SendNotifications($notificationType, $notificationData))->onQueue('notifications'));
}
/**
* @inheritdoc
*/
public function publishedNewTrack(Track $track) {
public function publishedNewTrack(Track $track)
{
$this->dispatchNotification(__FUNCTION__, func_get_args());
}
/**
* @inheritdoc
*/
public function publishedNewPlaylist(Playlist $playlist) {
public function publishedNewPlaylist(Playlist $playlist)
{
$this->dispatchNotification(__FUNCTION__, func_get_args());
}
/**
* @inheritdoc
*/
public function newFollower(User $userBeingFollowed, User $follower) {
public function newFollower(User $userBeingFollowed, User $follower)
{
$this->dispatchNotification(__FUNCTION__, func_get_args());
}
/**
* @inheritdoc
*/
public function newComment(Comment $comment) {
public function newComment(Comment $comment)
{
$this->dispatchNotification(__FUNCTION__, func_get_args());
}
/**
* @inheritdoc
*/
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) {
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$this->dispatchNotification(__FUNCTION__, func_get_args());
}
}

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -40,24 +39,28 @@ use Poniverse\Ponyfm\Models\User;
* This class returns a list of users who are to receive a particular notification.
* It is instantiated on a per-driver basis.
*/
class RecipientFinder implements NotificationHandler {
class RecipientFinder implements NotificationHandler
{
/**
* @var string class name of a notification driver
*/
private $notificationDriver;
public function __construct(string $notificationDriver) {
public function __construct(string $notificationDriver)
{
$this->notificationDriver = $notificationDriver;
}
private function fail() {
private function fail()
{
throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}");
}
/**
* @inheritdoc
*/
public function publishedNewTrack(Track $track) {
public function publishedNewTrack(Track $track)
{
switch ($this->notificationDriver) {
case PonyfmDriver::class:
return $track->user->followers;
@ -84,7 +87,8 @@ class RecipientFinder implements NotificationHandler {
/**
* @inheritdoc
*/
public function publishedNewPlaylist(Playlist $playlist) {
public function publishedNewPlaylist(Playlist $playlist)
{
switch ($this->notificationDriver) {
case PonyfmDriver::class:
return $playlist->user->followers;
@ -111,7 +115,8 @@ class RecipientFinder implements NotificationHandler {
/**
* @inheritdoc
*/
public function newFollower(User $userBeingFollowed, User $follower) {
public function newFollower(User $userBeingFollowed, User $follower)
{
switch ($this->notificationDriver) {
case PonyfmDriver::class:
return [$userBeingFollowed];
@ -125,7 +130,8 @@ class RecipientFinder implements NotificationHandler {
/**
* @inheritdoc
*/
public function newComment(Comment $comment) {
public function newComment(Comment $comment)
{
switch ($this->notificationDriver) {
case PonyfmDriver::class:
return
@ -142,7 +148,8 @@ class RecipientFinder implements NotificationHandler {
/**
* @inheritdoc
*/
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) {
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
switch ($this->notificationDriver) {
case PonyfmDriver::class:
return

View file

@ -257,7 +257,7 @@ class PfmValidator extends Illuminate\Validation\Validator
/** OLD CODE
* public function validate_required_when($attribute, $value, $parameters)
* {
* if ( Input::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){
* if ( Request::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){
* return true;
*
* } else {
@ -269,7 +269,7 @@ class PfmValidator extends Illuminate\Validation\Validator
// custom required_when validator
public function validateRequiredWhen($attribute, $value, $parameters)
{
if (Input::get($parameters[0]) == $parameters[1]) {
if (Request::get($parameters[0]) == $parameters[1]) {
return $this->validate_required($attribute, $value);
}

View file

@ -28,7 +28,8 @@ namespace Poniverse;
* @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06
* @package Poniverse
*/
class AccessTokenInfo {
class AccessTokenInfo
{
protected $token;
protected $isActive;
@ -42,21 +43,24 @@ class AccessTokenInfo {
protected $issuer;
protected $tokenType;
public function __construct($accessToken) {
public function __construct($accessToken)
{
$this->token = $accessToken;
}
/**
* @return mixed
*/
public function getToken() {
public function getToken()
{
return $this->token;
}
/**
* @return bool
*/
public function getIsActive() {
public function getIsActive()
{
return $this->isActive;
}
@ -64,7 +68,8 @@ class AccessTokenInfo {
* @param bool $isActive
* @return AccessTokenInfo
*/
public function setIsActive($isActive) {
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
@ -72,7 +77,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getExpiresAt() {
public function getExpiresAt()
{
return $this->expiresAt;
}
@ -80,7 +86,8 @@ class AccessTokenInfo {
* @param mixed $expiresAt
* @return AccessTokenInfo
*/
public function setExpiresAt($expiresAt) {
public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt;
return $this;
}
@ -88,7 +95,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getIssuedAt() {
public function getIssuedAt()
{
return $this->issuedAt;
}
@ -96,7 +104,8 @@ class AccessTokenInfo {
* @param mixed $issuedAt
* @return AccessTokenInfo
*/
public function setIssuedAt($issuedAt) {
public function setIssuedAt($issuedAt)
{
$this->issuedAt = $issuedAt;
return $this;
}
@ -104,7 +113,8 @@ class AccessTokenInfo {
/**
* @return array
*/
public function getScopes() {
public function getScopes()
{
return $this->scopes;
}
@ -112,7 +122,8 @@ class AccessTokenInfo {
* @param array|string $scopes
* @return AccessTokenInfo
*/
public function setScopes($scopes) {
public function setScopes($scopes)
{
if (is_array($scopes)) {
$this->scopes = $scopes;
} else {
@ -125,7 +136,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getClientId() {
public function getClientId()
{
return $this->clientId;
}
@ -133,7 +145,8 @@ class AccessTokenInfo {
* @param mixed $clientId
* @return AccessTokenInfo
*/
public function setClientId($clientId) {
public function setClientId($clientId)
{
$this->clientId = $clientId;
return $this;
}
@ -141,7 +154,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getSub() {
public function getSub()
{
return $this->sub;
}
@ -149,7 +163,8 @@ class AccessTokenInfo {
* @param mixed $sub
* @return AccessTokenInfo
*/
public function setSub($sub) {
public function setSub($sub)
{
$this->sub = $sub;
return $this;
}
@ -157,7 +172,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getUserId() {
public function getUserId()
{
return $this->userId;
}
@ -165,7 +181,8 @@ class AccessTokenInfo {
* @param mixed $userId
* @return AccessTokenInfo
*/
public function setUserId($userId) {
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
@ -173,7 +190,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getIntendedAudience() {
public function getIntendedAudience()
{
return $this->intendedAudience;
}
@ -181,7 +199,8 @@ class AccessTokenInfo {
* @param mixed $intendedAudience
* @return AccessTokenInfo
*/
public function setIntendedAudience($intendedAudience) {
public function setIntendedAudience($intendedAudience)
{
$this->intendedAudience = $intendedAudience;
return $this;
}
@ -189,7 +208,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getIssuer() {
public function getIssuer()
{
return $this->issuer;
}
@ -197,7 +217,8 @@ class AccessTokenInfo {
* @param mixed $issuer
* @return AccessTokenInfo
*/
public function setIssuer($issuer) {
public function setIssuer($issuer)
{
$this->issuer = $issuer;
return $this;
}
@ -205,7 +226,8 @@ class AccessTokenInfo {
/**
* @return mixed
*/
public function getTokenType() {
public function getTokenType()
{
return $this->tokenType;
}
@ -213,7 +235,8 @@ class AccessTokenInfo {
* @param mixed $tokenType
* @return AccessTokenInfo
*/
public function setTokenType($tokenType) {
public function setTokenType($tokenType)
{
$this->tokenType = $tokenType;
return $this;
}

View file

@ -28,7 +28,8 @@ use Poniverse\Ponyfm\Exceptions\InvalidAccessTokenException;
* this class is going to be a simple flat api class.
*/
class Poniverse {
class Poniverse
{
protected $clientId;
protected $clientSecret;
protected $accessToken;

View file

@ -102,7 +102,7 @@ class SplClassLoader
*/
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
spl_autoload_register([$this, 'loadClass']);
}
/**
@ -110,7 +110,7 @@ class SplClassLoader
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
spl_autoload_unregister([$this, 'loadClass']);
}
/**

View file

@ -5,7 +5,7 @@ require(__DIR__ . '/../bootstrap.php');
// a parser with different configuration options for a particular mime type
// Example setting a namespace for the XMLHandler parser
$conf = array('namespace' => 'http://example.com');
$conf = ['namespace' => 'http://example.com'];
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
// We can also add the parsers with our own...

View file

@ -14,7 +14,7 @@ $response = Request::get($uri)
echo "The event {$response->body->event} will take place on {$response->body->event_start}\n";
// Example overriding the default JSON handler with one that encodes the response as an array
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(['decode_as_array' => true]));
$response = Request::get($uri)
->expectsType('json')

View file

@ -21,7 +21,7 @@ class Bootstrap
*/
public static function init()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'autoload'));
spl_autoload_register(['\Httpful\Bootstrap', 'autoload']);
self::registerHandlers();
}
@ -40,7 +40,7 @@ class Bootstrap
*/
public static function pharInit()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload'));
spl_autoload_register(['\Httpful\Bootstrap', 'pharAutoload']);
self::registerHandlers();
}
@ -78,17 +78,18 @@ class Bootstrap
// @todo check a conf file to load from that instead of
// hardcoding into the library?
$handlers = array(
$handlers = [
\Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(),
\Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(),
\Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(),
\Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(),
);
];
foreach ($handlers as $mime => $handler) {
// Don't overwrite if the handler has already been registered
if (Httpful::hasParserRegistered($mime))
if (Httpful::hasParserRegistered($mime)) {
continue;
}
Httpful::register($mime, $handler);
}

View file

@ -14,17 +14,19 @@ class CsvHandler extends MimeHandlerAdapter
*/
public function parse($body)
{
if (empty($body))
if (empty($body)) {
return null;
}
$parsed = array();
$parsed = [];
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
while (($r = fgetcsv($fp)) !== FALSE) {
while (($r = fgetcsv($fp)) !== false) {
$parsed[] = $r;
}
if (empty($parsed))
if (empty($parsed)) {
throw new \Exception("Unable to parse response as CSV");
}
return $parsed;
}

View file

@ -14,7 +14,7 @@ class FormHandler extends MimeHandlerAdapter
*/
public function parse($body)
{
$parsed = array();
$parsed = [];
parse_str($body, $parsed);
return $parsed;
}

View file

@ -21,11 +21,13 @@ class JsonHandler extends MimeHandlerAdapter
*/
public function parse($body)
{
if (empty($body))
if (empty($body)) {
return null;
}
$parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed))
if (is_null($parsed)) {
throw new \Exception("Unable to parse response as JSON");
}
return $parsed;
}

View file

@ -10,7 +10,7 @@ namespace Httpful\Handlers;
class MimeHandlerAdapter
{
public function __construct(array $args = array())
public function __construct(array $args = [])
{
$this->init($args);
}

View file

@ -23,7 +23,7 @@ class XmlHandler extends MimeHandlerAdapter
/**
* @param array $conf sets configuration options
*/
public function __construct(array $conf = array())
public function __construct(array $conf = [])
{
$this->namespace = isset($conf['namespace']) ? $conf['namespace'] : '';
$this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0;
@ -36,11 +36,13 @@ class XmlHandler extends MimeHandlerAdapter
*/
public function parse($body)
{
if (empty($body))
if (empty($body)) {
return null;
}
$parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace);
if ($parsed === false)
if ($parsed === false) {
throw new \Exception("Unable to parse response as XML");
}
return $parsed;
}
@ -84,7 +86,7 @@ class XmlHandler extends MimeHandlerAdapter
} else {
$node->appendChild($dom->createTextNode($value));
}
return array($node, $dom);
return [$node, $dom];
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
@ -100,7 +102,7 @@ class XmlHandler extends MimeHandlerAdapter
$parent->appendChild($el);
$this->_future_serializeAsXml($v, $el, $dom);
}
return array($parent, $dom);
return [$parent, $dom];
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
@ -115,6 +117,6 @@ class XmlHandler extends MimeHandlerAdapter
$this->_future_serializeAsXml($pr->getValue($value), $el, $dom);
}
}
return array($parent, $dom);
return [$parent, $dom];
}
}

View file

@ -21,7 +21,7 @@ class Http
*/
public static function safeMethods()
{
return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE);
return [self::HEAD, self::GET, self::OPTIONS, self::TRACE];
}
/**
@ -50,7 +50,7 @@ class Http
// Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than
// not, it is not.
return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH);
return [self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH];
}
/**
@ -80,7 +80,6 @@ class Http
*/
public static function canHaveBody()
{
return array(self::POST, self::PUT, self::PATCH, self::OPTIONS);
return [self::POST, self::PUT, self::PATCH, self::OPTIONS];
}
}

View file

@ -2,10 +2,11 @@
namespace Httpful;
class Httpful {
class Httpful
{
const VERSION = '0.2.4';
private static $mimeRegistrar = array();
private static $mimeRegistrar = [];
private static $default = null;
/**

View file

@ -22,7 +22,7 @@ class Mime
* Map short name for a mime type
* to a full proper mime type
*/
public static $mimes = array(
public static $mimes = [
'json' => self::JSON,
'xml' => self::XML,
'form' => self::FORM,
@ -34,7 +34,7 @@ class Mime
'javascript'=> self::JS,
'yaml' => self::YAML,
'csv' => self::CSV,
);
];
/**
* Get the full Mime Type name from a "short name".

View file

@ -30,12 +30,12 @@ class Request
public $uri,
$method = Http::GET,
$headers = array(),
$headers = [],
$raw_headers = '',
$strict_ssl = false,
$content_type,
$expected_type,
$additional_curl_opts = array(),
$additional_curl_opts = [],
$auto_parse = true,
$serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART,
$username,
@ -46,7 +46,7 @@ class Request
$error_callback,
$follow_redirects = false,
$max_redirects = self::MAX_REDIRECTS_DEFAULT,
$payload_serializers = array();
$payload_serializers = [];
// Options
// private $_options = array(
@ -70,7 +70,9 @@ class Request
*/
private function __construct($attrs = null)
{
if (!is_array($attrs)) return;
if (!is_array($attrs)) {
return;
}
foreach ($attrs as $attr => $value) {
$this->$attr = $value;
}
@ -195,8 +197,9 @@ class Request
*/
public function send()
{
if (!$this->hasBeenInitialized())
if (!$this->hasBeenInitialized()) {
$this->_curlPrep();
}
$result = curl_exec($this->_ch);
@ -275,7 +278,8 @@ class Request
/**
* @return is this request setup for client side cert?
*/
public function hasClientSideCert() {
public function hasClientSideCert()
{
return isset($this->client_cert) && isset($this->client_key);
}
@ -326,7 +330,9 @@ class Request
*/
public function mime($mime)
{
if (empty($mime)) return $this;
if (empty($mime)) {
return $this;
}
$this->content_type = $this->expected_type = Mime::getFullMime($mime);
return $this;
}
@ -349,7 +355,9 @@ class Request
*/
public function method($method)
{
if (empty($method)) return $this;
if (empty($method)) {
return $this;
}
$this->method = $method;
return $this;
}
@ -360,7 +368,9 @@ class Request
*/
public function expects($mime)
{
if (empty($mime)) return $this;
if (empty($mime)) {
return $this;
}
$this->expected_type = Mime::getFullMime($mime);
return $this;
}
@ -376,7 +386,9 @@ class Request
*/
public function contentType($mime)
{
if (empty($mime)) return $this;
if (empty($mime)) {
return $this;
}
$this->content_type = Mime::getFullMime($mime);
return $this;
}
@ -419,9 +431,10 @@ class Request
* @param string $auth_username Authentication username. Default null
* @param string $auth_password Authentication password. Default null
*/
public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null){
public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null)
{
$this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}");
if(in_array($auth_type, array(CURLAUTH_BASIC,CURLAUTH_NTLM)) ){
if (in_array($auth_type, [CURLAUTH_BASIC,CURLAUTH_NTLM])) {
$this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type)
->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}");
}
@ -431,7 +444,8 @@ class Request
/**
* @return is this request setup for using proxy?
*/
public function hasProxy(){
public function hasProxy()
{
return is_string($this->additional_curl_opts[CURLOPT_PROXY]);
}
@ -646,15 +660,17 @@ class Request
// This method also adds the custom header support as described in the
// method comments
if (count($args) === 0)
if (count($args) === 0) {
return;
}
// Strip the sugar. If it leads with "with", strip.
// This is okay because: No defined HTTP headers begin with with,
// and if you are defining a custom header, the standard is to prefix it
// with an "X-", so that should take care of any collisions.
if (substr($method, 0, 4) === 'with')
if (substr($method, 0, 4) === 'with') {
$method = substr($method, 4);
}
// Precede upper case letters with dashes, uppercase the first letter of method
$header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)));
@ -681,7 +697,7 @@ class Request
// recusion. Do not use this syntax elsewhere.
// It goes against the whole readability
// and transparency idea.
self::$_template = new Request(array('method' => Http::GET));
self::$_template = new Request(['method' => Http::GET]);
// This is more like it...
self::$_template
@ -695,12 +711,14 @@ class Request
*/
private function _setDefaults()
{
if (!isset(self::$_template))
if (!isset(self::$_template)) {
self::_initializeDefaults();
}
foreach (self::$_template as $k => $v) {
if ($k[0] != '_')
if ($k[0] != '_') {
$this->$k = $v;
}
}
return $this;
}
@ -725,8 +743,9 @@ class Request
Bootstrap::init();
// Setup the default template if need be
if (!isset(self::$_template))
if (!isset(self::$_template)) {
self::_initializeDefaults();
}
$request = new Request();
return $request
@ -745,8 +764,9 @@ class Request
public function _curlPrep()
{
// Check for required stuff
if (!isset($this->uri))
if (!isset($this->uri)) {
throw new \Exception('Attempting to send a request before defining a URI endpoint.');
}
$ch = curl_init($this->uri);
@ -757,12 +777,13 @@ class Request
}
if ($this->hasClientSideCert()) {
if (!file_exists($this->client_key))
if (!file_exists($this->client_key)) {
throw new \Exception('Could not read Client Key');
}
if (!file_exists($this->client_cert))
if (!file_exists($this->client_cert)) {
throw new \Exception('Could not read Client Certificate');
}
curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding);
@ -792,7 +813,7 @@ class Request
$this->headers['Content-Length'] = strlen($this->serialized_payload);
}
$headers = array();
$headers = [];
// https://github.com/nategood/httpful/issues/37
// Except header removes any HTTP 1.1 Continue from response headers
$headers[] = 'Expect:';
@ -851,7 +872,8 @@ class Request
return $this;
}
public function buildUserAgent() {
public function buildUserAgent()
{
$user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/';
$curl = \curl_version();
@ -864,8 +886,11 @@ class Request
$user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')';
if (isset($_SERVER['SERVER_SOFTWARE'])) {
$user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '',
$_SERVER['SERVER_SOFTWARE']);
$user_agent .= ' ' . \preg_replace(
'~PHP/[\d\.]+~U',
'',
$_SERVER['SERVER_SOFTWARE']
);
} else {
if (isset($_SERVER['TERM_PROGRAM'])) {
$user_agent .= " {$_SERVER['TERM_PROGRAM']}";
@ -915,12 +940,14 @@ class Request
*/
private function _serializePayload($payload)
{
if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER)
if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) {
return $payload;
}
// When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized
if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload))
if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) {
return $payload;
}
// Use a custom serializer if one is registered for this mime type
if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) {

View file

@ -112,7 +112,7 @@ class Response
public function _parseHeaders($headers)
{
$headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY);
$parse_headers = array();
$parse_headers = [];
for ($i = 1; $i < count($headers); $i++) {
list($key, $raw_value) = explode(':', $headers[$i], 2);
$key = trim($key);

View file

@ -2,7 +2,8 @@
namespace Httpful\Response;
final class Headers implements \ArrayAccess, \Countable {
final class Headers implements \ArrayAccess, \Countable
{
private $headers;
@ -15,7 +16,7 @@ final class Headers implements \ArrayAccess, \Countable {
{
$lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY);
array_shift($lines); // HTTP HEADER
$headers = array();
$headers = [];
foreach ($lines as $line) {
list($name, $value) = explode(':', $line, 2);
$headers[strtolower(trim($name))] = trim($value);
@ -54,5 +55,4 @@ final class Headers implements \ArrayAccess, \Countable {
{
return $this->headers;
}
}

View file

@ -67,10 +67,10 @@ X-My-Header:Value2\r\n";
function testMethods()
{
$valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head');
$valid_methods = ['get', 'post', 'delete', 'put', 'options', 'head'];
$url = 'http://example.com/';
foreach ($valid_methods as $method) {
$r = call_user_func(array('Httpful\Request', $method), $url);
$r = call_user_func(['Httpful\Request', $method], $url);
$this->assertEquals('Httpful\Request', get_class($r));
$this->assertEquals(strtoupper($method), $r->method);
}
@ -407,10 +407,13 @@ Content-Type: text/plain; charset=utf-8\r\n", $req);
{
// Parent type
$request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>',
$response = new Response(
'<xml><name>Nathan</name></xml>',
"HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked\r\n", $request);
Transfer-Encoding: chunked\r\n",
$request
);
$this->assertEquals("", $response->content_type);
}
@ -443,16 +446,17 @@ Transfer-Encoding: chunked\r\n", $request);
// Lazy test...
$prev = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertEquals($prev, new \Httpful\Handlers\XmlHandler());
$conf = array('namespace' => 'http://example.com');
$conf = ['namespace' => 'http://example.com'];
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
$new = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertNotEquals($prev, $new);
}
}
class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter {
public function parse($body) {
class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter
{
public function parse($body)
{
return 'custom parse';
}
}

View file

@ -135,7 +135,7 @@ class Client
*
* @var array
*/
protected $curl_options = array();
protected $curl_options = [];
/**
* Construct
@ -189,13 +189,13 @@ class Client
* @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => ''))
* @return string URL used for authentication
*/
public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = array())
public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = [])
{
$parameters = array_merge(array(
$parameters = array_merge([
'response_type' => 'code',
'client_id' => $this->client_id,
'redirect_uri' => $redirect_uri
), $extra_parameters);
], $extra_parameters);
return $auth_endpoint . '?' . http_build_query($parameters, null, '&');
}
@ -224,7 +224,7 @@ class Client
throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR);
}
$parameters['grant_type'] = $grantTypeClass::GRANT_TYPE;
$http_headers = array();
$http_headers = [];
switch ($this->client_auth) {
case self::AUTH_TYPE_URI:
case self::AUTH_TYPE_FORM:
@ -313,7 +313,7 @@ class Client
* @param int $form_content_type HTTP form content type to use
* @return array
*/
public function fetch($protected_resource_url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
public function fetch($protected_resource_url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = [], $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{
if ($this->access_token) {
switch ($this->access_token_type) {
@ -357,8 +357,7 @@ class Client
$timestamp = time();
$nonce = uniqid();
$parsed_url = parse_url($url);
if (!isset($parsed_url['port']))
{
if (!isset($parsed_url['port'])) {
$parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80;
}
if ($http_method == self::HTTP_METHOD_GET) {
@ -369,14 +368,17 @@ class Client
}
}
$signature = base64_encode(hash_hmac($this->access_token_algorithm,
$signature = base64_encode(hash_hmac(
$this->access_token_algorithm,
$timestamp . "\n"
. $nonce . "\n"
. $http_method . "\n"
. $parsed_url['path'] . "\n"
. $parsed_url['host'] . "\n"
. $parsed_url['port'] . "\n\n"
, $this->access_token_secret, true));
. $parsed_url['port'] . "\n\n",
$this->access_token_secret,
true
));
return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"';
}
@ -391,13 +393,13 @@ class Client
* @param int $form_content_type HTTP form content type to use
* @return array
*/
private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
private function executeRequest($url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{
$curl_options = array(
$curl_options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CUSTOMREQUEST => $http_method
);
];
switch ($http_method) {
case self::HTTP_METHOD_POST:
@ -405,7 +407,6 @@ class Client
/* No break */
case self::HTTP_METHOD_PUT:
case self::HTTP_METHOD_PATCH:
/**
* Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data,
* while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
@ -434,7 +435,7 @@ class Client
$curl_options[CURLOPT_URL] = $url;
if (is_array($http_headers)) {
$header = array();
$header = [];
foreach ($http_headers as $key => $parsed_urlvalue) {
$header[] = "$key: $parsed_urlvalue";
}
@ -466,11 +467,11 @@ class Client
}
curl_close($ch);
return array(
return [
'result' => (null === $json_decode) ? $result : $json_decode,
'code' => $http_code,
'content_type' => $content_type
);
];
}
/**
@ -493,7 +494,9 @@ class Client
private function convertToCamelCase($grant_type)
{
$parts = explode('_', $grant_type);
array_walk($parts, function(&$item) { $item = ucfirst($item);});
array_walk($parts, function (&$item) {
$item = ucfirst($item);
});
return implode('', $parts);
}
}

View file

@ -23,15 +23,12 @@ class AuthorizationCode implements IGrantType
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['code']))
{
if (!isset($parameters['code'])) {
throw new InvalidArgumentException(
'The \'code\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
elseif (!isset($parameters['redirect_uri']))
{
} elseif (!isset($parameters['redirect_uri'])) {
throw new InvalidArgumentException(
'The \'redirect_uri\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER

View file

@ -1,5 +1,6 @@
<?php
namespace OAuth2\GrantType;
/**
* Specific GrantType Interface
*/

View file

@ -23,15 +23,12 @@ class Password implements IGrantType
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['username']))
{
if (!isset($parameters['username'])) {
throw new InvalidArgumentException(
'The \'username\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER
);
}
elseif (!isset($parameters['password']))
{
} elseif (!isset($parameters['password'])) {
throw new InvalidArgumentException(
'The \'password\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER

View file

@ -23,8 +23,7 @@ class RefreshToken implements IGrantType
*/
public function validateParameters(&$parameters)
{
if (!isset($parameters['refresh_token']))
{
if (!isset($parameters['refresh_token'])) {
throw new InvalidArgumentException(
'The \'refresh_token\' parameter must be defined for the refresh token grant type',
InvalidArgumentException::MISSING_PARAMETER

View file

@ -29,11 +29,13 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User;
class Search {
class Search
{
protected $elasticsearch;
protected $index;
public function __construct(Client $connection, string $indexName) {
public function __construct(Client $connection, string $indexName)
{
$this->elasticsearch = $connection;
$this->index = $indexName;
}
@ -43,7 +45,8 @@ class Search {
* @param int $resultsPerContentType
* @return array
*/
public function searchAllContent(string $query) {
public function searchAllContent(string $query)
{
$results = $this->elasticsearch->msearch([
'index' => $this->index,
'body' => [
@ -131,7 +134,8 @@ class Search {
];
}
protected function transformTracks(array $searchHits) {
protected function transformTracks(array $searchHits)
{
$tracks = $this->transformToEloquent(Track::class, $searchHits);
$tracks = $tracks->map(function (Track $track) {
return Track::mapPublicTrackSummary($track);
@ -139,7 +143,8 @@ class Search {
return $tracks;
}
protected function transformAlbums(array $searchHits) {
protected function transformAlbums(array $searchHits)
{
$albums = $this->transformToEloquent(Album::class, $searchHits);
$albums = $albums->map(function (Album $album) {
return Album::mapPublicAlbumSummary($album);
@ -147,7 +152,8 @@ class Search {
return $albums;
}
protected function transformPlaylists(array $searchHits) {
protected function transformPlaylists(array $searchHits)
{
$playlists = $this->transformToEloquent(Playlist::class, $searchHits);
$playlists = $playlists->map(function (Playlist $playlist) {
return Playlist::mapPublicPlaylistSummary($playlist);
@ -155,7 +161,8 @@ class Search {
return $playlists;
}
protected function transformUsers(array $searchHits) {
protected function transformUsers(array $searchHits)
{
$users = $this->transformToEloquent(User::class, $searchHits);
$users = $users->map(function (User $user) {
return User::mapPublicUserSummary($user);
@ -173,7 +180,8 @@ class Search {
* @param array $searchHits
* @return \Illuminate\Database\Eloquent\Collection
*/
protected function transformToEloquent(string $modelClass, array $searchHits) {
protected function transformToEloquent(string $modelClass, array $searchHits)
{
if (empty($searchHits)) {
return new Collection();
}

View file

@ -27,7 +27,8 @@ use Illuminate\Contracts\Database\ModelIdentifier;
*
* @link https://github.com/laravel/framework/issues/9347#issuecomment-120803564
*/
trait SerializesModels {
trait SerializesModels
{
use \Illuminate\Queue\SerializesModels;
/**
@ -36,7 +37,8 @@ trait SerializesModels {
* @param mixed $value
* @return mixed
*/
protected function getRestoredPropertyValue($value) {
protected function getRestoredPropertyValue($value)
{
if ($value instanceof ModelIdentifier) {
return method_exists($value->class, 'withTrashed')
? (new $value->class)->withTrashed()->findOrFail($value->id)

View file

@ -19,7 +19,8 @@
* @link https://github.com/Grandt/PHPZip
* @version 1.37
*/
class ZipStream {
class ZipStream
{
const VERSION = 1.37;
const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature
@ -35,10 +36,10 @@ class ZipStream {
private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB)
private $zipComment = null;
private $cdRec = array(); // central directory
private $cdRec = []; // central directory
private $offset = 0;
private $isFinalized = FALSE;
private $addExtraField = TRUE;
private $isFinalized = false;
private $addExtraField = true;
private $streamChunkSize = 16384; // 65536;
private $streamFilePath = null;
@ -54,7 +55,8 @@ class ZipStream {
* @param String $archiveName Name to send to the HTTP client.
* @param String $contentType Content mime type. Optional, defaults to "application/zip".
*/
function __construct($archiveName = "", $contentType = "application/zip") {
function __construct($archiveName = "", $contentType = "application/zip")
{
if (!function_exists('sys_get_temp_dir')) {
die("ERROR: ZipStream " . self::VERSION . " requires PHP version 5.2.1 or above.");
}
@ -62,7 +64,7 @@ class ZipStream {
$headerFile = null;
$headerLine = null;
if (!headers_sent($headerFile, $headerLine) or die("<p><strong>Error:</strong> Unable to send file $archiveName. HTML Headers have already been sent from <strong>$headerFile</strong> in line <strong>$headerLine</strong></p>")) {
if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$archiveName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
if ((ob_get_contents() === false || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$archiveName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
@ -80,8 +82,9 @@ class ZipStream {
}
}
function __destruct() {
$this->isFinalized = TRUE;
function __destruct()
{
$this->isFinalized = true;
$this->cdRec = null;
exit;
}
@ -92,8 +95,9 @@ class ZipStream {
*
* @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it.
*/
function setExtraField($setExtraField = TRUE) {
$this->addExtraField = ($setExtraField === TRUE);
function setExtraField($setExtraField = true)
{
$this->addExtraField = ($setExtraField === true);
}
/**
@ -102,13 +106,14 @@ class ZipStream {
* @param string $newComment New comment. null to clear.
* @return bool $success
*/
public function setComment($newComment = null) {
public function setComment($newComment = null)
{
if ($this->isFinalized) {
return FALSE;
return false;
}
$this->zipComment = $newComment;
return TRUE;
return true;
}
/**
@ -120,9 +125,10 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null) {
public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) {
return FALSE;
return false;
}
$directoryPath = str_replace("\\", "/", $directoryPath);
@ -130,9 +136,9 @@ class ZipStream {
if (strlen($directoryPath) > 0) {
$this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR);
return TRUE;
return true;
}
return FALSE;
return false;
}
/**
@ -144,14 +150,15 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addFile($data, $filePath, $timestamp = 0, $fileComment = null) {
public function addFile($data, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) {
return FALSE;
return false;
}
if (is_resource($data) && get_resource_type($data) == "stream") {
$this->addLargeFile($data, $filePath, $timestamp, $fileComment);
return FALSE;
return false;
}
$gzType = "\x08\x00"; // Compression type 8 = deflate
@ -175,7 +182,7 @@ class ZipStream {
print ($gzData);
return TRUE;
return true;
}
/**
@ -192,7 +199,8 @@ class ZipStream {
* If you start the function by parsing an array, the array will be populated with the realPath
* and zipPath kay/value pairs added to the archive by the function.
*/
public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array()) {
public function addDirectoryContent($realPath, $zipPath, $recursive = true, $followSymlinks = true, &$addedFiles = [])
{
if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) {
if (is_dir($realPath)) {
$this->addDirectory($zipPath);
@ -208,11 +216,11 @@ class ZipStream {
$newRealPath = $file->getPathname();
$newZipPath = self::pathJoin($zipPath, $file->getFilename());
if (file_exists($newRealPath) && ($followSymlinks === TRUE || !is_link($newRealPath))) {
if (file_exists($newRealPath) && ($followSymlinks === true || !is_link($newRealPath))) {
if ($file->isFile()) {
$addedFiles[realpath($newRealPath)] = $newZipPath;
$this->addLargeFile($newRealPath, $newZipPath);
} else if ($recursive === TRUE) {
} else if ($recursive === true) {
$this->addDirectoryContent($newRealPath, $newZipPath, $recursive);
} else {
$this->addDirectory($zipPath);
@ -231,9 +239,10 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) {
public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) {
return FALSE;
return false;
}
if (is_string($dataFile) && is_file($dataFile)) {
@ -247,7 +256,7 @@ class ZipStream {
}
$this->closeStream($this->addExtraField);
}
return TRUE;
return true;
}
/**
@ -258,13 +267,14 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success
*/
public function openStream($filePath, $timestamp = 0, $fileComment = null) {
public function openStream($filePath, $timestamp = 0, $fileComment = null)
{
if (!function_exists('sys_get_temp_dir')) {
die("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used.");
}
if ($this->isFinalized) {
return FALSE;
return false;
}
if (strlen($this->streamFilePath) > 0) {
@ -278,7 +288,7 @@ class ZipStream {
$this->streamFileComment = $fileComment;
$this->streamFileLength = 0;
return TRUE;
return true;
}
/**
@ -287,9 +297,10 @@ class ZipStream {
* @param String $data
* @return $length bytes added or FALSE if the archive is finalized or there are no open stream.
*/
public function addStreamData($data) {
public function addStreamData($data)
{
if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE;
return false;
}
$length = fwrite($this->streamData, $data, strlen($data));
@ -306,9 +317,10 @@ class ZipStream {
*
* @return bool $success
*/
public function closeStream() {
public function closeStream()
{
if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE;
return false;
}
fflush($this->streamData);
@ -327,18 +339,19 @@ class ZipStream {
$this->streamFile = null;
return TRUE;
return true;
}
private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) {
private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) {
return FALSE;
return false;
}
$tempzip = tempnam(sys_get_temp_dir(), 'ZipStream');
$zip = new ZipArchive;
if ($zip->open($tempzip) === TRUE) {
if ($zip->open($tempzip) === true) {
$zip->addFile($dataFile, 'file');
$zip->close();
}
@ -382,7 +395,8 @@ class ZipStream {
* A closed archive can no longer have new files added to it.
* @return bool $success
*/
public function finalize() {
public function finalize()
{
if (!$this->isFinalized) {
if (strlen($this->streamFilePath) > 0) {
$this->closeStream();
@ -404,13 +418,13 @@ class ZipStream {
flush();
$this->isFinalized = TRUE;
$this->isFinalized = true;
$cd = null;
$this->cdRec = null;
return TRUE;
return true;
}
return FALSE;
return false;
}
/**
@ -419,7 +433,8 @@ class ZipStream {
* @param int $timestamp
* @return 2-byte encoded DOS Date
*/
private function getDosTime($timestamp = 0) {
private function getDosTime($timestamp = 0)
{
$timestamp = (int)$timestamp;
$oldTZ = @date_default_timezone_get();
date_default_timezone_set('UTC');
@ -445,7 +460,8 @@ class ZipStream {
* @param int $dataLength
* @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories.
*/
private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) {
private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr)
{
$filePath = str_replace("\\", "/", $filePath);
$fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment));
$timestamp = (int)$timestamp;
@ -516,7 +532,8 @@ class ZipStream {
* @param String $dir
* @param String $file
*/
public static function pathJoin($dir, $file) {
public static function pathJoin($dir, $file)
{
if (empty($dir) || empty($file)) {
return self::getRelativePath($dir . $file);
}
@ -531,7 +548,8 @@ class ZipStream {
* @param String $path The path to clean up
* @return String the clean path
*/
public static function getRelativePath($path) {
public static function getRelativePath($path)
{
$path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path));
$dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/'));
@ -548,7 +566,7 @@ class ZipStream {
$dirs = array_splice($dirs, 1);
}
$newDirs = array();
$newDirs = [];
foreach ($dirs as $dir) {
if ($dir !== "..") {
$subOffset--;
@ -570,4 +588,3 @@ class ZipStream {
return $root . implode("/", array_slice($newDirs, 0, $offset));
}
}
?>

Some files were not shown because too many files have changed in this diff Show more