Apply fixes from StyleCI (#11)

This pull request applies code style fixes from an analysis carried out by [StyleCI](https://github.styleci.io).

---

For more information, click [here](https://github.styleci.io/analyses/8wKwbZ).
This commit is contained in:
Pig Fang 2019-03-02 22:58:37 +08:00 committed by GitHub
parent 71e17a26ae
commit 3cf19d8656
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
105 changed files with 1147 additions and 1200 deletions

View File

@ -43,6 +43,7 @@ class MigratePlayersTable extends Command
if ($count == 0) {
$this->info('No need to update.');
return;
}

View File

@ -10,7 +10,7 @@ class GetPlayerJson extends Event
/**
* CSL_API = 0
* USM_API = 1
* USM_API = 1.
*
* @var int
*/
@ -25,7 +25,7 @@ class GetPlayerJson extends Event
*/
public function __construct(Player $player, $apiType)
{
$this->player = $player;
$this->apiType = $apiType;
$this->player = $player;
$this->apiType = $apiType;
}
}

View File

@ -2,7 +2,7 @@
namespace App\Events;
use \Illuminate\Http\UploadedFile;
use Illuminate\Http\UploadedFile;
class HashingFile extends Event
{

View File

@ -28,7 +28,7 @@ class RenderingFooter extends Event
{
if ($content) {
if (! is_string($content)) {
throw new \Exception("Can not add non-string content", 1);
throw new \Exception('Can not add non-string content', 1);
}
$this->contents[] = $content;

View File

@ -28,7 +28,7 @@ class RenderingHeader extends Event
{
if ($content) {
if (! is_string($content)) {
throw new \Exception("Can not add non-string content", 1);
throw new \Exception('Can not add non-string content', 1);
}
$this->contents[] = $content;

View File

@ -4,13 +4,12 @@ namespace App\Exceptions;
use Exception;
use Illuminate\Http\Response;
use App\Exceptions\PrettyPageException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class Handler extends ExceptionHandler
@ -74,10 +73,11 @@ class Handler extends ExceptionHandler
if ($request->expectsJson()) {
return response()->json([
'errno' => 1,
'msg' => $e->validator->errors()->first()
'msg' => $e->validator->errors()->first(),
]);
} else {
$request->session()->flash('errors', $e->validator->errors());
return redirect()->back();
}
}
@ -87,7 +87,7 @@ class Handler extends ExceptionHandler
return parent::render($request, $e);
} else {
// Hide exception details if we are not in debug mode
if (config('app.debug') && !$request->ajax()) {
if (config('app.debug') && ! $request->ajax()) {
return $this->renderExceptionWithWhoops($e);
} else {
return $this->renderExceptionInBrief($e);
@ -126,7 +126,7 @@ class Handler extends ExceptionHandler
*/
protected function renderExceptionInBrief(Exception $e)
{
if (request()->isMethod('GET') && !request()->ajax()) {
if (request()->isMethod('GET') && ! request()->ajax()) {
return response()->view('errors.exception', ['message' => $e->getMessage()]);
} else {
return response($e->getMessage());

View File

@ -12,7 +12,7 @@ class PrettyPageException extends \Exception
* @param bool $render Whether to show a error page.
* @return void
*/
public function __construct($message = "Error occured.", $code = -1, $render = false)
public function __construct($message = 'Error occured.', $code = -1, $render = false)
{
parent::__construct($message, $code);

View File

@ -3,13 +3,12 @@
namespace App\Http\Controllers;
use Option;
use App\Events;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Player;
use App\Models\Texture;
use Illuminate\Http\Request;
use App\Services\OptionForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Services\Repositories\UserRepository;
@ -20,15 +19,15 @@ class AdminController extends Controller
$today = Carbon::today()->timestamp;
// Prepare data for the graph
$data = [];
$data = [];
$labels = [];
for ($i = 6; $i >= 0; $i--) {
$time = Carbon::createFromTimestamp($today - $i * 86400);
$labels[] = $time->format('m-d');
$data['user_registration'][] = User::like('register_at', $time->toDateString())->count();
$data['texture_uploads'][] = Texture::like('upload_at', $time->toDateString())->count();
$data['user_registration'][] = User::like('register_at', $time->toDateString())->count();
$data['texture_uploads'][] = Texture::like('upload_at', $time->toDateString())->count();
}
$datasets = [
@ -53,14 +52,14 @@ class AdminController extends Controller
'pointHoverBackgroundColor' => '#c1c7d1',
'pointHoverBorderColor' => '#c1c7d1',
'data' => $data['texture_uploads'],
]
],
];
$options = [
'tooltips' => [
'intersect' => false,
'mode' => 'index'
]
'mode' => 'index',
],
];
return view('admin.index', ['chartOptions' => compact('labels', 'datasets', 'options')]);
@ -68,9 +67,9 @@ class AdminController extends Controller
public function customize(Request $request)
{
if ($request->input('action') == "color") {
if ($request->input('action') == 'color') {
$this->validate($request, [
'color_scheme' => 'required'
'color_scheme' => 'required',
]);
$color_scheme = str_replace('_', '-', $request->input('color_scheme'));
@ -79,8 +78,7 @@ class AdminController extends Controller
return json(trans('admin.customize.change-color.success'), 0);
}
$homepage = Option::form('homepage', OptionForm::AUTO_DETECT, function($form)
{
$homepage = Option::form('homepage', OptionForm::AUTO_DETECT, function ($form) {
$form->text('home_pic_url')->hint();
$form->text('favicon_url')->hint()->description();
@ -94,14 +92,12 @@ class AdminController extends Controller
->description();
$form->textarea('copyright_text')->rows(6)->description();
})->handle(function () {
Option::set('copyright_prefer_'.config('app.locale'), request('copyright_prefer'));
Option::set('copyright_text_'.config('app.locale'), request('copyright_text'));
});
$customJsCss = Option::form('customJsCss', OptionForm::AUTO_DETECT, function($form)
{
$customJsCss = Option::form('customJsCss', OptionForm::AUTO_DETECT, function ($form) {
$form->textarea('custom_css', 'CSS')->rows(6);
$form->textarea('custom_js', 'JavaScript')->rows(6);
})->addMessage()->handle();
@ -111,8 +107,7 @@ class AdminController extends Controller
public function score()
{
$rate = Option::form('rate', OptionForm::AUTO_DETECT, function($form)
{
$rate = Option::form('rate', OptionForm::AUTO_DETECT, function ($form) {
$form->group('score_per_storage')->text('score_per_storage')->addon();
$form->group('private_score_per_storage')
@ -126,11 +121,9 @@ class AdminController extends Controller
$form->group('score_per_player')->text('score_per_player')->addon();
$form->text('user_initial_score');
})->handle();
$sign = Option::form('sign', OptionForm::AUTO_DETECT, function($form)
{
$sign = Option::form('sign', OptionForm::AUTO_DETECT, function ($form) {
$form->group('sign_score')
->text('sign_score_from')->addon(trans('options.sign.sign_score.addon1'))
->text('sign_score_to')->addon(trans('options.sign.sign_score.addon2'));
@ -138,12 +131,12 @@ class AdminController extends Controller
$form->group('sign_gap_time')->text('sign_gap_time')->addon();
$form->checkbox('sign_after_zero')->label()->hint();
})->after(function() {
})->after(function () {
$sign_score = request('sign_score_from').','.request('sign_score_to');
Option::set('sign_score', $sign_score);
})->with([
'sign_score_from' => @explode(',', option('sign_score'))[0],
'sign_score_to' => @explode(',', option('sign_score'))[1]
'sign_score_to' => @explode(',', option('sign_score'))[1],
])->handle();
return view('admin.score', ['forms' => compact('rate', 'sign')]);
@ -151,8 +144,7 @@ class AdminController extends Controller
public function options()
{
$general = Option::form('general', OptionForm::AUTO_DETECT, function($form)
{
$general = Option::form('general', OptionForm::AUTO_DETECT, function ($form) {
$form->text('site_name');
$form->text('site_description')->description();
@ -211,7 +203,6 @@ class AdminController extends Controller
$form->textarea('comment_script')->rows(6)->description();
$form->checkbox('allow_sending_statistics')->label()->hint();
})->handle(function () {
Option::set('site_name_'.config('app.locale'), request('site_name'));
Option::set('site_description_'.config('app.locale'), request('site_description'));
@ -223,14 +214,12 @@ class AdminController extends Controller
Option::set('announcement_'.config('app.locale'), request('announcement'));
});
$resources = Option::form('resources', OptionForm::AUTO_DETECT, function($form)
{
$resources = Option::form('resources', OptionForm::AUTO_DETECT, function ($form) {
$form->checkbox('force_ssl')->label()->hint();
$form->checkbox('auto_detect_asset_url')->label()->description();
$form->checkbox('return_204_when_notfound')->label()->description();
$form->text('cache_expire_time')->hint(OptionForm::AUTO_DETECT);
})->type('warning')->hint(OptionForm::AUTO_DETECT)->handle();
return view('admin.options')->with('forms', compact('general', 'resources', 'announ'));
@ -252,10 +241,10 @@ class AdminController extends Controller
$perPage = $request->input('perPage', 10);
$users = User::select(['uid', 'email', 'nickname', 'score', 'permission', 'register_at', 'verified'])
->where('uid', 'like', '%' . $search . '%')
->orWhere('email', 'like', '%' . $search . '%')
->orWhere('nickname', 'like', '%' . $search . '%')
->orWhere('score', 'like', '%' . $search . '%')
->where('uid', 'like', '%'.$search.'%')
->orWhere('email', 'like', '%'.$search.'%')
->orWhere('nickname', 'like', '%'.$search.'%')
->orWhere('score', 'like', '%'.$search.'%')
->orderBy($sortField, $sortType)
->offset(($page - 1) * $perPage)
->limit($perPage)
@ -265,12 +254,13 @@ class AdminController extends Controller
$users->transform(function ($user) {
$user->operations = auth()->user()->permission;
$user->players_count = $user->players->count();
return $user;
});
return [
'totalRecords' => $isSingleUser ? 1 : User::count(),
'data' => $users
'data' => $users,
];
}
@ -290,9 +280,9 @@ class AdminController extends Controller
$perPage = $request->input('perPage', 10);
$players = Player::select(['pid', 'uid', 'player_name', 'tid_skin', 'tid_cape', 'last_modified'])
->where('pid', 'like', '%' . $search . '%')
->orWhere('uid', 'like', '%' . $search . '%')
->orWhere('player_name', 'like', '%' . $search . '%')
->where('pid', 'like', '%'.$search.'%')
->orWhere('uid', 'like', '%'.$search.'%')
->orWhere('player_name', 'like', '%'.$search.'%')
->orderBy($sortField, $sortType)
->offset(($page - 1) * $perPage)
->limit($perPage)
@ -301,12 +291,12 @@ class AdminController extends Controller
return [
'totalRecords' => $isSpecifiedUser ? 1 : Player::count(),
'data' => $players
'data' => $players,
];
}
/**
* Handle ajax request from /admin/users
* Handle ajax request from /admin/users.
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
@ -327,9 +317,9 @@ class AdminController extends Controller
}
}
if ($action == "email") {
if ($action == 'email') {
$this->validate($request, [
'email' => 'required|email'
'email' => 'required|email',
]);
if ($users->get($request->input('email'), 'email')) {
@ -339,42 +329,38 @@ class AdminController extends Controller
$user->setEmail($request->input('email'));
return json(trans('admin.users.operations.email.success'), 0);
} elseif ($action == "verification") {
$user->verified = !$user->verified;
} elseif ($action == 'verification') {
$user->verified = ! $user->verified;
$user->save();
return json(trans('admin.users.operations.verification.success'), 0);
} elseif ($action == "nickname") {
} elseif ($action == 'nickname') {
$this->validate($request, [
'nickname' => 'required|no_special_chars'
'nickname' => 'required|no_special_chars',
]);
$user->setNickName($request->input('nickname'));
return json(trans('admin.users.operations.nickname.success', [
'new' => $request->input('nickname')
'new' => $request->input('nickname'),
]), 0);
} elseif ($action == "password") {
} elseif ($action == 'password') {
$this->validate($request, [
'password' => 'required|min:8|max:16'
'password' => 'required|min:8|max:16',
]);
$user->changePassword($request->input('password'));
return json(trans('admin.users.operations.password.success'), 0);
} elseif ($action == "score") {
} elseif ($action == 'score') {
$this->validate($request, [
'score' => 'required|integer'
'score' => 'required|integer',
]);
$user->setScore($request->input('score'));
return json(trans('admin.users.operations.score.success'), 0);
} elseif ($action == "ban") {
} elseif ($action == 'ban') {
$permission = $user->getPermission() == User::BANNED ? User::NORMAL : User::BANNED;
$user->setPermission($permission);
@ -382,10 +368,9 @@ class AdminController extends Controller
return json([
'errno' => 0,
'msg' => trans('admin.users.operations.ban.'.($permission == User::BANNED ? 'ban' : 'unban').'.success'),
'permission' => $user->getPermission()
'permission' => $user->getPermission(),
]);
} elseif ($action == "admin") {
} elseif ($action == 'admin') {
$permission = $user->getPermission() == User::ADMIN ? User::NORMAL : User::ADMIN;
$user->setPermission($permission);
@ -393,10 +378,9 @@ class AdminController extends Controller
return json([
'errno' => 0,
'msg' => trans('admin.users.operations.admin.'.($permission == User::ADMIN ? 'set' : 'unset').'.success'),
'permission' => $user->getPermission()
'permission' => $user->getPermission(),
]);
} elseif ($action == "delete") {
} elseif ($action == 'delete') {
$user->delete();
return json(trans('admin.users.operations.delete.success'), 0);
@ -406,7 +390,7 @@ class AdminController extends Controller
}
/**
* Handle ajax request from /admin/players
* Handle ajax request from /admin/players.
*/
public function playerAjaxHandler(Request $request, UserRepository $users)
{
@ -424,40 +408,40 @@ class AdminController extends Controller
}
}
if ($action == "texture") {
if ($action == 'texture') {
$this->validate($request, [
'type' => 'required',
'tid' => 'required|integer'
'tid' => 'required|integer',
]);
if (! Texture::find($request->tid) && $request->tid != 0)
if (! Texture::find($request->tid) && $request->tid != 0) {
return json(trans('admin.players.textures.non-existent', ['tid' => $request->tid]), 1);
}
$player->setTexture(['tid_'.$request->type => $request->tid]);
return json(trans('admin.players.textures.success', ['player' => $player->player_name]), 0);
} elseif ($action == "owner") {
} elseif ($action == 'owner') {
$this->validate($request, [
'uid' => 'required|integer'
'uid' => 'required|integer',
]);
$user = $users->get($request->input('uid'));
if (! $user)
if (! $user) {
return json(trans('admin.users.operations.non-existent'), 1);
}
$player->setOwner($request->input('uid'));
return json(trans('admin.players.owner.success', ['player' => $player->player_name, 'user' => $user->getNickName()]), 0);
} elseif ($action == "delete") {
} elseif ($action == 'delete') {
$player->delete();
return json(trans('admin.players.delete.success'), 0);
} elseif ($action == "name") {
} elseif ($action == 'name') {
$this->validate($request, [
'name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max')
'name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max'),
]);
$player->rename($request->input('name'));
@ -469,7 +453,7 @@ class AdminController extends Controller
}
/**
* Get one user information
* Get one user information.
*
* @param string $uid
* @param UserRepository $users
@ -480,11 +464,10 @@ class AdminController extends Controller
$user = $users->get(intval($uid));
if ($user) {
return json('success', 0, ['user' => $user->makeHidden([
'password', 'ip', 'last_sign_at', 'register_at', 'remember_token'
'password', 'ip', 'last_sign_at', 'register_at', 'remember_token',
])->toArray()]);
} else {
return json('No such user.', 1);
}
}
}

View File

@ -3,7 +3,6 @@
namespace App\Http\Controllers;
use URL;
use Log;
use Mail;
use View;
use Cache;
@ -23,13 +22,13 @@ class AuthController extends Controller
{
$this->validate($request, [
'identification' => 'required',
'password' => 'required|min:6|max:32'
'password' => 'required|min:6|max:32',
]);
$identification = $request->input('identification');
// Guess type of identification
$authType = (validate($identification, 'email')) ? "email" : "username";
$authType = (validate($identification, 'email')) ? 'email' : 'username';
event(new Events\UserTryToLogin($identification, $authType));
@ -64,7 +63,7 @@ class AuthController extends Controller
Cache::put($loginFailsCacheKey, ++$loginFails, 3600);
return json(trans('auth.validation.password'), 1, [
'login_fails' => $loginFails
'login_fails' => $loginFails,
]);
}
}
@ -74,6 +73,7 @@ class AuthController extends Controller
{
if (Auth::check()) {
Auth::logout();
return json(trans('auth.logout.success'), 0);
} else {
return json(trans('auth.logout.fail'), 1);
@ -101,7 +101,7 @@ class AuthController extends Controller
$data = $this->validate($request, array_merge([
'email' => 'required|email|unique:users',
'password' => 'required|min:8|max:32',
'captcha' => 'required'.(app()->environment('testing') ? '' : '|captcha')
'captcha' => 'required'.(app()->environment('testing') ? '' : '|captcha'),
], $rule));
if (option('register_with_player_name')) {
@ -136,9 +136,9 @@ class AuthController extends Controller
if (option('register_with_player_name')) {
$player = new Player;
$player->uid = $user->uid;
$player->player_name = $request->get('player_name');
$player->tid_skin = 0;
$player->uid = $user->uid;
$player->player_name = $request->get('player_name');
$player->tid_skin = 0;
$player->last_modified = get_datetime_string();
$player->save();
@ -149,13 +149,13 @@ class AuthController extends Controller
return json([
'errno' => 0,
'msg' => trans('auth.register.success')
'msg' => trans('auth.register.success'),
]);
}
public function forgot()
{
if (config('mail.driver') != "") {
if (config('mail.driver') != '') {
return view('auth.forgot');
} else {
throw new PrettyPageException(trans('auth.forgot.disabled'), 8);
@ -165,7 +165,7 @@ class AuthController extends Controller
public function handleForgot(Request $request, UserRepository $users)
{
$this->validate($request, [
'captcha' => 'required'.(app()->environment('testing') ? '' : '|captcha')
'captcha' => 'required'.(app()->environment('testing') ? '' : '|captcha'),
]);
if (! config('mail.driver')) {
@ -181,15 +181,16 @@ class AuthController extends Controller
return json([
'errno' => 2,
'msg' => trans('auth.forgot.frequent-mail'),
'remain' => $remain
'remain' => $remain,
]);
}
// Get user instance
$user = $users->get($request->input('email'), 'email');
if (! $user)
if (! $user) {
return json(trans('auth.forgot.unregistered'), 1);
}
$url = URL::temporarySignedRoute('auth.reset', now()->addHour(), ['uid' => $user->uid]);
@ -239,5 +240,4 @@ class AuthController extends Controller
return view('auth.verify');
}
}

View File

@ -7,10 +7,8 @@ use Option;
use App\Models\User;
use App\Models\Closet;
use App\Models\Texture;
use App\Models\ClosetModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\PrettyPageException;
class ClosetController extends Controller
{
@ -25,6 +23,7 @@ class ClosetController extends Controller
{
$this->middleware(function ($request, $next) {
$this->closet = new Closet(Auth::id());
return $next($request);
});
}
@ -37,9 +36,9 @@ class ClosetController extends Controller
public function getClosetData(Request $request)
{
$category = $request->input('category', 'skin');
$page = abs($request->input('page', 1));
$page = abs($request->input('page', 1));
$per_page = (int) $request->input('perPage', 6);
$q = $request->input('q', null);
$q = $request->input('q', null);
$per_page = $per_page > 0 ? $per_page : 6;
@ -60,7 +59,7 @@ class ClosetController extends Controller
return response()->json([
'category' => $category,
'items' => $items->forPage($page, $per_page)->values(),
'total_pages' => $total_pages
'total_pages' => $total_pages,
]);
}
@ -68,7 +67,7 @@ class ClosetController extends Controller
{
$this->validate($request, [
'tid' => 'required|integer',
'name' => 'required|no_special_chars'
'name' => 'required|no_special_chars',
]);
$currentUser = Auth::user();
@ -101,11 +100,12 @@ class ClosetController extends Controller
{
$this->validate($request, [
'tid' => 'required|integer',
'new_name' => 'required|no_special_chars'
'new_name' => 'required|no_special_chars',
]);
if ($this->closet->rename($request->tid, $request->new_name)) {
$this->closet->save();
return json(trans('user.closet.rename.success', ['name' => $request->new_name]), 0);
} else {
return json(trans('user.closet.remove.non-existent'), 1);
@ -115,7 +115,7 @@ class ClosetController extends Controller
public function remove(Request $request)
{
$this->validate($request, [
'tid' => 'required|integer'
'tid' => 'required|integer',
]);
if ($this->closet->remove($request->tid)) {
@ -125,13 +125,13 @@ class ClosetController extends Controller
$this->closet->save();
if (option('return_score'))
if (option('return_score')) {
Auth::user()->setScore(option('score_per_closet_item'), 'plus');
}
return json(trans('user.closet.remove.success'), 0);
} else {
return json(trans('user.closet.remove.non-existent'), 1);
}
}
}

View File

@ -2,7 +2,6 @@
namespace App\Http\Controllers;
use Illuminate\Validation\Validator;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

View File

@ -6,8 +6,8 @@ use Exception;
use ZipArchive;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Composer\Semver\Comparator;
use App\Services\PluginManager;
use Composer\Semver\Comparator;
class MarketController extends Controller
{
@ -37,7 +37,7 @@ class MarketController extends Controller
$this->guzzle = $guzzle;
$this->guzzleConfig = [
'headers' => ['User-Agent' => config('secure.user_agent')],
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
];
}
@ -61,7 +61,7 @@ class MarketController extends Controller
$item['dependencies'] = [
'isRequirementsSatisfied' => $manager->isRequirementsSatisfied($requirements),
'requirements' => $requirements,
'unsatisfiedRequirements' => $manager->getUnsatisfiedRequirements($requirements)
'unsatisfiedRequirements' => $manager->getUnsatisfiedRequirements($requirements),
];
return $item;
@ -74,12 +74,13 @@ class MarketController extends Controller
{
$pluginsHaveUpdate = collect($this->getAllAvailablePlugins())->filter(function ($item) {
$plugin = plugin($item['name']);
return $plugin && Comparator::greaterThan($item['version'], $plugin->version);
});
return json([
'available' => $pluginsHaveUpdate->isNotEmpty(),
'plugins' => $pluginsHaveUpdate->values()->all()
'plugins' => $pluginsHaveUpdate->values()->all(),
]);
}
@ -101,16 +102,18 @@ class MarketController extends Controller
// Download
try {
$this->guzzle->request('GET', $url, array_merge($this->guzzleConfig, [
'sink' => $tmp_path
'sink' => $tmp_path,
]));
} catch (Exception $e) {
report($e);
return json(trans('admin.plugins.market.download-failed', ['error' => $e->getMessage()]), 2);
}
// Check file's sha1 hash
if (sha1_file($tmp_path) !== $metadata['dist']['shasum']) {
@unlink($tmp_path);
return json(trans('admin.plugins.market.shasum-failed'), 3);
}
@ -146,7 +149,7 @@ class MarketController extends Controller
)->getBody();
} catch (Exception $e) {
throw new Exception(trans('admin.plugins.market.connection-error', [
'error' => htmlentities($e->getMessage())
'error' => htmlentities($e->getMessage()),
]));
}

View File

@ -15,10 +15,8 @@ use App\Events\CheckPlayerExists;
use App\Events\PlayerWillBeAdded;
use App\Events\PlayerWillBeDeleted;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\PrettyPageException;
use App\Http\Middleware\CheckPlayerExist;
use App\Http\Middleware\CheckPlayerOwner;
use App\Services\Repositories\UserRepository;
class PlayerController extends Controller
{
@ -42,13 +40,14 @@ class PlayerController extends Controller
});
$this->middleware([CheckPlayerExist::class, CheckPlayerOwner::class], [
'only' => ['delete', 'rename', 'setTexture', 'clearTexture']
'only' => ['delete', 'rename', 'setTexture', 'clearTexture'],
]);
}
public function index()
{
$user = Auth::user();
return view('user.player')
->with('players', $user->players->toArray())
->with('user', $user);
@ -67,7 +66,7 @@ class PlayerController extends Controller
$user = Auth::user();
$this->validate($request, [
'player_name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max')
'player_name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max'),
]);
event(new CheckPlayerExists($request->input('player_name')));
@ -84,9 +83,9 @@ class PlayerController extends Controller
$player = new Player;
$player->uid = $user->uid;
$player->player_name = $request->input('player_name');
$player->tid_skin = 0;
$player->uid = $user->uid;
$player->player_name = $request->input('player_name');
$player->tid_skin = 0;
$player->last_modified = get_datetime_string();
$player->save();
@ -122,7 +121,7 @@ class PlayerController extends Controller
public function rename(Request $request)
{
$this->validate($request, [
'new_player_name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max')
'new_player_name' => 'required|player_name|min:'.option('player_name_length_min').'|max:'.option('player_name_length_max'),
]);
$newName = $request->input('new_player_name');
@ -171,5 +170,4 @@ class PlayerController extends Controller
return json(trans('user.player.clear.success', ['name' => $this->player->player_name]), 0);
}
}

View File

@ -2,8 +2,6 @@
namespace App\Http\Controllers;
use View;
use App\Events;
use App\Services\Plugin;
use Illuminate\Http\Request;
use App\Services\PluginManager;
@ -47,7 +45,7 @@ class PluginController extends Controller
return json([
'errno' => 1,
'msg' => trans('admin.plugins.operations.unsatisfied.notice'),
'reason' => $reason
'reason' => $reason,
]);
}
@ -99,7 +97,7 @@ class PluginController extends Controller
return [
'isRequirementsSatisfied' => $plugins->isRequirementsSatisfied($plugin),
'requirements' => $plugin->getRequirements(),
'unsatisfiedRequirements' => $plugins->getUnsatisfiedRequirements($plugin)
'unsatisfiedRequirements' => $plugins->getUnsatisfiedRequirements($plugin),
];
}
}

View File

@ -5,14 +5,13 @@ namespace App\Http\Controllers;
use DB;
use Log;
use File;
use Schema;
use Option;
use Storage;
use Schema;
use Artisan;
use Storage;
use App\Models\User;
use Illuminate\Http\Request;
use Composer\Semver\Comparator;
use Illuminate\Validation\Validator;
use App\Exceptions\PrettyPageException;
class SetupController extends Controller
@ -41,7 +40,7 @@ class SetupController extends Controller
);
}
$content = File::get('..' . DIRECTORY_SEPARATOR . '.env');
$content = File::get('..'.DIRECTORY_SEPARATOR.'.env');
$content = str_replace(
'DB_CONNECTION = '.env('DB_CONNECTION'),
'DB_CONNECTION = '.$request->input('type'),
@ -77,7 +76,7 @@ class SetupController extends Controller
'DB_PREFIX = '.$request->input('prefix'),
$content
);
File::put('..' . DIRECTORY_SEPARATOR . '.env', $content);
File::put('..'.DIRECTORY_SEPARATOR.'.env', $content);
return redirect('setup/info');
}
@ -112,7 +111,7 @@ class SetupController extends Controller
'email' => 'required|email',
'nickname' => 'required|no_special_chars|max:255',
'password' => 'required|min:8|max:32|confirmed',
'site_name' => 'required'
'site_name' => 'required',
]);
if ($request->has('generate_random')) {
@ -122,14 +121,14 @@ class SetupController extends Controller
Artisan::call('salt:random');
} else {
// @codeCoverageIgnoreStart
Log::warning("[SetupWizard] Failed to set application key. No write permission.");
Log::warning('[SetupWizard] Failed to set application key. No write permission.');
// @codeCoverageIgnoreEnd
}
}
// Create tables
Artisan::call('migrate', ['--force' => true]);
Log::info("[SetupWizard] Tables migrated.");
Log::info('[SetupWizard] Tables migrated.');
Option::set('site_name', $request->input('site_name'));
@ -139,7 +138,7 @@ class SetupController extends Controller
$siteUrl = substr($siteUrl, 0, -10); // @codeCoverageIgnore
}
Option::set('site_url', $siteUrl);
Option::set('site_url', $siteUrl);
// Register super admin
$user = new User;
@ -161,7 +160,7 @@ class SetupController extends Controller
return view('setup.wizard.finish')->with([
'email' => $request->input('email'),
'password' => $request->input('password')
'password' => $request->input('password'),
]);
}
@ -182,8 +181,8 @@ class SetupController extends Controller
$tips = [];
while($filename = @readdir($resource)) {
if ($filename != "." && $filename != "..") {
while ($filename = @readdir($resource)) {
if ($filename != '.' && $filename != '..') {
preg_match('/update-(.*)-to-(.*).php/', $filename, $matches);
// Skip if the file is not valid or expired

View File

@ -4,8 +4,8 @@ namespace App\Http\Controllers;
use View;
use Option;
use Storage;
use Session;
use Storage;
use App\Models\User;
use App\Models\Closet;
use App\Models\Player;
@ -13,7 +13,6 @@ use App\Models\Texture;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\PrettyPageException;
use App\Services\Repositories\UserRepository;
class SkinlibController extends Controller
@ -59,7 +58,7 @@ class SkinlibController extends Controller
// Available sorting methods: time, likes
$sort = $request->input('sort', 'time');
$sortBy = ($sort == "time") ? "upload_at" : $sort;
$sortBy = ($sort == 'time') ? 'upload_at' : $sort;
// Current page
$page = $request->input('page', 1);
@ -72,7 +71,7 @@ class SkinlibController extends Controller
// Keyword to search
$keyword = $request->input('keyword', '');
if ($filter == "skin") {
if ($filter == 'skin') {
$query = Texture::where(function ($innerQuery) {
// Nested condition, DO NOT MODIFY
$innerQuery->where('type', '=', 'steve')->orWhere('type', '=', 'alex');
@ -81,7 +80,7 @@ class SkinlibController extends Controller
$query = Texture::where('type', $filter);
}
if ($keyword !== "") {
if ($keyword !== '') {
$query = $query->like('name', $keyword);
}
@ -94,7 +93,7 @@ class SkinlibController extends Controller
$query = $query->where('public', true);
} else {
// Show private textures when show uploaded textures of current user
if ($uploader != $currentUser->uid && !$currentUser->isAdmin()) {
if ($uploader != $currentUser->uid && ! $currentUser->isAdmin()) {
$query = $query->where(function ($innerQuery) use ($currentUser) {
$innerQuery->where('public', true)->orWhere('uploader', '=', $currentUser->uid);
});
@ -118,7 +117,7 @@ class SkinlibController extends Controller
return response()->json([
'items' => $textures,
'current_uid' => $currentUser ? $currentUser->uid : 0,
'total_pages' => $totalPages
'total_pages' => $totalPages,
]);
}
@ -127,7 +126,7 @@ class SkinlibController extends Controller
$texture = Texture::find($tid);
$user = Auth::user();
if (! $texture || $texture && !Storage::disk('textures')->has($texture->hash)) {
if (! $texture || $texture && ! Storage::disk('textures')->has($texture->hash)) {
if (option('auto_del_invalid_texture')) {
if ($texture) {
$texture->delete();
@ -138,9 +137,10 @@ class SkinlibController extends Controller
abort(404, trans('skinlib.show.deleted').trans('skinlib.show.contact-admin'));
}
if (!$texture->public) {
if (!Auth::check() || ($user->uid != $texture->uploader && !$user->isAdmin()))
if (! $texture->public) {
if (! Auth::check() || ($user->uid != $texture->uploader && ! $user->isAdmin())) {
abort(403, trans('skinlib.show.private'));
}
}
return view('skinlib.show')
@ -173,21 +173,22 @@ class SkinlibController extends Controller
return $response;
}
$t = new Texture();
$t->name = $request->input('name');
$t->type = $request->input('type');
$t->likes = 1;
$t->hash = bs_hash_file($request->file('file'));
$t->size = ceil($request->file('file')->getSize() / 1024);
$t->public = $request->input('public') == 'true';
$t->uploader = $user->uid;
$t = new Texture();
$t->name = $request->input('name');
$t->type = $request->input('type');
$t->likes = 1;
$t->hash = bs_hash_file($request->file('file'));
$t->size = ceil($request->file('file')->getSize() / 1024);
$t->public = $request->input('public') == 'true';
$t->uploader = $user->uid;
$t->upload_at = get_datetime_string();
$cost = $t->size * ($t->public ? Option::get('score_per_storage') : Option::get('private_score_per_storage'));
$cost += option('score_per_closet_item');
if ($user->getScore() < $cost)
if ($user->getScore() < $cost) {
return json(trans('skinlib.upload.lack-score'), 7);
}
$results = Texture::where('hash', $t->hash)->get();
@ -197,7 +198,7 @@ class SkinlibController extends Controller
// then allow to re-upload it.
if ($result->type == $t->type && $result->public) {
return json(trans('skinlib.upload.repeated'), 0, [
'tid' => $result->tid
'tid' => $result->tid,
]);
}
}
@ -213,10 +214,12 @@ class SkinlibController extends Controller
if ($user->getCloset()->add($t->tid, $t->name)) {
return json(trans('skinlib.upload.success', ['name' => $request->input('name')]), 0, [
'tid' => $t->tid
'tid' => $t->tid,
]);
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
public function delete(Request $request, UserRepository $users)
{
@ -227,7 +230,7 @@ class SkinlibController extends Controller
return json(trans('skinlib.non-existent'), 1);
}
if ($result->uploader != $user->uid && !$user->isAdmin()) {
if ($result->uploader != $user->uid && ! $user->isAdmin()) {
return json(trans('skinlib.no-permission'), 1);
}
@ -253,18 +256,22 @@ class SkinlibController extends Controller
if ($result->delete()) {
return json(trans('skinlib.delete.success'), 0);
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
public function privacy(Request $request, UserRepository $users)
{
$t = Texture::find($request->input('tid'));
$user = Auth::user();
if (! $t)
if (! $t) {
return json(trans('skinlib.non-existent'), 1);
}
if ($t->uploader != $user->uid && !$user->isAdmin())
if ($t->uploader != $user->uid && ! $user->isAdmin()) {
return json(trans('skinlib.no-permission'), 1);
}
$score_diff = $t->size * (option('private_score_per_storage') - option('score_per_storage')) * ($t->public ? -1 : 1);
if ($users->get($t->uploader)->getScore() + $score_diff < 0) {
@ -281,50 +288,60 @@ class SkinlibController extends Controller
@$users->get($t->uploader)->setScore($score_diff, 'plus');
if ($t->setPrivacy(!$t->public)) {
if ($t->setPrivacy(! $t->public)) {
return json([
'errno' => 0,
'msg' => trans('skinlib.privacy.success', ['privacy' => (!$t->public ? trans('general.private') : trans('general.public'))]),
'public' => $t->public
'msg' => trans('skinlib.privacy.success', ['privacy' => (! $t->public ? trans('general.private') : trans('general.public'))]),
'public' => $t->public,
]);
}
} // @codeCoverageIgnore
}
public function rename(Request $request) {
// @codeCoverageIgnore
public function rename(Request $request)
{
$this->validate($request, [
'tid' => 'required|integer',
'new_name' => 'required|no_special_chars'
'new_name' => 'required|no_special_chars',
]);
$user = Auth::user();
$t = Texture::find($request->input('tid'));
if (! $t)
if (! $t) {
return json(trans('skinlib.non-existent'), 1);
}
if ($t->uploader != $user->uid && !$user->isAdmin())
if ($t->uploader != $user->uid && ! $user->isAdmin()) {
return json(trans('skinlib.no-permission'), 1);
}
$t->name = $request->input('new_name');
if ($t->save()) {
return json(trans('skinlib.rename.success', ['name' => $request->input('new_name')]), 0);
}
} // @codeCoverageIgnore
}
public function model(Request $request) {
// @codeCoverageIgnore
public function model(Request $request)
{
$user = Auth::user();
$data = $this->validate($request, [
'tid' => 'required|integer',
'model' => 'required|in:steve,alex,cape'
'model' => 'required|in:steve,alex,cape',
]);
$t = Texture::find($request->input('tid'));
if (! $t)
if (! $t) {
return json(trans('skinlib.non-existent'), 1);
}
if ($t->uploader != $user->uid && !$user->isAdmin())
if ($t->uploader != $user->uid && ! $user->isAdmin()) {
return json(trans('skinlib.no-permission'), 1);
}
$duplicate = Texture::where('hash', $t->hash)
->where('type', $request->input('model'))
@ -341,7 +358,7 @@ class SkinlibController extends Controller
}
/**
* Check Uploaded Files
* Check Uploaded Files.
*
* @param Request $request
* @return JsonResponse
@ -357,32 +374,36 @@ class SkinlibController extends Controller
$this->validate($request, [
'name' => [
'required',
option('texture_name_regexp') ? 'regex:'.option('texture_name_regexp') : 'no_special_chars'
option('texture_name_regexp') ? 'regex:'.option('texture_name_regexp') : 'no_special_chars',
],
'file' => 'required|max:'.option('max_upload_file_size'),
'public' => 'required'
'public' => 'required',
]);
$mime = $request->file('file')->getMimeType();
if ($mime != "image/png" && $mime != "image/x-png") {
if ($mime != 'image/png' && $mime != 'image/x-png') {
return json(trans('skinlib.upload.type-error'), 1);
}
$type = $request->input('type');
$size = getimagesize($request->file('file'));
$type = $request->input('type');
$size = getimagesize($request->file('file'));
$ratio = $size[0] / $size[1];
if ($type == "steve" || $type == "alex") {
if ($ratio != 2 && $ratio != 1)
if ($type == 'steve' || $type == 'alex') {
if ($ratio != 2 && $ratio != 1) {
return json(trans('skinlib.upload.invalid-size', ['type' => trans('general.skin'), 'width' => $size[0], 'height' => $size[1]]), 1);
if ($size[0] % 64 != 0 || $size[1] % 32 != 0)
}
if ($size[0] % 64 != 0 || $size[1] % 32 != 0) {
return json(trans('skinlib.upload.invalid-hd-skin', ['type' => trans('general.skin'), 'width' => $size[0], 'height' => $size[1]]), 1);
} elseif ($type == "cape") {
if ($ratio != 2)
}
} elseif ($type == 'cape') {
if ($ratio != 2) {
return json(trans('skinlib.upload.invalid-size', ['type' => trans('general.cape'), 'width' => $size[0], 'height' => $size[1]]), 1);
}
} else {
return json(trans('general.illegal-parameters'), 1);
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
}

View File

@ -6,16 +6,12 @@ use Event;
use Option;
use Storage;
use Response;
use Minecraft;
use Exception;
use Carbon\Carbon;
use App\Models\User;
use Minecraft;
use App\Models\Player;
use App\Models\Texture;
use Illuminate\Http\Request;
use App\Events\GetSkinPreview;
use App\Events\GetAvatarPreview;
use App\Exceptions\PrettyPageException;
use App\Services\Repositories\UserRepository;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
@ -28,20 +24,20 @@ class TextureController extends Controller
* @param string $api
* @return \Illuminate\Http\Response
*/
public function json($player_name, $api = "")
public function json($player_name, $api = '')
{
$player = $this->getPlayerInstance($player_name);
if ($api == "csl") {
if ($api == 'csl') {
$content = $player->getJsonProfile(Player::CSL_API);
} else if ($api == "usm") {
} elseif ($api == 'usm') {
$content = $player->getJsonProfile(Player::USM_API);
} else {
$content = $player->getJsonProfile(Option::get('api_type'));
}
return Response::jsonProfile($content, 200, [
'Last-Modified' => strtotime($player->last_modified)
'Last-Modified' => strtotime($player->last_modified),
]);
}
@ -50,7 +46,8 @@ class TextureController extends Controller
return $this->json($player_name, $api);
}
public function texture($hash, $headers = [], $message = '') {
public function texture($hash, $headers = [], $message = '')
{
try {
if (Storage::disk('textures')->has($hash)) {
return Response::png(Storage::disk('textures')->get($hash), 200, array_merge([
@ -66,7 +63,8 @@ class TextureController extends Controller
return abort(404, $message);
}
public function textureWithApi($api, $hash) {
public function textureWithApi($api, $hash)
{
return $this->texture($hash);
}
@ -93,12 +91,14 @@ class TextureController extends Controller
if ($hash = $player->getTexture($type)) {
return $this->texture($hash, [
'Last-Modified' => strtotime($player->last_modified)
'Last-Modified' => strtotime($player->last_modified),
], trans('general.texture-deleted'));
} else {
abort(404, trans('general.texture-not-uploaded', ['type' => $type]));
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
public function avatarByTid($tid, $size = 128)
{
@ -162,8 +162,8 @@ class TextureController extends Controller
} else {
$binary = Storage::disk('textures')->read($t->hash);
if ($t->type == "cape") {
$png = Minecraft::generatePreviewFromCape($binary, $size*0.8, $size*1.125, $size);
if ($t->type == 'cape') {
$png = Minecraft::generatePreviewFromCape($binary, $size * 0.8, $size * 1.125, $size);
} else {
$png = Minecraft::generatePreviewFromSkin($binary, $size, ($t->type == 'alex'), 'both', 4);
}
@ -191,8 +191,9 @@ class TextureController extends Controller
return $this->preview($tid, $size);
}
public function raw($tid) {
if (!option('allow_downloading_texture')) {
public function raw($tid)
{
if (! option('allow_downloading_texture')) {
abort(404);
}

View File

@ -5,12 +5,10 @@ namespace App\Http\Controllers;
use Log;
use File;
use Cache;
use Option;
use Storage;
use Exception;
use ZipArchive;
use Illuminate\Support\Arr;
use App\Services\OptionForm;
use Illuminate\Http\Request;
use Composer\Semver\Comparator;
@ -66,7 +64,7 @@ class UpdateController extends Controller
$this->guzzle = $guzzle;
$this->guzzleConfig = [
'headers' => ['User-Agent' => config('secure.user_agent')],
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
];
}
@ -80,7 +78,7 @@ class UpdateController extends Controller
'pre_release' => false,
// Fallback to current time
'release_time' => '',
'new_version_available' => false
'new_version_available' => false,
];
// If current update source is available
@ -97,7 +95,7 @@ class UpdateController extends Controller
'release_note',
'release_url',
'release_time',
'pre_release'
'pre_release',
]));
} else {
// if detailed release info is not given
@ -124,7 +122,7 @@ class UpdateController extends Controller
{
return json([
'latest' => $this->getUpdateInfo('latest_version'),
'available' => $this->newVersionAvailable()
'available' => $this->newVersionAvailable(),
]);
}
@ -137,8 +135,9 @@ class UpdateController extends Controller
public function download(Request $request)
{
if (! $this->newVersionAvailable())
if (! $this->newVersionAvailable()) {
return json([]);
}
$action = $request->get('action');
$release_url = $this->getReleaseInfo($this->latestVersion)['release_url'];
@ -180,7 +179,9 @@ class UpdateController extends Controller
'sink' => $tmp_path,
'progress' => function ($total, $downloaded) {
// @codeCoverageIgnoreStart
if ($total == 0) return;
if ($total == 0) {
return;
}
// Log current progress per 100 KiB
if ($total == $downloaded || floor($downloaded / 102400) > floor($GLOBALS['last_downloaded'] / 102400)) {
$GLOBALS['last_downloaded'] = $downloaded;
@ -188,10 +189,11 @@ class UpdateController extends Controller
Cache::put('download-progress', compact('total', 'downloaded'), 3600);
}
// @codeCoverageIgnoreEnd
}
},
]));
} catch (Exception $e) {
@unlink($tmp_path);
return json(trans('admin.update.errors.prefix').$e->getMessage(), 1);
}
@ -220,7 +222,6 @@ class UpdateController extends Controller
if ($zip->extractTo($extract_dir) === false) {
return json(trans('admin.update.errors.prefix').'Cannot unzip file.', 1);
}
} else {
return json(trans('admin.update.errors.unzip').$res, 1);
}
@ -239,7 +240,6 @@ class UpdateController extends Controller
File::copyDirectory($extract_dir, base_path());
Log::info('[Update Wizard] Overwrite with extracted files');
} catch (Exception $e) {
report($e);
Log::error('[Update Wizard] Error occured when overwriting files');
@ -253,6 +253,7 @@ class UpdateController extends Controller
}
Log::info('[Update Wizard] Done');
return json(trans('admin.update.complete'), 0);
default:
@ -265,13 +266,13 @@ class UpdateController extends Controller
if (! $this->updateInfo) {
// Add timestamp to control cdn cache
$url = starts_with($this->updateSource, 'http')
? $this->updateSource."?v=".substr(time(), 0, -3)
? $this->updateSource.'?v='.substr(time(), 0, -3)
: $this->updateSource;
try {
$response = $this->guzzle->request('GET', $url, $this->guzzleConfig)->getBody();
} catch (Exception $e) {
Log::error("[CheckingUpdate] Failed to get update information: ".$e->getMessage());
Log::error('[CheckingUpdate] Failed to get update information: '.$e->getMessage());
}
if (isset($response)) {
@ -292,5 +293,4 @@ class UpdateController extends Controller
{
return Arr::get($this->getUpdateInfo('releases'), $version);
}
}

View File

@ -13,7 +13,6 @@ use Illuminate\Http\Request;
use App\Mail\EmailVerification;
use App\Events\UserProfileUpdated;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\PrettyPageException;
use App\Services\Repositories\UserRepository;
class UserController extends Controller
@ -32,19 +31,21 @@ class UserController extends Controller
public function index()
{
$user = Auth::user();
return view('user.index')->with([
'user' => $user,
'statistics' => [
'players' => $this->calculatePercentageUsed($user->players->count(), option('score_per_player')),
'storage' => $this->calculatePercentageUsed($user->getStorageUsed(), option('score_per_storage'))
'storage' => $this->calculatePercentageUsed($user->getStorageUsed(), option('score_per_storage')),
],
'announcement' => app('parsedown')->text(option_localized('announcement'))
'announcement' => app('parsedown')->text(option_localized('announcement')),
]);
}
public function scoreInfo()
{
$user = Auth::user();
return [
'user' => [
'score' => $user->score,
@ -52,10 +53,10 @@ class UserController extends Controller
],
'stats' => [
'players' => $this->calculatePercentageUsed($user->players->count(), option('score_per_player')),
'storage' => $this->calculatePercentageUsed($user->getStorageUsed(), option('score_per_storage'))
'storage' => $this->calculatePercentageUsed($user->getStorageUsed(), option('score_per_storage')),
],
'signAfterZero' => option('sign_after_zero'),
'signGapTime' => option('sign_gap_time')
'signGapTime' => option('sign_gap_time'),
];
}
@ -70,8 +71,8 @@ class UserController extends Controller
{
$user = Auth::user();
// Initialize default value to avoid division by zero.
$result['used'] = $used;
$result['total'] = 'UNLIMITED';
$result['used'] = $used;
$result['total'] = 'UNLIMITED';
$result['percentage'] = 0;
if ($rate != 0) {
@ -99,15 +100,16 @@ class UserController extends Controller
'msg' => trans('user.sign-success', ['score' => $acquiredScore]),
'score' => $user->getScore(),
'storage' => $this->calculatePercentageUsed($user->getStorageUsed(), option('score_per_storage')),
'remaining_time' => $gap > 1 ? round($gap) : $gap
'remaining_time' => $gap > 1 ? round($gap) : $gap,
]);
} else {
$remaining_time = $this->getUserSignRemainingTimeWithPrecision();
return json(trans('user.cant-sign-until', [
'time' => $remaining_time >= 1
? $remaining_time : round($remaining_time * 60),
'unit' => $remaining_time >= 1
? trans('user.time-unit-hour') : trans('user.time-unit-min')
? trans('user.time-unit-hour') : trans('user.time-unit-min'),
]), 1);
}
}
@ -145,6 +147,7 @@ class UserController extends Controller
} catch (\Exception $e) {
// Write the exception to log
report($e);
return json(trans('user.verification.failed', ['msg' => $e->getMessage()]), 2);
}
@ -173,13 +176,14 @@ class UserController extends Controller
switch ($action) {
case 'nickname':
$this->validate($request, [
'new_nickname' => 'required|no_special_chars|max:255'
'new_nickname' => 'required|no_special_chars|max:255',
]);
$nickname = $request->input('new_nickname');
if ($user->setNickName($nickname)) {
event(new UserProfileUpdated($action, $user));
return json(trans('user.profile.nickname.success', ['nickname' => $nickname]), 0);
}
@ -188,11 +192,12 @@ class UserController extends Controller
case 'password':
$this->validate($request, [
'current_password' => 'required|min:6|max:32',
'new_password' => 'required|min:8|max:32'
'new_password' => 'required|min:8|max:32',
]);
if (! $user->verifyPassword($request->input('current_password')))
if (! $user->verifyPassword($request->input('current_password'))) {
return json(trans('user.profile.password.wrong-password'), 1);
}
if ($user->changePassword($request->input('new_password'))) {
event(new UserProfileUpdated($action, $user));
@ -207,15 +212,16 @@ class UserController extends Controller
case 'email':
$this->validate($request, [
'new_email' => 'required|email',
'password' => 'required|min:6|max:32'
'password' => 'required|min:6|max:32',
]);
if ($users->get($request->input('new_email'), 'email')) {
return json(trans('user.profile.email.existed'), 1);
}
if (! $user->verifyPassword($request->input('password')))
if (! $user->verifyPassword($request->input('password'))) {
return json(trans('user.profile.email.wrong-password'), 1);
}
if ($user->setEmail($request->input('new_email'))) {
// Set account status to unverified
@ -233,14 +239,16 @@ class UserController extends Controller
case 'delete':
$this->validate($request, [
'password' => 'required|min:6|max:32'
'password' => 'required|min:6|max:32',
]);
if ($user->isAdmin())
if ($user->isAdmin()) {
return json(trans('user.profile.delete.admin'), 1);
}
if (! $user->verifyPassword($request->input('password')))
if (! $user->verifyPassword($request->input('password'))) {
return json(trans('user.profile.delete.wrong-password'), 1);
}
Auth::logout();
@ -250,7 +258,7 @@ class UserController extends Controller
return response()
->json([
'errno' => 0,
'msg' => trans('user.profile.delete.success')
'msg' => trans('user.profile.delete.success'),
]);
}
@ -260,7 +268,9 @@ class UserController extends Controller
return json(trans('general.illegal-parameters'), 1);
break;
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
/**
* Set user avatar.
@ -270,14 +280,15 @@ class UserController extends Controller
public function setAvatar(Request $request)
{
$this->validate($request, [
'tid' => 'required|integer'
'tid' => 'required|integer',
]);
$result = Texture::find($request->input('tid'));
if ($result) {
if ($result->type == "cape")
if ($result->type == 'cape') {
return json(trans('user.profile.avatar.wrong-type'), 1);
}
if (Auth::user()->setAvatar($request->input('tid'))) {
return json(trans('user.profile.avatar.success'), 0);
@ -285,6 +296,7 @@ class UserController extends Controller
} else {
return json(trans('skinlib.non-existent'), 1);
}
} // @codeCoverageIgnore
}
// @codeCoverageIgnore
}

View File

@ -11,7 +11,7 @@ class AfterSessionBooted
*
* @var array
*/
static $jobs;
public static $jobs;
/**
* Handle an incoming request.

View File

@ -3,11 +3,8 @@
namespace App\Http\Middleware;
use App;
use View;
use Http;
use Cookie;
use Session;
use Closure;
use Session;
use App\Models\User;
use App\Events\UserAuthenticated;
use Illuminate\Support\Facades\Auth;
@ -17,7 +14,6 @@ class CheckAuthenticated
public function handle($request, Closure $next)
{
if (Auth::check()) {
$user = Auth::user();
if ($user->permission == User::BANNED) {
@ -27,14 +23,13 @@ class CheckAuthenticated
}
// Ask for filling email
if ($user->email == "") {
if ($user->email == '') {
return $this->askForFillingEmail($request, $next);
}
event(new UserAuthenticated($user));
return $next($request);
} else {
$this->flashLastRequestedPath();
@ -48,7 +43,6 @@ class CheckAuthenticated
if (isset($request->email)) {
if (filter_var($request->email, FILTER_VALIDATE_EMAIL)) {
if (User::where('email', $request->email)->get()->isEmpty()) {
$user->setEmail($request->email);

View File

@ -14,7 +14,7 @@ class CheckPlayerExist
if (is_null(Player::find($request->input('pid')))) {
return response()->json([
'errno' => 1,
'msg' => trans('general.unexistent-player')
'msg' => trans('general.unexistent-player'),
]);
} else {
return $next($request);
@ -32,15 +32,18 @@ class CheckPlayerExist
$responses = event(new CheckPlayerExists($player_name));
foreach ($responses as $r) {
if ($r) return $next($request); // @codeCoverageIgnore
if ($r) {
return $next($request);
} // @codeCoverageIgnore
}
if (! Player::where('player_name', $player_name)->get()->isEmpty())
if (! Player::where('player_name', $player_name)->get()->isEmpty()) {
return $next($request);
}
if (option('return_204_when_notfound')) {
return response('', 204, [
'Cache-Control' => 'public, max-age='.option('cache_expire_time')
'Cache-Control' => 'public, max-age='.option('cache_expire_time'),
]);
} else {
return abort(404, trans('general.unexistent-player'));

View File

@ -22,7 +22,7 @@ class CheckPlayerOwner
if ($player->uid != auth()->id()) {
return response()->json([
'errno' => 1,
'msg' => trans('admin.players.no-permission')
'msg' => trans('admin.players.no-permission'),
]);
}
}

View File

@ -6,7 +6,7 @@ class CheckUserVerified
{
public function handle($request, \Closure $next)
{
if (option('require_verification') && !auth()->user()->verified) {
if (option('require_verification') && ! auth()->user()->verified) {
abort(403, trans('auth.check.verified'));
}

View File

@ -33,5 +33,4 @@ class DetectLanguagePrefer
session(['locale' => config('app.locale')]);
};
}
}

View File

@ -2,8 +2,6 @@
namespace App\Http\Middleware;
use Closure;
use Session;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter

View File

@ -2,8 +2,6 @@
namespace App\Http\Middleware;
use App;
use Session;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated

View File

@ -12,7 +12,7 @@ class RedirectIfUrlEndsWithSlash
$baseUrl = $request->getBaseUrl();
// Try to remove slash at the end of current url
$newUrl = substr($request->getRequestUri(), 0, -1);
$newUrl = substr($request->getRequestUri(), 0, -1);
if ($newUrl != $baseUrl) {
return redirect(Str::replaceLast($baseUrl, '', $newUrl));

View File

@ -5,7 +5,6 @@ namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class EmailVerification extends Mailable
{

View File

@ -5,7 +5,6 @@ namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ForgotPassword extends Mailable
{

View File

@ -25,7 +25,7 @@ class Closet
private $textures;
/**
* Indicates if closet has been modified
* Indicates if closet has been modified.
*
* @var array
*/
@ -39,13 +39,13 @@ class Closet
public function __construct($uid)
{
$this->uid = $uid;
$this->db = DB::table('closets');
$this->db = DB::table('closets');
// Create a new closet if not exists
if ($this->db->where('uid', $uid)->count() == 0) {
$this->db->insert([
'uid' => $uid,
'textures' => '[]'
'textures' => '[]',
]);
}
@ -66,7 +66,7 @@ class Closet
return true;
}
if (!$t->public && $t->uploader != $uid && !app('users')->get($uid)->isAdmin()) {
if (! $t->public && $t->uploader != $uid && ! app('users')->get($uid)->isAdmin()) {
return true;
}
@ -92,7 +92,7 @@ class Closet
* @param string $category "skin" or "cape" or "all".
* @return array
*/
public function getItems($category = "all")
public function getItems($category = 'all')
{
$textures = Texture::whereIn('tid', $this->textures->pluck('tid')->all())
->get()
@ -100,15 +100,16 @@ class Closet
$in_closet = $this->textures
->where('tid', $texture->tid)
->first();
return [
'tid' => $texture->tid,
'name' => $in_closet['name'],
'type' => $texture->type,
'add_at' => $in_closet['add_at']
'add_at' => $in_closet['add_at'],
];
})
->sortByDesc('add_at');
if ($category == "all") {
if ($category == 'all') {
return $textures->values()->all();
} elseif ($category == 'cape') {
return $textures->filter(function ($texture) {
@ -137,7 +138,7 @@ class Closet
$this->textures->push([
'tid' => (int) $tid,
'name' => $name,
'add_at' => time()
'add_at' => time(),
]);
$this->closet_modified = true;
@ -157,7 +158,7 @@ class Closet
}
/**
* Get one texture info
* Get one texture info.
*
* @param int $tid
* @return array|null Result
@ -170,7 +171,7 @@ class Closet
/**
* Rename closet item.
*
* @param integer $tid
* @param int $tid
* @param string $newName
* @return bool
*/
@ -184,6 +185,7 @@ class Closet
if ($texture['tid'] == $tid) {
$texture['name'] = $newName;
}
return $texture;
});
@ -208,6 +210,7 @@ class Closet
});
$this->closet_modified = true;
return true;
}
@ -259,6 +262,7 @@ class Closet
foreach (DB::table('closets')->pluck('uid') as $uid) {
$result[] = new Closet($uid);
}
return $result;
}
}

View File

@ -3,11 +3,8 @@
namespace App\Models;
use Event;
use Response;
use App\Models\User;
use App\Events\GetPlayerJson;
use App\Events\PlayerProfileUpdated;
use App\Exceptions\PrettyPageException;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
@ -23,9 +20,9 @@ class Player extends Model
/**
* Properties for Eloquent Model.
*/
public $primaryKey = 'pid';
public $timestamps = false;
protected $fillable = ['uid', 'player_name', 'last_modified'];
public $primaryKey = 'pid';
public $timestamps = false;
protected $fillable = ['uid', 'player_name', 'last_modified'];
/**
* The attributes that should be cast to native types.
@ -92,7 +89,7 @@ class Player extends Model
* @param array $tids
* @return $this
*/
public function setTexture(Array $tids)
public function setTexture(array $tids)
{
foreach (self::$types as $type) {
$property = "tid_$type";
@ -163,7 +160,7 @@ class Player extends Model
{
$this->update([
'player_name' => $newName,
'last_modified' => get_datetime_string()
'last_modified' => get_datetime_string(),
]);
$this->player_name = $newName;
@ -179,7 +176,8 @@ class Player extends Model
* @param int $uid
* @return $this
*/
public function setOwner($uid) {
public function setOwner($uid)
{
$this->update(['uid' => $uid]);
event(new PlayerProfileUpdated($this));
@ -197,7 +195,6 @@ class Player extends Model
{
// Support both CustomSkinLoader API & UniSkinAPI
if ($api_type == self::CSL_API || $api_type == self::USM_API) {
$responses = Event::dispatch(new GetPlayerJson($this, $api_type));
// If listeners return nothing
@ -225,7 +222,7 @@ class Player extends Model
$model = empty($texture) ? 'default' : ($texture->type === 'steve' ? 'default' : 'slim');
if ($api_type == self::USM_API) {
$json['last_update'] = strtotime($this->last_modified);
$json['last_update'] = strtotime($this->last_modified);
$json['model_preference'] = [$model];
}
@ -248,6 +245,7 @@ class Player extends Model
{
// @see http://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql
$this->update(['last_modified' => get_datetime_string()]);
return event(new PlayerProfileUpdated($this));
}
}

View File

@ -25,6 +25,7 @@ class Texture extends Model
public function setPrivacy($public)
{
$this->public = $public;
return $this->save();
}

View File

@ -13,9 +13,9 @@ class User extends Authenticatable
/**
* Permissions.
*/
const BANNED = -1;
const NORMAL = 0;
const ADMIN = 1;
const BANNED = -1;
const NORMAL = 0;
const ADMIN = 1;
const SUPER_ADMIN = 2;
/**
@ -27,8 +27,8 @@ class User extends Authenticatable
/**
* Properties for Eloquent Model.
*/
public $primaryKey = 'uid';
public $timestamps = false;
public $primaryKey = 'uid';
public $timestamps = false;
protected $fillable = ['email', 'nickname', 'permission'];
/**
@ -58,7 +58,7 @@ class User extends Authenticatable
*/
public function isAdmin()
{
return ($this->permission >= static::ADMIN);
return $this->permission >= static::ADMIN;
}
/**
@ -154,6 +154,7 @@ class User extends Authenticatable
public function setEmail($new_email)
{
$this->email = $new_email;
return $this->save();
}
@ -167,7 +168,7 @@ class User extends Authenticatable
if (! $this->uid) {
return trans('general.unexistent-user');
} else {
return ($this->nickname == "") ? $this->email : $this->nickname;
return ($this->nickname == '') ? $this->email : $this->nickname;
}
}
@ -180,6 +181,7 @@ class User extends Authenticatable
public function setNickName($newNickName)
{
$this->nickname = $newNickName;
return $this->save();
}
@ -200,7 +202,7 @@ class User extends Authenticatable
* @param string $mode What operation should be done, set, plus or minus.
* @return bool
*/
public function setScore($score, $mode = "set")
public function setScore($score, $mode = 'set')
{
switch ($mode) {
case 'set':
@ -215,6 +217,7 @@ class User extends Authenticatable
$this->score -= $score;
break;
}
return $this->save();
}
@ -229,7 +232,7 @@ class User extends Authenticatable
$this->storageUsed = 0;
$result = DB::table('textures')
->select(DB::raw("SUM(size) AS total_size"))
->select(DB::raw('SUM(size) AS total_size'))
->where('uploader', $this->uid)
->first()->total_size;
@ -247,7 +250,6 @@ class User extends Authenticatable
public function sign()
{
if ($this->canSign()) {
$scoreLimits = explode(',', option('sign_score'));
$acquiredScore = rand($scoreLimits[0], $scoreLimits[1]);
@ -287,7 +289,7 @@ class User extends Authenticatable
*/
public function canSign()
{
return ($this->getSignRemainingTime() <= 0);
return $this->getSignRemainingTime() <= 0;
}
/**
@ -319,6 +321,7 @@ class User extends Authenticatable
public function setAvatar($tid)
{
$this->avatar = $tid;
return $this->save();
}

View File

@ -9,8 +9,8 @@ use App\Events;
use App\Models\User;
use ReflectionException;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider;
use App\Exceptions\PrettyPageException;
use Illuminate\Support\ServiceProvider;
use App\Services\Repositories\OptionRepository;
class AppServiceProvider extends ServiceProvider
@ -29,7 +29,7 @@ class AppServiceProvider extends ServiceProvider
return $user->isAdmin();
});
Event::listen(Events\RenderingHeader::class, function($event) {
Event::listen(Events\RenderingHeader::class, function ($event) {
// Provide some application information for javascript
$blessing = array_merge(Arr::except(config('app'), ['key', 'providers', 'aliases', 'cipher', 'log', 'url']), [
'base_url' => url('/'),
@ -56,7 +56,7 @@ class AppServiceProvider extends ServiceProvider
{
$this->app->singleton('cipher', 'App\Services\Cipher\\'.config('secure.cipher'));
$this->app->singleton('users', \App\Services\Repositories\UserRepository::class);
$this->app->singleton('options', OptionRepository::class);
$this->app->singleton('options', OptionRepository::class);
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);

View File

@ -2,7 +2,6 @@
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider

View File

@ -30,13 +30,13 @@ class PluginServiceProvider extends ServiceProvider
foreach ($plugins->getPlugins() as $plugin) {
if ($plugin->isEnabled()) {
$src_paths[$plugin->getNameSpace()] = $plugin->getPath()."/src";
$src_paths[$plugin->getNameSpace()] = $plugin->getPath().'/src';
// Add paths of views
$finder->addNamespace($plugin->getNameSpace(), $plugin->getPath()."/views");
$finder->addNamespace($plugin->getNameSpace(), $plugin->getPath().'/views');
}
// Always add paths of translation files for namespace hints
$loader->addNamespace($plugin->getNameSpace(), $plugin->getPath()."/lang");
$loader->addNamespace($plugin->getNameSpace(), $plugin->getPath().'/lang');
}
$this->registerPluginCallbackListener();
@ -73,7 +73,7 @@ class PluginServiceProvider extends ServiceProvider
Events\PluginWasDisabled::class,
], function ($event) {
// Call callback functions of plugin
if (file_exists($filename = $event->plugin->getPath()."/callbacks.php")) {
if (file_exists($filename = $event->plugin->getPath().'/callbacks.php')) {
$callbacks = require $filename;
$callback = Arr::get($callbacks, get_class($event));
@ -105,7 +105,7 @@ class PluginServiceProvider extends ServiceProvider
foreach ((array) array_keys($paths) as $namespace) {
if ($namespace != '' && mb_strpos($class, $namespace) === 0) {
// Parse real file path
$path = $paths[$namespace].Str::replaceFirst($namespace, '', $class).".php";
$path = $paths[$namespace].Str::replaceFirst($namespace, '', $class).'.php';
$path = str_replace('\\', '/', $path);
if (file_exists($path)) {

View File

@ -26,7 +26,7 @@ class ResponseMacroServiceProvider extends ServiceProvider
// Return `304 Not Modified` if given `If-Modified-Since` header
// is newer than our `Last-Modified` time or the `Etag` matches.
if ($if_modified_since >= $last_modified || $if_none_match == $etag) {
$src = '';
$src = '';
$status = 304;
}
@ -34,7 +34,7 @@ class ResponseMacroServiceProvider extends ServiceProvider
'Content-type' => 'image/png',
'Last-Modified' => format_http_date($last_modified),
'Cache-Control' => 'public, max-age='.option('cache_expire_time'),
'Etag' => $etag
'Etag' => $etag,
], $header));
});
@ -43,7 +43,7 @@ class ResponseMacroServiceProvider extends ServiceProvider
$if_modified_since = strtotime(request()->headers->get('If-Modified-Since'));
if ($if_modified_since && $if_modified_since >= $last_modified) {
$src = '';
$src = '';
$status = 304;
}

View File

@ -14,7 +14,7 @@ class ValidatorExtendServiceProvider extends ServiceProvider
*/
public function boot()
{
/**
/*
* @param $a attribute
* @param $value value
* @param $p parameters
@ -60,7 +60,7 @@ class ValidatorExtendServiceProvider extends ServiceProvider
return $value === e(addslashes(trim($value)));
});
Validator::extend('playername', function($a, $value, $p, $v) {
Validator::extend('playername', function ($a, $value, $p, $v) {
return preg_match('/^([A-Za-z0-9_]+)$/', $value);
});

View File

@ -7,7 +7,7 @@ abstract class BaseCipher implements EncryptInterface
/**
* {@inheritdoc}
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
//
}
@ -15,7 +15,7 @@ abstract class BaseCipher implements EncryptInterface
/**
* {@inheritdoc}
*/
public function verify($password, $hash, $salt = "")
public function verify($password, $hash, $salt = '')
{
return hash_equals($hash, $this->hash($password, $salt));
}

View File

@ -11,7 +11,7 @@ interface EncryptInterface
* @param string $salt
* @return string
*/
public function hash($value, $salt = "");
public function hash($value, $salt = '');
/**
* Verifies that the given hash matches the given password.

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class MD5 extends BaseCipher
{
/**
* Once MD5 hash
* Once MD5 hash.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return md5($value);
}

View File

@ -7,12 +7,12 @@ class PHP_PASSWORD_HASH extends BaseCipher
/**
* Use password_hash() to create hash.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return password_hash($value, PASSWORD_DEFAULT);
}
public function verify($password, $hash, $salt = "")
public function verify($password, $hash, $salt = '')
{
return password_verify($password, $hash);
}

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class SALTED2MD5 extends BaseCipher
{
/**
* MD5 hash with salt
* MD5 hash with salt.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return md5(md5($value).$salt);
}

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class SALTED2SHA256 extends BaseCipher
{
/**
* SHA256 hash with salt
* SHA256 hash with salt.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return hash('sha256', hash('sha256', $value).$salt);
}

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class SALTED2SHA512 extends BaseCipher
{
/**
* SHA512 hash with salt
* SHA512 hash with salt.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return hash('sha512', hash('sha512', $value).$salt);
}

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class SHA256 extends BaseCipher
{
/**
* Once SHA256 hash
* Once SHA256 hash.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return hash('sha256', $value);
}

View File

@ -5,9 +5,9 @@ namespace App\Services\Cipher;
class SHA512 extends BaseCipher
{
/**
* Once SHA512 hash
* Once SHA512 hash.
*/
public function hash($value, $salt = "")
public function hash($value, $salt = '')
{
return hash('sha512', $value);
}

View File

@ -65,8 +65,9 @@ class Hook
{
Event::listen(Events\RenderingFooter::class, function ($event) use ($id, $pages) {
foreach ($pages as $pattern) {
if (! app('request')->is($pattern))
if (! app('request')->is($pattern)) {
continue;
}
// We will determine current locale in the event callback,
// otherwise the locale is not properly detected.
@ -85,10 +86,10 @@ class Hook
public static function addStyleFileToPage($urls, $pages = ['*'], $priority = 1)
{
Event::listen(Events\RenderingHeader::class, function ($event) use ($urls, $pages) {
foreach ($pages as $pattern) {
if (! app('request')->is($pattern))
if (! app('request')->is($pattern)) {
continue;
}
foreach ((array) $urls as $url) {
$event->addContent("<link rel=\"stylesheet\" href=\"$url\">");
@ -96,17 +97,16 @@ class Hook
return;
}
}, $priority);
}
public static function addScriptFileToPage($urls, $pages = ['*'], $priority = 1)
{
Event::listen(Events\RenderingFooter::class, function ($event) use ($urls, $pages) {
foreach ($pages as $pattern) {
if (! app('request')->is($pattern))
if (! app('request')->is($pattern)) {
continue;
}
foreach ((array) $urls as $url) {
$event->addContent("<script src=\"$url\"></script>");
@ -114,7 +114,6 @@ class Hook
return;
}
}, $priority);
}
}

View File

@ -24,7 +24,7 @@ class Minecraft
'f' => 8, // Front
'l' => 16, // Left
'r' => 0, // Right
'b' => 24 // Back
'b' => 24, // Back
];
imagecopyresized($dest, $src, 0, 0, $x[$view] * $ratio, 8 * $ratio, $height, $height, 8 * $ratio, 8 * $ratio); // Face
@ -32,6 +32,7 @@ class Minecraft
imagecopyresized($dest, $src, 0, 0, ($x[$view] + 32) * $ratio, 8 * $ratio, $height, $height, 8 * $ratio, 8 * $ratio); // Accessories
imagedestroy($src);
return $dest;
}
@ -71,15 +72,15 @@ class Minecraft
imagefill($dest, 0, 0, $transparent);
if ($side == 'both' || $side == 'front') {
imagecopy($dest, $src, 4 * $ratio, 0 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head - 1
imagecopy($dest, $src, 4 * $ratio, 0 * $ratio, 40 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head - 2
imagecopy($dest, $src, 4 * $ratio, 8 * $ratio, 20 * $ratio, 20 * $ratio, 8 * $ratio, 12 * $ratio); // Body - 1
imagecopy($dest, $src, 4 * $ratio, 20 * $ratio, 4 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Leg - 1
imagecopy($dest, $src, 4 * $ratio, 0 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head - 1
imagecopy($dest, $src, 4 * $ratio, 0 * $ratio, 40 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head - 2
imagecopy($dest, $src, 4 * $ratio, 8 * $ratio, 20 * $ratio, 20 * $ratio, 8 * $ratio, 12 * $ratio); // Body - 1
imagecopy($dest, $src, 4 * $ratio, 20 * $ratio, 4 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Leg - 1
if ($alex) {
imagecopy($dest, $src, 1 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm - 1
imagecopy($dest, $src, 1 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm - 1
} else {
imagecopy($dest, $src, 0 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm - 1
imagecopy($dest, $src, 0 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm - 1
}
// Check if given skin is double layer skin.
@ -88,65 +89,62 @@ class Minecraft
imagecopy($dest, $src, 8 * $ratio, 20 * $ratio, 20 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg - 1
// copy second layer
imagecopy($dest, $src, 4 * $ratio, 8 * $ratio, 20 * $ratio, 36 * $ratio, 8 * $ratio, 12 * $ratio); // Body - 2
imagecopy($dest, $src, 4 * $ratio, 20 * $ratio, 4 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio); // Right Leg - 2
imagecopy($dest, $src, 8 * $ratio, 20 * $ratio, 4 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg - 2
imagecopy($dest, $src, 4 * $ratio, 8 * $ratio, 20 * $ratio, 36 * $ratio, 8 * $ratio, 12 * $ratio); // Body - 2
imagecopy($dest, $src, 4 * $ratio, 20 * $ratio, 4 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio); // Right Leg - 2
imagecopy($dest, $src, 8 * $ratio, 20 * $ratio, 4 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg - 2
if ($alex) {
imagecopy($dest, $src, 12 * $ratio, 8 * $ratio, 36 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio); // Left Arm - 1
imagecopy($dest, $src, 1 * $ratio, 8 * $ratio, 44 * $ratio, 36 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm - 2
imagecopy($dest, $src, 11 * $ratio, 8 * $ratio, 50 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio); // Left Arm - 2
imagecopy($dest, $src, 1 * $ratio, 8 * $ratio, 44 * $ratio, 36 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm - 2
imagecopy($dest, $src, 11 * $ratio, 8 * $ratio, 50 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio); // Left Arm - 2
} else {
imagecopy($dest, $src, 12 * $ratio, 8 * $ratio, 36 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Arm - 1
imagecopy($dest, $src, 0 * $ratio, 8 * $ratio, 44 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm - 2
imagecopy($dest, $src, 12 * $ratio, 8 * $ratio, 52 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Arm - 2
imagecopy($dest, $src, 0 * $ratio, 8 * $ratio, 44 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm - 2
imagecopy($dest, $src, 12 * $ratio, 8 * $ratio, 52 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Arm - 2
}
} else {
// I am not sure whether there are single layer Alex-model skin.
if ($alex) {
static::imageflip($dest, $src, 12 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Left Arm
static::imageflip($dest, $src, 12 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Left Arm
} else {
static::imageflip($dest, $src, 12 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Left Arm
static::imageflip($dest, $src, 12 * $ratio, 8 * $ratio, 44 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Left Arm
}
static::imageflip($dest, $src, 8 * $ratio, 20 * $ratio, 4 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg
static::imageflip($dest, $src, 8 * $ratio, 20 * $ratio, 4 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg
}
}
if ($side == 'both' || $side == 'back') {
imagecopy($dest, $src, $half_width + 4 * $ratio, 8 * $ratio, 32 * $ratio, 20 * $ratio, 8 * $ratio, 12 * $ratio); // Body
imagecopy($dest, $src, $half_width + 4 * $ratio, 0 * $ratio, 24 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head
imagecopy($dest, $src, $half_width + 4 * $ratio, 8 * $ratio, 32 * $ratio, 20 * $ratio, 8 * $ratio, 12 * $ratio); // Body
imagecopy($dest, $src, $half_width + 4 * $ratio, 0 * $ratio, 24 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Head
imagecopy($dest, $src, $half_width + 8 * $ratio, 20 * $ratio, 12 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Leg
imagecopy($dest, $src, $half_width + 4 * $ratio, 0 * $ratio, 56 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Headwear
imagecopy($dest, $src, $half_width + 4 * $ratio, 0 * $ratio, 56 * $ratio, 8 * $ratio, 8 * $ratio, 8 * $ratio); // Headwear
if ($alex) {
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 51 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 51 * $ratio, 20 * $ratio, 3 * $ratio, 12 * $ratio); // Right Arm
} else {
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 52 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 52 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio); // Right Arm
}
if ($double) {
if ($alex) {
imagecopy($dest, $src, $half_width + 1 * $ratio, 8 * $ratio, 43 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 1 * $ratio, 8 * $ratio, 43 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio);
} else {
imagecopy($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 44 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 44 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
}
imagecopy($dest, $src, $half_width + 4 * $ratio, 20 * $ratio, 28 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio); // Left Leg
// copy second layer
imagecopy($dest, $src, $half_width + 4 * $ratio, 8 * $ratio, 32 * $ratio, 36 * $ratio, 8 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 52 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 4 * $ratio, 8 * $ratio, 32 * $ratio, 36 * $ratio, 8 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 12 * $ratio, 8 * $ratio, 52 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio);
if ($alex) {
imagecopy($dest, $src, $half_width + 1 * $ratio, 8 * $ratio, 59 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 1 * $ratio, 8 * $ratio, 59 * $ratio, 52 * $ratio, 3 * $ratio, 12 * $ratio);
} else {
imagecopy($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 60 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 60 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
}
imagecopy($dest, $src, $half_width + 8 * $ratio, 20 * $ratio, 12 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 4 * $ratio, 20 * $ratio, 12 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 8 * $ratio, 20 * $ratio, 12 * $ratio, 36 * $ratio, 4 * $ratio, 12 * $ratio);
imagecopy($dest, $src, $half_width + 4 * $ratio, 20 * $ratio, 12 * $ratio, 52 * $ratio, 4 * $ratio, 12 * $ratio);
} else {
static::imageflip($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 52 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio);
static::imageflip($dest, $src, $half_width + 0 * $ratio, 8 * $ratio, 52 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio);
static::imageflip($dest, $src, $half_width + 4 * $ratio, 20 * $ratio, 12 * $ratio, 20 * $ratio, 4 * $ratio, 12 * $ratio);
}
}
@ -184,7 +182,7 @@ class Minecraft
imagesavealpha($dest, true);
$transparent = imagecolorallocatealpha($dest, 255, 255, 255, 127);
imagefill($dest, 0, 0, $transparent);
imagecopyresized($dest, $src, 0, 0, $ratio, $ratio, $width, $height, imagesx($src)*10/64, imagesy($src)*16/32);
imagecopyresized($dest, $src, 0, 0, $ratio, $ratio, $width, $height, imagesx($src) * 10 / 64, imagesy($src) * 16 / 32);
imagedestroy($src);
if ($fillWidth == 0 || $fillHeight == 0) {
@ -195,9 +193,10 @@ class Minecraft
imagesavealpha($filled, true);
$transparent = imagecolorallocatealpha($filled, 255, 255, 255, 127);
imagefill($filled, 0, 0, $transparent);
imagecopyresized($filled, $dest, ($fillWidth-$width)/2, ($fillHeight-$height)/2, 0, 0, $width, $height, $width, $height);
imagecopyresized($filled, $dest, ($fillWidth - $width) / 2, ($fillHeight - $height) / 2, 0, 0, $width, $height, $width, $height);
imagedestroy($dest);
return $filled;
}

View File

@ -4,9 +4,9 @@ namespace App\Services;
use Option;
use ReflectionClass;
use BadMethodCallException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use BadMethodCallException;
class OptionForm
{
@ -20,19 +20,19 @@ class OptionForm
protected $title;
protected $hint;
protected $type = 'primary';
protected $type = 'primary';
protected $items = [];
protected $values = [];
protected $buttons = [];
protected $buttons = [];
protected $messages = [];
protected $hookBefore;
protected $hookAfter;
protected $alwaysCallback = null;
protected $renderWithOutTable = false;
protected $renderWithOutTable = false;
protected $renderInputTagsOnly = false;
protected $renderWithOutSubmitButton = false;
@ -145,7 +145,7 @@ class OptionForm
'href' => '',
'text' => 'BUTTON',
'type' => 'button',
'name' => ''
'name' => '',
], $info);
$classes = "btn btn-{$info['style']} ".implode(' ', (array) Arr::get($info, 'class'));
@ -166,7 +166,7 @@ class OptionForm
* @param string $style
* @return $this
*/
public function addMessage($msg = self::AUTO_DETECT, $style = "info")
public function addMessage($msg = self::AUTO_DETECT, $style = 'info')
{
if ($msg == self::AUTO_DETECT) {
$msg = trans("options.$this->id.message");
@ -178,7 +178,7 @@ class OptionForm
}
/**
* Add callback which will be executed before handling options
* Add callback which will be executed before handling options.
*
* @param callable $callback
* @return $this
@ -191,7 +191,7 @@ class OptionForm
}
/**
* Add callback which will be executed after handling options
* Add callback which will be executed after handling options.
*
* @param callable $callback
* @return $this
@ -229,7 +229,7 @@ class OptionForm
if (isset($matches[2])) {
return [
'id' => $matches[1],
'offset' => $matches[2]
'offset' => $matches[2],
];
}
@ -256,13 +256,13 @@ class OptionForm
call_user_func($this->hookBefore, $this);
}
$postOptionQueue = [];
$postOptionQueue = [];
$arrayOptionQueue = [];
foreach ($this->items as $item) {
if ($item instanceof OptionFormGroup) {
foreach ($item->items as $innerItem) {
if ($innerItem['type'] == "text") {
if ($innerItem['type'] == 'text') {
$postOptionQueue[] = new OptionFormText($innerItem['id']);
}
}
@ -273,9 +273,9 @@ class OptionForm
}
foreach ($postOptionQueue as $item) {
if ($item instanceof OptionFormCheckbox && !isset($allPostData[$item->id])) {
if ($item instanceof OptionFormCheckbox && ! isset($allPostData[$item->id])) {
// preset value for checkboxes which are not checked
$allPostData[$item->id] = "false";
$allPostData[$item->id] = 'false';
}
// Str::is('*[*]', $item->id)
@ -392,7 +392,7 @@ class OptionForm
'style' => 'primary',
'text' => trans('general.submit'),
'type' => 'submit',
'name' => 'submit_'.$this->id
'name' => 'submit_'.$this->id,
]);
}
@ -432,7 +432,7 @@ class OptionFormItem
public function __construct($id, $name = null)
{
$this->id = $id;
$this->id = $id;
$this->name = $name;
}
@ -468,7 +468,7 @@ class OptionFormItem
return $this;
}
public function disabled($disabled = "disabled")
public function disabled($disabled = 'disabled')
{
$this->disabled = "disabled=\"$disabled\"";
@ -493,9 +493,7 @@ class OptionFormItem
*/
public function render()
{
return;
}
}
class OptionFormText extends OptionFormItem
@ -520,7 +518,7 @@ class OptionFormText extends OptionFormItem
'id' => $this->id,
'value' => $this->value,
'disabled' => $this->disabled,
'placeholder' => $this->placeholder
'placeholder' => $this->placeholder,
]);
}
}
@ -546,7 +544,7 @@ class OptionFormCheckbox extends OptionFormItem
'id' => $this->id,
'value' => $this->value,
'label' => $this->label,
'disabled' => $this->disabled
'disabled' => $this->disabled,
]);
}
}
@ -568,7 +566,7 @@ class OptionFormTextarea extends OptionFormItem
'id' => $this->id,
'rows' => $this->rows,
'value' => $this->value,
'disabled' => $this->disabled
'disabled' => $this->disabled,
]);
}
}
@ -590,7 +588,7 @@ class OptionFormSelect extends OptionFormItem
'id' => $this->id,
'options' => $this->options,
'selected' => $this->value,
'disabled' => $this->disabled
'disabled' => $this->disabled,
]);
}
}
@ -634,7 +632,7 @@ class OptionFormGroup extends OptionFormItem
$rendered[] = view('common.option-form.'.$item['type'])->with([
'id' => $item['id'],
'value' => $item['value'],
'placeholder' => Arr::get($item, 'placeholder')
'placeholder' => Arr::get($item, 'placeholder'),
]);
}

View File

@ -294,7 +294,7 @@ class Plugin implements Arrayable, ArrayAccess
return (array) array_merge([
'name' => $this->name,
'version' => $this->getVersion(),
'path' => $this->path
'path' => $this->path,
], $this->packageInfo);
}
}

View File

@ -2,7 +2,6 @@
namespace App\Services;
use Log;
use Storage;
use App\Events;
use Composer\Semver\Semver;
@ -53,8 +52,8 @@ class PluginManager
Dispatcher $dispatcher,
Filesystem $filesystem
) {
$this->app = $app;
$this->option = $option;
$this->app = $app;
$this->option = $option;
$this->dispatcher = $dispatcher;
$this->filesystem = $filesystem;
}
@ -78,8 +77,9 @@ class PluginManager
// traverse plugins dir
while ($filename = @readdir($resource)) {
if ($filename == '.' || $filename == '..')
if ($filename == '.' || $filename == '..') {
continue;
}
$path = $this->getPluginsDir().DIRECTORY_SEPARATOR.$filename;
@ -91,7 +91,6 @@ class PluginManager
$installed[$filename] = json_decode($this->filesystem->get($packageJsonPath), true);
}
}
}
closedir($resource);
@ -110,7 +109,7 @@ class PluginManager
if ($plugins->has($plugin->name)) {
throw new PrettyPageException(trans('errors.plugins.duplicate', [
'dir1' => $plugin->getDirname(),
'dir2' => $plugins->get($plugin->name)->getDirname()
'dir2' => $plugins->get($plugin->name)->getDirname(),
]), 5);
}
@ -354,7 +353,7 @@ class PluginManager
if (! Semver::satisfies(config('app.version'), $versionConstraint)) {
$unsatisfied['blessing-skin-server'] = [
'version' => config('app.version'),
'constraint' => $versionConstraint
'constraint' => $versionConstraint,
];
}
@ -363,10 +362,10 @@ class PluginManager
$requiredPlugin = $this->getPlugin($name);
if (!$requiredPlugin || !$requiredPlugin->isEnabled()) {
if (! $requiredPlugin || ! $requiredPlugin->isEnabled()) {
$unsatisfied[$name] = [
'version' => null,
'constraint' => $versionConstraint
'constraint' => $versionConstraint,
];
continue;
@ -375,7 +374,7 @@ class PluginManager
if (! Semver::satisfies($requiredPlugin->getVersion(), $versionConstraint)) {
$unsatisfied[$name] = [
'version' => $requiredPlugin->getVersion(),
'constraint' => $versionConstraint
'constraint' => $versionConstraint,
];
continue;
@ -407,7 +406,7 @@ class PluginManager
}
/**
* Copy plugin assets
* Copy plugin assets.
*
* @param Plugin $plugin
*
@ -415,11 +414,11 @@ class PluginManager
*/
public function copyPluginAssets($plugin)
{
$dir = public_path('plugins/' . $plugin->name . '/assets');
$dir = public_path('plugins/'.$plugin->name.'/assets');
Storage::deleteDirectory($dir);
return $this->filesystem->copyDirectory(
$this->getPluginsDir() . DIRECTORY_SEPARATOR . $plugin->name . DIRECTORY_SEPARATOR . 'assets',
$this->getPluginsDir().DIRECTORY_SEPARATOR.$plugin->name.DIRECTORY_SEPARATOR.'assets',
$dir
);
}
@ -435,15 +434,17 @@ class PluginManager
$this->enabled = $list->map(function ($item) {
if (is_string($item)) {
$plugin = $this->getPlugin($item);
return [
'name' => $item,
'version' => $plugin->getVersion(),
];
} else {
$plugin = $this->getPlugin($item['name']);
if (!empty($plugin)) {
if (! empty($plugin)) {
$item['version'] = $plugin->getVersion();
}
return $item;
}
});
@ -452,5 +453,4 @@ class PluginManager
return $this;
}
}

View File

@ -24,7 +24,6 @@ class OptionRepository extends Repository
foreach ($options as $option) {
$this->items[$option->option_name] = $option->option_value;
}
}
/**
@ -43,7 +42,9 @@ class OptionRepository extends Repository
$value = Arr::get($this->items, $key, $default);
if ($raw) return $value;
if ($raw) {
return $value;
}
switch (strtolower($value)) {
case 'true':
@ -141,7 +142,7 @@ class OptionRepository extends Repository
* @param array $array
* @return array
*/
public function only(Array $array)
public function only(array $array)
{
$result = [];
@ -155,7 +156,7 @@ class OptionRepository extends Repository
}
/**
* Save all modified options into database
* Save all modified options into database.
*/
public function __destruct()
{

View File

@ -17,14 +17,15 @@ class UserRepository extends Repository
*/
public function has($identification, $type = 'uid')
{
if ($type == "uid") {
if ($type == 'uid') {
return Arr::has($this->items, $identification);
} else {
return (bool) Arr::where((array) $this->items, function($value) use ($identification, $type) {
if (property_exists($value, $type))
return (bool) Arr::where((array) $this->items, function ($value) use ($identification, $type) {
if (property_exists($value, $type)) {
return false;
}
return ($value->$type == $identification);
return $value->$type == $identification;
});
}
}
@ -39,12 +40,12 @@ class UserRepository extends Repository
public function get($identification, $type = 'uid')
{
if (! $this->has($identification, $type)) {
if ($type == "username") {
if ($type == 'username') {
$player = Player::where('player_name', $identification)->first();
if ($player) {
$identification = $player->uid;
$type = "uid";
$type = 'uid';
} else {
return null;
}
@ -54,21 +55,24 @@ class UserRepository extends Repository
if ($user) {
$this->set($user->uid, $user);
return $user;
}
return null;
}
$result = Arr::where((array) $this->items, function($value) use ($identification, $type) {
if (property_exists($value, $type))
$result = Arr::where((array) $this->items, function ($value) use ($identification, $type) {
if (property_exists($value, $type)) {
return false;
}
return ($value->$type == $identification);
return $value->$type == $identification;
});
// Return first element
reset($result);
return current($result);
}

View File

@ -2,46 +2,42 @@
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
if (! function_exists('get_base_url')) {
function get_base_url()
{
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? "https://" : "http://";
$base_url .= $_SERVER["SERVER_NAME"];
$base_url .= ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$base_url .= $_SERVER['SERVER_NAME'];
$base_url .= ($_SERVER['SERVER_PORT'] == '80') ? '' : (':'.$_SERVER['SERVER_PORT']);
return $base_url;
}
}
if (! function_exists('get_current_url')) {
function get_current_url()
{
return get_base_url().$_SERVER["REQUEST_URI"];
return get_base_url().$_SERVER['REQUEST_URI'];
}
}
if (! function_exists('avatar')) {
function avatar(User $user, $size)
{
$fname = base64_encode($user->email).".png?tid=".$user->getAvatarId();
$fname = base64_encode($user->email).'.png?tid='.$user->getAvatarId();
return url("avatar/$size/$fname");
}
}
if (! function_exists('assets')) {
function assets($relativeUri)
{
// Add query string to fresh cache
if (Str::startsWith($relativeUri, 'css') || Str::startsWith($relativeUri, 'js')) {
return url("resources/assets/dist/$relativeUri")."?v=".config('app.version');
return url("resources/assets/dist/$relativeUri").'?v='.config('app.version');
} elseif (Str::startsWith($relativeUri, 'lang')) {
return url("resources/$relativeUri");
} else {
@ -51,7 +47,6 @@ if (! function_exists('assets')) {
}
if (! function_exists('webpack_assets')) {
function webpack_assets($relativeUri)
{
if (app()->environment('development')) {
@ -75,19 +70,17 @@ if (! function_exists('plugin')) {
}
if (! function_exists('plugin_assets')) {
function plugin_assets($id, $relativeUri)
{
if ($plugin = plugin($id)) {
return $plugin->assets($relativeUri);
} else {
throw new InvalidArgumentException("No such plugin.");
throw new InvalidArgumentException('No such plugin.');
}
}
}
if (! function_exists('json')) {
function json()
{
$args = func_get_args();
@ -98,19 +91,18 @@ if (! function_exists('json')) {
// The third argument is array of extra fields
return Response::json(array_merge([
'errno' => $args[1],
'msg' => $args[0]
'msg' => $args[0],
], $args[2]));
} else {
return Response::json([
'errno' => Arr::get($args, 1, 1),
'msg' => $args[0]
'msg' => $args[0],
]);
}
}
}
if (! function_exists('bs_hash_file')) {
function bs_hash_file(Illuminate\Http\UploadedFile $file)
{
// Try to get hash from event listener
@ -125,7 +117,6 @@ if (! function_exists('bs_hash_file')) {
}
if (! function_exists('bs_footer_extra')) {
function bs_footer_extra()
{
$extraContents = [];
@ -137,7 +128,6 @@ if (! function_exists('bs_footer_extra')) {
}
if (! function_exists('bs_header_extra')) {
function bs_header_extra()
{
$extraContents = [];
@ -149,7 +139,6 @@ if (! function_exists('bs_header_extra')) {
}
if (! function_exists('bs_favicon')) {
function bs_favicon()
{
// Fallback to default favicon
@ -164,12 +153,11 @@ ICONS;
}
if (! function_exists('bs_menu')) {
function bs_menu($type)
{
$menu = config('menu');
Event::dispatch($type == "user" ? new App\Events\ConfigureUserMenu($menu)
Event::dispatch($type == 'user' ? new App\Events\ConfigureUserMenu($menu)
: new App\Events\ConfigureAdminMenu($menu));
if (! isset($menu[$type])) {
@ -185,7 +173,7 @@ if (! function_exists('bs_menu')) {
$availablePluginConfigs[] = [
'title' => trans($plugin->title),
'link' => 'admin/plugins/config/'.$plugin->name,
'icon' => 'fa-circle'
'icon' => 'fa-circle',
];
}
}
@ -193,6 +181,7 @@ if (! function_exists('bs_menu')) {
// Don't display this menu item when no plugin config is available
if (count($availablePluginConfigs) > 0) {
$item['children'] = array_merge($item['children'], $availablePluginConfigs);
return $item;
}
} else {
@ -205,7 +194,7 @@ if (! function_exists('bs_menu')) {
function bs_menu_render($data)
{
$content = "";
$content = '';
foreach ($data as $key => $value) {
$active = app('request')->is(@$value['link']);
@ -250,7 +239,6 @@ if (! function_exists('bs_menu')) {
}
if (! function_exists('bs_copyright')) {
function bs_copyright($prefer = null)
{
$prefer = is_null($prefer) ? option_localized('copyright_prefer', 0) : $prefer;
@ -260,7 +248,7 @@ if (! function_exists('bs_copyright')) {
'UG93ZXJlZCBieSA8YSBocmVmPSJodHRwczovL2dpdGh1Yi5jb20vcHJpbnRlbXB3L2JsZXNzaW5nLXNraW4tc2VydmVyIj5CbGVzc2luZyBTa2luIFNlcnZlcjwvYT4u',
'UHJvdWRseSBwb3dlcmVkIGJ5IDxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9wcmludGVtcHcvYmxlc3Npbmctc2tpbi1zZXJ2ZXIiPkJsZXNzaW5nIFNraW4gU2VydmVyPC9hPi4=',
'55SxIDxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9wcmludGVtcHcvYmxlc3Npbmctc2tpbi1zZXJ2ZXIiPkJsZXNzaW5nIFNraW4gU2VydmVyPC9hPiDlvLrlipvpqbHliqgu',
'6Ieq6LGq5Zyw6YeH55SoIDxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9wcmludGVtcHcvYmxlc3Npbmctc2tpbi1zZXJ2ZXIiPkJsZXNzaW5nIFNraW4gU2VydmVyPC9hPi4='
'6Ieq6LGq5Zyw6YeH55SoIDxhIGhyZWY9Imh0dHBzOi8vZ2l0aHViLmNvbS9wcmludGVtcHcvYmxlc3Npbmctc2tpbi1zZXJ2ZXIiPkJsZXNzaW5nIFNraW4gU2VydmVyPC9hPi4=',
];
return base64_decode(Arr::get($base64CopyrightText, $prefer, $base64CopyrightText[0]));
@ -268,18 +256,16 @@ if (! function_exists('bs_copyright')) {
}
if (! function_exists('bs_custom_copyright')) {
function bs_custom_copyright()
{
return get_string_replaced(option_localized('copyright_text'), [
'{site_name}' => option_localized('site_name'),
'{site_url}' => option('site_url')
'{site_url}' => option('site_url'),
]);
}
}
if (! function_exists('bs_nickname')) {
function bs_nickname(User $user = null)
{
$user = $user ?: auth()->user();
@ -289,7 +275,6 @@ if (! function_exists('bs_nickname')) {
}
if (! function_exists('bs_role')) {
function bs_role(User $user = null)
{
$user = $user ?: auth()->user();
@ -298,7 +283,7 @@ if (! function_exists('bs_role')) {
User::NORMAL => 'normal',
User::BANNED => 'banned',
User::ADMIN => 'admin',
User::SUPER_ADMIN => 'super-admin'
User::SUPER_ADMIN => 'super-admin',
];
$role = Arr::get($roles, $user->getPermission());
@ -330,6 +315,7 @@ if (! function_exists('option')) {
foreach ($key as $innerKey => $innerValue) {
$options->set($innerKey, $innerValue);
}
return;
}
@ -338,7 +324,6 @@ if (! function_exists('option')) {
}
if (! function_exists('option_localized')) {
function option_localized($key = null, $default = null, $raw = false)
{
return option($key.'_'.config('app.locale'), option($key));
@ -346,7 +331,6 @@ if (! function_exists('option_localized')) {
}
if (! function_exists('validate')) {
function validate($value, $type)
{
switch ($type) {
@ -355,20 +339,19 @@ if (! function_exists('validate')) {
break;
default:
# code...
// code...
break;
}
}
}
if (! function_exists('humanize_db_type')) {
function humanize_db_type($type = null)
{
$map = [
'mysql' => 'MySQL',
'sqlite' => 'SQLite',
'pgsql' => 'PostgreSQL'
'pgsql' => 'PostgreSQL',
];
$type = $type ?: config('database.default');
@ -378,7 +361,6 @@ if (! function_exists('humanize_db_type')) {
}
if (! function_exists('get_db_config')) {
function get_db_config($type = null)
{
$type = $type ?: config('database.default');
@ -396,7 +378,8 @@ if (! function_exists('format_http_date')) {
* @param int $timestamp
* @return string
*/
function format_http_date($timestamp) {
function format_http_date($timestamp)
{
return Carbon::createFromTimestampUTC($timestamp)->format('D, d M Y H:i:s \G\M\T');
}
}
@ -405,10 +388,11 @@ if (! function_exists('get_datetime_string')) {
/**
* Get date time string in "Y-m-d H:i:s" format.
*
* @param integer $timestamp
* @param int $timestamp
* @return string
*/
function get_datetime_string($timestamp = 0) {
function get_datetime_string($timestamp = 0)
{
return $timestamp == 0 ? Carbon::now()->toDateTimeString() : Carbon::createFromTimestamp($timestamp)->toDateTimeString();
}
}
@ -422,8 +406,9 @@ if (! function_exists('get_client_ip')) {
*
* @return string
*/
function get_client_ip() {
if (option('ip_get_method') == "0") {
function get_client_ip()
{
if (option('ip_get_method') == '0') {
// Use `HTTP_X_FORWARDED_FOR` if available first
$ip = Arr::get(
$_SERVER,
@ -457,6 +442,7 @@ if (! function_exists('get_string_replaced')) {
foreach ($rules as $search => $replace) {
$str = str_replace($search, $replace, $str);
}
return $str;
}
}
@ -473,14 +459,17 @@ if (! function_exists('is_request_secure')) {
*/
function is_request_secure()
{
if (Arr::get($_SERVER, 'HTTPS') == 'on')
if (Arr::get($_SERVER, 'HTTPS') == 'on') {
return true;
}
if (Arr::get($_SERVER, 'HTTP_X_FORWARDED_PROTO') == 'https')
if (Arr::get($_SERVER, 'HTTP_X_FORWARDED_PROTO') == 'https') {
return true;
}
if (Arr::get($_SERVER, 'HTTP_X_FORWARDED_SSL') == 'on')
if (Arr::get($_SERVER, 'HTTP_X_FORWARDED_SSL') == 'on') {
return true;
}
return false;
}
@ -493,7 +482,8 @@ if (! function_exists('nl2p')) {
* @param string $text
* @return string
*/
function nl2p($text) {
function nl2p($text)
{
$parts = explode("\n", $text);
$result = '<p>'.implode('</p><p>', $parts).'</p>';
// Remove empty paragraphs

View File

@ -19,7 +19,7 @@ if (file_exists($autoload = __DIR__.'/../vendor/autoload.php')) {
} else {
header('Content-Type: text/html; charset=UTF-8');
exit(
"[Error] No vendor folder found. Have you installed the dependencies with composer? <br>".
"[错误] 根目录下未发现 vendor 文件夹,请使用 composer 安装依赖库。详情请阅读 http://t.cn/REyMUqA"
'[Error] No vendor folder found. Have you installed the dependencies with composer? <br>'.
'[错误] 根目录下未发现 vendor 文件夹,请使用 composer 安装依赖库。详情请阅读 http://t.cn/REyMUqA'
);
}

View File

@ -24,13 +24,13 @@
'ctype',
'xml',
'json',
'fileinfo'
'fileinfo',
],
'write_permission' => [
'bootstrap/cache',
'storage',
'plugins'
]
'plugins',
],
];
foreach ($requirements['extensions'] as $extension) {
@ -60,8 +60,8 @@
}
}
$autoload = file_get_contents(__DIR__ . '/../vendor/autoload.php');
$autoload = file_get_contents(__DIR__.'/../vendor/autoload.php');
$lines = explode("\n", $autoload);
$lines[1] = '$GLOBALS["env_checked"] = true;';
file_put_contents(__DIR__ . '/../vendor/autoload.php', implode("\n", $lines));
file_put_contents(__DIR__.'/../vendor/autoload.php', implode("\n", $lines));
})();

View File

@ -145,7 +145,7 @@ return [
'providers' => [
/**
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
@ -170,13 +170,13 @@ return [
Illuminate\View\ViewServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
/**
/*
* Third-party Libraries...
*/
Swiggles\Memcache\MemcacheServiceProvider::class,
Mews\Captcha\CaptchaServiceProvider::class,
/**
/*
* Application Service Providers...
*/
App\Providers\RuntimeCheckServiceProvider::class,
@ -237,7 +237,7 @@ return [
'Str' => Illuminate\Support\Str::class,
'Arr' => Illuminate\Support\Arr::class,
/**
/*
* Blessing Skin
*/
'Option' => App\Services\Facades\Option::class,

View File

@ -40,6 +40,6 @@ return [
'blur' => 2,
'invert' => true,
'contrast' => -5,
]
],
];

View File

@ -36,7 +36,7 @@ return [
'driver' => 'file', // redis, file, pdo, custom
'path' => storage_path('debugbar'), // For file driver
'connection' => null, // Leave null for default connection (Redis/PDO)
'provider' => '' // Instance of StorageInterface for custom driver
'provider' => '', // Instance of StorageInterface for custom driver
],
/*
@ -148,19 +148,19 @@ return [
'hints' => true, // Show hints for common mistakes
],
'mail' => [
'full_log' => false
'full_log' => false,
],
'views' => [
'data' => false, //Note: Can slow down the application, because the data can be quite large..
],
'route' => [
'label' => true // show complete route on bar
'label' => true, // show complete route on bar
],
'logs' => [
'file' => null
'file' => null,
],
'cache' => [
'values' => true // collect cache values
'values' => true, // collect cache values
],
],

View File

@ -59,7 +59,7 @@ return [
],
'testing' => [
'driver' => 'memory'
'driver' => 'memory',
],
],

View File

@ -42,5 +42,5 @@ return [
'plugins_enabled' => '',
'copyright_prefer' => '0',
'score_per_closet_item' => '0',
'favicon_url' => 'app/favicon.ico'
'favicon_url' => 'app/favicon.ico',
];

View File

@ -18,14 +18,14 @@ return [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'guzzle' => [
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
],
],
'mandrill' => [
'secret' => env('MANDRILL_SECRET'),
'guzzle' => [
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
],
],
@ -34,14 +34,14 @@ return [
'secret' => env('SES_SECRET'),
'region' => env('SES_REGION'),
'guzzle' => [
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
],
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
'guzzle' => [
'verify' => config('secure.certificates')
'verify' => config('secure.certificates'),
],
],

View File

@ -6,6 +6,6 @@ use App\Models\Closet;
$factory->define(Closet::class, function (Faker\Generator $faker) {
return [
'uid' => factory(User::class)->create()->uid,
'textures' => '[]'
'textures' => '[]',
];
});

View File

@ -7,6 +7,6 @@ $factory->define(Player::class, function (Faker\Generator $faker) {
'uid' => factory(App\Models\User::class)->create()->uid,
'player_name' => $faker->firstName,
'tid_skin' => 0,
'last_modified' => $faker->dateTime
'last_modified' => $faker->dateTime,
];
});

View File

@ -11,7 +11,7 @@ $factory->define(Texture::class, function (Faker\Generator $faker) {
'size' => rand(1, 2048),
'uploader' => factory(App\Models\User::class)->create()->uid,
'public' => true,
'upload_at' => $faker->dateTime
'upload_at' => $faker->dateTime,
];
});
@ -24,7 +24,7 @@ $factory->defineAs(Texture::class, 'alex', function (Faker\Generator $faker) {
'size' => rand(1, 2048),
'uploader' => factory(App\Models\User::class)->create()->uid,
'public' => true,
'upload_at' => $faker->dateTime
'upload_at' => $faker->dateTime,
];
});
@ -37,6 +37,6 @@ $factory->defineAs(Texture::class, 'cape', function (Faker\Generator $faker) {
'size' => rand(1, 2048),
'uploader' => factory(App\Models\User::class)->create()->uid,
'public' => true,
'upload_at' => $faker->dateTime
'upload_at' => $faker->dateTime,
];
});

View File

@ -14,7 +14,7 @@ $factory->define(User::class, function (Faker\Generator $faker) {
'permission' => 0,
'verified' => true,
'last_sign_at' => $faker->dateTime->format('d-M-Y H:i:s'),
'register_at' => $faker->dateTime->format('d-M-Y H:i:s')
'register_at' => $faker->dateTime->format('d-M-Y H:i:s'),
];
});
@ -29,7 +29,7 @@ $factory->defineAs(User::class, 'admin', function (Faker\Generator $faker) {
'permission' => 1,
'verified' => true,
'last_sign_at' => $faker->dateTime->format('d-M-Y H:i:s'),
'register_at' => $faker->dateTime->format('d-M-Y H:i:s')
'register_at' => $faker->dateTime->format('d-M-Y H:i:s'),
];
});
@ -44,7 +44,7 @@ $factory->defineAs(User::class, 'superAdmin', function (Faker\Generator $faker)
'permission' => 2,
'verified' => true,
'last_sign_at' => $faker->dateTime->format('d-M-Y H:i:s'),
'register_at' => $faker->dateTime->format('d-M-Y H:i:s')
'register_at' => $faker->dateTime->format('d-M-Y H:i:s'),
];
});
@ -59,6 +59,6 @@ $factory->defineAs(User::class, 'banned', function (Faker\Generator $faker) {
'permission' => -1,
'verified' => true,
'last_sign_at' => $faker->dateTime->format('d-M-Y H:i:s'),
'register_at' => $faker->dateTime->format('d-M-Y H:i:s')
'register_at' => $faker->dateTime->format('d-M-Y H:i:s'),
];
});

View File

@ -1,6 +1,5 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ImportOptions extends Migration

View File

@ -5,12 +5,11 @@
* @Last Modified by: printempw
* @Last Modified time: 2016-08-29 13:47:13
*/
$options = [
'avatar_query_string' => '0',
'version' => '',
'check_update' => '1',
'update_source' => 'github'
'update_source' => 'github',
];
foreach ($options as $key => $value) {

View File

@ -5,8 +5,7 @@
* @Last Modified by: printempw
* @Last Modified time: 2016-08-27 18:21:15
*/
if (Option::get('update_source') == "github") {
if (Option::get('update_source') == 'github') {
Option::set('update_source', 'nyavm');
}

View File

@ -5,12 +5,11 @@
* @Last Modified by: printempw
* @Last Modified time: 2016-09-28 22:55:29
*/
Option::set('version', '3.1.1');
return [
'如果你是从 v3.0.x 升级上来的,请进行下列操作:',
'把 /textures 文件夹移动至 /storage 文件夹中',
'删除 /config/routes.php不然会出现奇怪的问题',
'重新复制一份 .env.example并适当修改其中的配置尤其注意 PWD_METHOD 要和以前一样,否则将无法登录)'
'重新复制一份 .env.example并适当修改其中的配置尤其注意 PWD_METHOD 要和以前一样,否则将无法登录)',
];

View File

@ -5,17 +5,16 @@
* @Last Modified by: printempw
* @Last Modified time: 2017-01-02 16:22:32
*/
if (!Illuminate\Support\Str::startsWith(option('update_source'), 'http')) {
if (! Illuminate\Support\Str::startsWith(option('update_source'), 'http')) {
Option::set('update_source', config('options.update_source'));
}
foreach (config('options') as $key => $value) {
if ($value === "true" || $value === "false") {
if ($value === 'true' || $value === 'false') {
$option = option($key);
if ($option === "0" || $option === "1") {
Option::set([$key => ($option === "0" ? "false" : "true")]);
if ($option === '0' || $option === '1') {
Option::set([$key => ($option === '0' ? 'false' : 'true')]);
}
}
}
@ -23,5 +22,5 @@ foreach (config('options') as $key => $value) {
Option::set('version', '3.2.0');
return [
'v3.2 新加入了插件系统,支持的插件请去程序发布帖查看'
'v3.2 新加入了插件系统,支持的插件请去程序发布帖查看',
];

View File

@ -5,5 +5,5 @@ Option::set('version', '3.4.0');
return [
'此版本中插件 API 变化较大,升级完成后务必将您目前正在使用的插件更新至【最新版本】',
'升级完成后请手动删除 storage/framework/views 目录下的缓存文件(如果它们没有被自动删除的话)',
'升级完成后请【务必】清空你的浏览器缓存,否则可能会出现奇怪的问题'
'升级完成后请【务必】清空你的浏览器缓存,否则可能会出现奇怪的问题',
];

View File

@ -1,17 +1,17 @@
<?php
/**
* Entrance of Blessing Skin Server
* Entrance of Blessing Skin Server.
*
* @package Blessing Skin Server
* @author printempw <h@prinzeugen.net>
*/
@ini_set('display_errors', 'on');
require __DIR__.'/../bootstrap/autoload.php';
if (!isset($GLOBALS['env_checked'])) require __DIR__.'/../bootstrap/chkenv.php';
if (! isset($GLOBALS['env_checked'])) {
require __DIR__.'/../bootstrap/chkenv.php';
}
// Process the request
require __DIR__.'/../bootstrap/kernel.php';

View File

@ -12,18 +12,17 @@
*/
/**
* Setup Wizard
* Setup Wizard.
*/
Route::group(['prefix' => 'setup'], function ()
{
Route::group(['prefix' => 'setup'], function () {
Route::group(['middleware' => 'setup'], function () {
Route::view('/', 'setup.wizard.welcome');
Route::view('/', 'setup.wizard.welcome');
Route::view('/database', 'setup.wizard.database');
Route::post('/database', 'SetupController@database');
Route::get ('/info', 'SetupController@info');
Route::post('/finish', 'SetupController@finish');
Route::get('/info', 'SetupController@info');
Route::post('/finish', 'SetupController@finish');
});
Route::get ('/update', 'SetupController@update');
Route::post('/update', 'SetupController@doUpdate');
Route::get('/update', 'SetupController@update');
Route::post('/update', 'SetupController@doUpdate');
});

View File

@ -12,27 +12,26 @@
*/
/**
* Resources
* Resources.
*/
Route::group(['middleware' => 'player'], function()
{
Route::group(['middleware' => 'player'], function () {
// Json profile
Route::get('/{player_name}.json', 'TextureController@json');
Route::get('/{api}/{player_name}.json', 'TextureController@jsonWithApi')->where('api', 'usm|csl');
Route::get('/{player_name}.json', 'TextureController@json');
Route::get('/{api}/{player_name}.json', 'TextureController@jsonWithApi')->where('api', 'usm|csl');
// Legacy links
Route::get('/skin/{player_name}.png', 'TextureController@skin');
Route::get('/cape/{player_name}.png', 'TextureController@cape');
Route::get('/skin/{player_name}.png', 'TextureController@skin');
Route::get('/cape/{player_name}.png', 'TextureController@cape');
});
Route::get('/textures/{hash}', 'TextureController@texture');
Route::get('/{api}/textures/{hash}', 'TextureController@textureWithApi')->where('api', 'usm|csl');
Route::get('/textures/{hash}', 'TextureController@texture');
Route::get('/{api}/textures/{hash}', 'TextureController@textureWithApi')->where('api', 'usm|csl');
Route::get('/avatar/{base64_email}.png', 'TextureController@avatar');
Route::get('/avatar/{base64_email}.png', 'TextureController@avatar');
Route::get('/avatar/{size}/{base64_email}.png', 'TextureController@avatarWithSize');
Route::get('/avatar/{tid}', 'TextureController@avatarByTid');
Route::get('/avatar/{size}/{tid}', 'TextureController@avatarByTidWithSize');
Route::get('/avatar/{tid}', 'TextureController@avatarByTid');
Route::get('/avatar/{size}/{tid}', 'TextureController@avatarByTidWithSize');
Route::get('/raw/{tid}.png', 'TextureController@raw');
Route::get('/raw/{tid}.png', 'TextureController@raw');
Route::get('/preview/{tid}.png', 'TextureController@preview');
Route::get('/preview/{size}/{tid}.png', 'TextureController@previewWithSize');
Route::get('/preview/{tid}.png', 'TextureController@preview');
Route::get('/preview/{size}/{tid}.png', 'TextureController@previewWithSize');

View File

@ -11,131 +11,125 @@
|
*/
Route::get('/', 'HomeController@index');
Route::get('/index.php', 'HomeController@index');
Route::get('/', 'HomeController@index');
Route::get('/index.php', 'HomeController@index');
Route::get('/locale/{lang}', 'HomeController@locale');
/**
/*
* Auth
*/
Route::group(['prefix' => 'auth'], function ()
{
Route::group(['middleware' => 'guest'], function ()
{
Route::view('/login', 'auth.login');
Route::get ('/register', 'AuthController@register');
Route::get ('/forgot', 'AuthController@forgot');
Route::get ('/reset/{uid}', 'AuthController@reset')->name('auth.reset')->middleware('signed');
Route::group(['prefix' => 'auth'], function () {
Route::group(['middleware' => 'guest'], function () {
Route::view('/login', 'auth.login');
Route::get('/register', 'AuthController@register');
Route::get('/forgot', 'AuthController@forgot');
Route::get('/reset/{uid}', 'AuthController@reset')->name('auth.reset')->middleware('signed');
});
Route::any('/logout', 'AuthController@logout');
Route::any('/captcha', '\Mews\Captcha\CaptchaController@getCaptcha');
Route::any('/logout', 'AuthController@logout');
Route::any('/captcha', '\Mews\Captcha\CaptchaController@getCaptcha');
Route::post('/login', 'AuthController@handleLogin');
Route::post('/register', 'AuthController@handleRegister');
Route::post('/forgot', 'AuthController@handleForgot');
Route::post('/reset/{uid}', 'AuthController@handleReset')->middleware('signed');
Route::post('/login', 'AuthController@handleLogin');
Route::post('/register', 'AuthController@handleRegister');
Route::post('/forgot', 'AuthController@handleForgot');
Route::post('/reset/{uid}', 'AuthController@handleReset')->middleware('signed');
Route::get ('/verify/{uid}', 'AuthController@verify')->name('auth.verify')->middleware('signed');
Route::get('/verify/{uid}', 'AuthController@verify')->name('auth.verify')->middleware('signed');
});
/**
/*
* User Center
*/
Route::group(['middleware' => ['web', 'auth'], 'prefix' => 'user'], function ()
{
Route::any ('', 'UserController@index');
Route::get ('/score-info', 'UserController@scoreInfo');
Route::post('/sign', 'UserController@sign');
Route::group(['middleware' => ['web', 'auth'], 'prefix' => 'user'], function () {
Route::any('', 'UserController@index');
Route::get('/score-info', 'UserController@scoreInfo');
Route::post('/sign', 'UserController@sign');
// Profile
Route::get ('/profile', 'UserController@profile');
Route::post('/profile', 'UserController@handleProfile');
Route::post('/profile/avatar', 'UserController@setAvatar');
Route::get('/profile', 'UserController@profile');
Route::post('/profile', 'UserController@handleProfile');
Route::post('/profile/avatar', 'UserController@setAvatar');
// Email Verification
Route::post('/email-verification', 'UserController@sendVerificationEmail');
Route::post('/email-verification', 'UserController@sendVerificationEmail');
// Player
Route::group(['prefix' => 'player', 'middleware' => 'verified'], function () {
Route::any ('', 'PlayerController@index');
Route::get ('/list', 'PlayerController@listAll');
Route::post('/add', 'PlayerController@add');
Route::any ('/show', 'PlayerController@show');
Route::post('/set', 'PlayerController@setTexture');
Route::any('', 'PlayerController@index');
Route::get('/list', 'PlayerController@listAll');
Route::post('/add', 'PlayerController@add');
Route::any('/show', 'PlayerController@show');
Route::post('/set', 'PlayerController@setTexture');
Route::post('/texture/clear', 'PlayerController@clearTexture');
Route::post('/rename', 'PlayerController@rename');
Route::post('/delete', 'PlayerController@delete');
Route::post('/rename', 'PlayerController@rename');
Route::post('/delete', 'PlayerController@delete');
});
// Closet
Route::get ('/closet', 'ClosetController@index');
Route::get ('/closet-data', 'ClosetController@getClosetData');
Route::post('/closet/add', 'ClosetController@add');
Route::post('/closet/remove', 'ClosetController@remove');
Route::post('/closet/rename', 'ClosetController@rename');
Route::get('/closet', 'ClosetController@index');
Route::get('/closet-data', 'ClosetController@getClosetData');
Route::post('/closet/add', 'ClosetController@add');
Route::post('/closet/remove', 'ClosetController@remove');
Route::post('/closet/rename', 'ClosetController@rename');
});
/**
/*
* Skin Library
*/
Route::group(['prefix' => 'skinlib'], function ()
{
Route::get('', 'SkinlibController@index');
Route::any('/info/{tid}', 'SkinlibController@info');
Route::any('/show/{tid}', 'SkinlibController@show');
Route::any('/data', 'SkinlibController@getSkinlibFiltered');
Route::group(['prefix' => 'skinlib'], function () {
Route::get('', 'SkinlibController@index');
Route::any('/info/{tid}', 'SkinlibController@info');
Route::any('/show/{tid}', 'SkinlibController@show');
Route::any('/data', 'SkinlibController@getSkinlibFiltered');
Route::group(['middleware' => ['auth', 'verified']], function ()
{
Route::get ('/upload', 'SkinlibController@upload');
Route::post('/upload', 'SkinlibController@handleUpload');
Route::post('/model', 'SkinlibController@model');
Route::post('/rename', 'SkinlibController@rename');
Route::post('/privacy', 'SkinlibController@privacy');
Route::post('/delete', 'SkinlibController@delete');
Route::group(['middleware' => ['auth', 'verified']], function () {
Route::get('/upload', 'SkinlibController@upload');
Route::post('/upload', 'SkinlibController@handleUpload');
Route::post('/model', 'SkinlibController@model');
Route::post('/rename', 'SkinlibController@rename');
Route::post('/privacy', 'SkinlibController@privacy');
Route::post('/delete', 'SkinlibController@delete');
});
});
/**
/*
* Admin Panel
*/
Route::group(['middleware' => ['auth', 'admin'], 'prefix' => 'admin'], function ()
{
Route::get('/', 'AdminController@index');
Route::group(['middleware' => ['auth', 'admin'], 'prefix' => 'admin'], function () {
Route::get('/', 'AdminController@index');
Route::any('/customize', 'AdminController@customize');
Route::any('/score', 'AdminController@score');
Route::any('/options', 'AdminController@options');
Route::any('/customize', 'AdminController@customize');
Route::any('/score', 'AdminController@score');
Route::any('/options', 'AdminController@options');
Route::view('/users', 'admin.users');
Route::any ('/user-data', 'AdminController@getUserData');
Route::view('/users', 'admin.users');
Route::any('/user-data', 'AdminController@getUserData');
Route::view('/players', 'admin.players');
Route::any ('/player-data', 'AdminController@getPlayerData');
Route::get ('/user/{uid}', 'AdminController@getOneUser');
Route::view('/players', 'admin.players');
Route::any('/player-data', 'AdminController@getPlayerData');
Route::get('/user/{uid}', 'AdminController@getOneUser');
// ajax handlers
Route::post('/users', 'AdminController@userAjaxHandler');
Route::post('/players', 'AdminController@playerAjaxHandler');
Route::post('/users', 'AdminController@userAjaxHandler');
Route::post('/players', 'AdminController@playerAjaxHandler');
Route::group(['prefix' => 'plugins', 'middleware' => 'super-admin'], function () {
Route::get ('/data', 'PluginController@getPluginData');
Route::get('/data', 'PluginController@getPluginData');
Route::view('/manage', 'admin.plugins');
Route::post('/manage', 'PluginController@manage');
Route::any ('/config/{name}', 'PluginController@config');
Route::any('/config/{name}', 'PluginController@config');
Route::view('/market', 'admin.market');
Route::get ('/market-data', 'MarketController@marketData');
Route::get ('/market/check', 'MarketController@checkUpdates');
Route::get('/market-data', 'MarketController@marketData');
Route::get('/market/check', 'MarketController@checkUpdates');
Route::post('/market/download', 'MarketController@download');
});
Route::group(['prefix' => 'update', 'middleware' => 'super-admin'], function () {
Route::any('', 'UpdateController@showUpdatePage');
Route::get('/check', 'UpdateController@checkUpdates');
Route::any('', 'UpdateController@showUpdatePage');
Route::get('/check', 'UpdateController@checkUpdates');
Route::any('/download', 'UpdateController@download');
});
});

View File

@ -7,7 +7,6 @@ use App\Models\Player;
use App\Models\Texture;
use Illuminate\Support\Str;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AdminControllerTest extends BrowserKitTestCase
@ -31,17 +30,17 @@ class AdminControllerTest extends BrowserKitTestCase
// Check if `color_scheme` is existed or not
$this->get('/admin/customize?action=color', [
'Accept' => 'application/json',
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'color scheme'])
'msg' => trans('validation.required', ['attribute' => 'color scheme']),
]);
// Change color
$this->get('/admin/customize?action=color&color_scheme=purple')
->seeJson([
'errno' => 0,
'msg' => trans('admin.customize.change-color.success')
'msg' => trans('admin.customize.change-color.success'),
]);
$this->assertEquals('purple', option('color_scheme'));
@ -166,8 +165,8 @@ class AdminControllerTest extends BrowserKitTestCase
'permission',
'register_at',
'operations',
'players_count'
]]
'players_count',
]],
]);
$user = factory(User::class)->create();
@ -179,8 +178,8 @@ class AdminControllerTest extends BrowserKitTestCase
'nickname' => $user->nickname,
'score' => $user->score,
'permission' => $user->permission,
'players_count' => 0
]]
'players_count' => 0,
]],
]);
}
@ -202,8 +201,8 @@ class AdminControllerTest extends BrowserKitTestCase
'player_name',
'tid_skin',
'tid_cape',
'last_modified'
]]
'last_modified',
]],
]);
$this->getJson('/admin/player-data?uid='.$user->uid)
@ -213,8 +212,8 @@ class AdminControllerTest extends BrowserKitTestCase
'uid' => $user->uid,
'player_name' => $player->player_name,
'tid_skin' => $player->tid_skin,
'tid_cape' => $player->tid_cape
]]
'tid_cape' => $player->tid_cape,
]],
]);
}
@ -224,7 +223,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/users')
->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.non-existent')
'msg' => trans('admin.users.operations.non-existent'),
]);
$user = factory(User::class)->create();
@ -233,7 +232,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/users', ['uid' => $user->uid])
->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.invalid')
'msg' => trans('admin.users.operations.invalid'),
]);
// An admin operating on a super admin should be forbidden
@ -241,7 +240,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/users', ['uid' => $superAdmin->uid])
->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.no-permission')
'msg' => trans('admin.users.operations.no-permission'),
]);
// Action is `email` but without `email` field
@ -251,7 +250,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'email'])
'msg' => trans('validation.required', ['attribute' => 'email']),
]);
// Action is `email` but with an invalid email address
@ -261,7 +260,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.email', ['attribute' => 'email'])
'msg' => trans('validation.email', ['attribute' => 'email']),
]);
// Using an existed email address
@ -270,7 +269,7 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'email', 'email' => $superAdmin->email]
)->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.email.existed', ['email' => $superAdmin->email])
'msg' => trans('admin.users.operations.email.existed', ['email' => $superAdmin->email]),
]);
// Set email successfully
@ -279,11 +278,11 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'email', 'email' => 'a@b.c']
)->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.email.success')
'msg' => trans('admin.users.operations.email.success'),
]);
$this->seeInDatabase('users', [
'uid' => $user->uid,
'email' => 'a@b.c'
'email' => 'a@b.c',
]);
// Toggle verification
@ -292,11 +291,11 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'verification']
)->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.verification.success')
'msg' => trans('admin.users.operations.verification.success'),
]);
$this->seeInDatabase('users', [
'uid' => $user->uid,
'verified' => 0
'verified' => 0,
]);
// Action is `nickname` but without `nickname` field
@ -306,7 +305,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'nickname'])
'msg' => trans('validation.required', ['attribute' => 'nickname']),
]);
// Action is `nickname` but with an invalid nickname
@ -316,7 +315,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.no_special_chars', ['attribute' => 'nickname'])
'msg' => trans('validation.no_special_chars', ['attribute' => 'nickname']),
]);
// Set nickname successfully
@ -325,11 +324,11 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'nickname', 'nickname' => 'nickname']
)->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.nickname.success', ['new' => 'nickname'])
'msg' => trans('admin.users.operations.nickname.success', ['new' => 'nickname']),
]);
$this->seeInDatabase('users', [
'uid' => $user->uid,
'nickname' => 'nickname'
'nickname' => 'nickname',
]);
// Action is `password` but without `password` field
@ -339,7 +338,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'password'])
'msg' => trans('validation.required', ['attribute' => 'password']),
]);
// Set a too short password
@ -349,7 +348,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8])
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8]),
]);
// Set a too long password
@ -359,7 +358,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 16])
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 16]),
]);
// Set password successfully
@ -368,7 +367,7 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'password', 'password' => '12345678']
)->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.password.success')
'msg' => trans('admin.users.operations.password.success'),
]);
$user = User::find($user->uid);
$this->assertTrue($user->verifyPassword('12345678'));
@ -380,7 +379,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'score'])
'msg' => trans('validation.required', ['attribute' => 'score']),
]);
// Action is `score` but with an not-an-integer value
@ -390,7 +389,7 @@ class AdminControllerTest extends BrowserKitTestCase
['Accept' => 'application/json']
)->seeJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'score'])
'msg' => trans('validation.integer', ['attribute' => 'score']),
]);
// Set score successfully
@ -399,11 +398,11 @@ class AdminControllerTest extends BrowserKitTestCase
['uid' => $user->uid, 'action' => 'score', 'score' => 123]
)->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.score.success')
'msg' => trans('admin.users.operations.score.success'),
]);
$this->seeInDatabase('users', [
'uid' => $user->uid,
'score' => 123
'score' => 123,
]);
// Ban a user
@ -411,7 +410,7 @@ class AdminControllerTest extends BrowserKitTestCase
->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.ban.ban.success'),
'permission' => User::BANNED
'permission' => User::BANNED,
]);
$user = User::find($user->uid);
$this->assertEquals(User::BANNED, $user->getPermission());
@ -421,7 +420,7 @@ class AdminControllerTest extends BrowserKitTestCase
->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.ban.unban.success'),
'permission' => User::NORMAL
'permission' => User::NORMAL,
]);
$user = User::find($user->uid);
$this->assertEquals(User::NORMAL, $user->getPermission());
@ -431,7 +430,7 @@ class AdminControllerTest extends BrowserKitTestCase
->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.admin.set.success'),
'permission' => User::ADMIN
'permission' => User::ADMIN,
]);
$user = User::find($user->uid);
$this->assertEquals(User::ADMIN, $user->getPermission());
@ -440,7 +439,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/users', ['uid' => $user->uid])
->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.no-permission')
'msg' => trans('admin.users.operations.no-permission'),
]);
// Set an admin to be a normal user
@ -449,7 +448,7 @@ class AdminControllerTest extends BrowserKitTestCase
->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.admin.unset.success'),
'permission' => User::NORMAL
'permission' => User::NORMAL,
]);
$user = User::find($user->uid);
$this->assertEquals(User::NORMAL, $user->getPermission());
@ -458,7 +457,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/users', ['uid' => $user->uid, 'action' => 'delete'])
->seeJson([
'errno' => 0,
'msg' => trans('admin.users.operations.delete.success')
'msg' => trans('admin.users.operations.delete.success'),
]);
$this->assertNull(User::find($user->uid));
}
@ -471,7 +470,7 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/players', ['pid' => -1])
->seeJson([
'errno' => 1,
'msg' => trans('general.unexistent-player')
'msg' => trans('general.unexistent-player'),
]);
// An admin cannot operate another admin's player
@ -481,7 +480,7 @@ class AdminControllerTest extends BrowserKitTestCase
['pid' => factory(Player::class)->create(['uid' => $admin->uid])->pid]
)->seeJson([
'errno' => 1,
'msg' => trans('admin.players.no-permission')
'msg' => trans('admin.players.no-permission'),
]);
$superAdmin = factory(User::class, 'superAdmin')->create();
$this->postJson(
@ -489,7 +488,7 @@ class AdminControllerTest extends BrowserKitTestCase
['pid' => factory(Player::class)->create(['uid' => $superAdmin->uid])->pid]
)->seeJson([
'errno' => 1,
'msg' => trans('admin.players.no-permission')
'msg' => trans('admin.players.no-permission'),
]);
// For self is OK
$this->actAs($admin)->postJson(
@ -497,30 +496,30 @@ class AdminControllerTest extends BrowserKitTestCase
['pid' => factory(Player::class)->create(['uid' => $admin->uid])->pid]
)->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.invalid')
'msg' => trans('admin.users.operations.invalid'),
]);
// Change texture without `type` field
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'texture'
'action' => 'texture',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'type'])
'msg' => trans('validation.required', ['attribute' => 'type']),
]);
// Change texture without `tid` field
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'texture',
'type' => 'skin'
'type' => 'skin',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'tid'])
'msg' => trans('validation.required', ['attribute' => 'tid']),
]);
// Change texture with a not-integer value
@ -528,12 +527,12 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'skin',
'tid' => 'string'
'tid' => 'string',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'tid'])
'msg' => trans('validation.integer', ['attribute' => 'tid']),
]);
// Invalid texture
@ -541,10 +540,10 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'skin',
'tid' => -1
'tid' => -1,
])->seeJson([
'errno' => 1,
'msg' => trans('admin.players.textures.non-existent', ['tid' => -1])
'msg' => trans('admin.players.textures.non-existent', ['tid' => -1]),
]);
$skin = factory(Texture::class)->create();
@ -555,10 +554,10 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'skin',
'tid' => $skin->tid
'tid' => $skin->tid,
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name])
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name]),
]);
$player = Player::find($player->pid);
$this->assertEquals($skin->tid, $player->tid_skin);
@ -568,10 +567,10 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'cape',
'tid' => $cape->tid
'tid' => $cape->tid,
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name])
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name]),
]);
$player = Player::find($player->pid);
$this->assertEquals($cape->tid, $player->tid_cape);
@ -581,10 +580,10 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'skin',
'tid' => 0
'tid' => 0,
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name])
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name]),
]);
$player = Player::find($player->pid);
$this->assertEquals(0, $player->tid_skin);
@ -594,10 +593,10 @@ class AdminControllerTest extends BrowserKitTestCase
'pid' => $player->pid,
'action' => 'texture',
'type' => 'cape',
'tid' => 0
'tid' => 0,
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name])
'msg' => trans('admin.players.textures.success', ['player' => $player->player_name]),
]);
$player = Player::find($player->pid);
$this->assertEquals(0, $player->tid_cape);
@ -605,34 +604,34 @@ class AdminControllerTest extends BrowserKitTestCase
// Change owner without `uid` field
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'owner'
'action' => 'owner',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'uid'])
'msg' => trans('validation.required', ['attribute' => 'uid']),
]);
// Change owner with a not-integer `uid` value
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'owner',
'uid' => 'string'
'uid' => 'string',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'uid'])
'msg' => trans('validation.integer', ['attribute' => 'uid']),
]);
// Change owner to a not-existed user
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'owner',
'uid' => -1
'uid' => -1,
])->seeJson([
'errno' => 1,
'msg' => trans('admin.users.operations.non-existent')
'msg' => trans('admin.users.operations.non-existent'),
]);
// Change owner successfully
@ -640,44 +639,44 @@ class AdminControllerTest extends BrowserKitTestCase
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'owner',
'uid' => $user->uid
'uid' => $user->uid,
])->seeJson([
'errno' => 0,
'msg' => trans(
'admin.players.owner.success',
['player' => $player->player_name, 'user' => $user->nickname]
)
),
]);
// Rename a player without `name` field
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'name'
'action' => 'name',
], [
'Accept' => 'application/json',
])->seeJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'name'])
'msg' => trans('validation.required', ['attribute' => 'name']),
]);
// Rename a player successfully
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'name',
'name' => 'new_name'
'name' => 'new_name',
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.name.success', ['player' => 'new_name']),
'name' => 'new_name'
'name' => 'new_name',
]);
// Delete a player
$this->postJson('/admin/players', [
'pid' => $player->pid,
'action' => 'delete'
'action' => 'delete',
])->seeJson([
'errno' => 0,
'msg' => trans('admin.players.delete.success')
'msg' => trans('admin.players.delete.success'),
]);
$this->assertNull(Player::find($player->pid));
}
@ -697,14 +696,14 @@ class AdminControllerTest extends BrowserKitTestCase
'avatar' => $user->avatar,
'permission' => $user->permission,
'verified' => (bool) $user->verified,
'verification_token' => (string) $user->verification_token
]
'verification_token' => (string) $user->verification_token,
],
]);
$this->get('/admin/user/-1')
->seeJson([
'errno' => 1,
'msg' => 'No such user.'
'msg' => 'No such user.',
]);
}
}

View File

@ -10,8 +10,6 @@ use App\Mail\ForgotPassword;
use App\Services\Facades\Option;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AuthControllerTest extends TestCase
@ -32,52 +30,52 @@ class AuthControllerTest extends TestCase
$user->changePassword('12345678');
$player = factory(Player::class)->create(
[
'uid' => $user->uid
'uid' => $user->uid,
]
);
// Should return a warning if `identification` is empty
$this->postJson(
'/auth/login', [], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.identification')])
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.identification')]),
]);
// Should return a warning if `password` is empty
$this->postJson(
'/auth/login', [
'identification' => $user->email
'identification' => $user->email,
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'password'])
'msg' => trans('validation.required', ['attribute' => 'password']),
]);
// Should return a warning if length of `password` is lower than 6
$this->postJson(
'/auth/login', [
'identification' => $user->email,
'password' => '123'
'password' => '123',
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 6])
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 6]),
]);
// Should return a warning if length of `password` is greater than 32
$this->postJson(
'/auth/login', [
'identification' => $user->email,
'password' => Str::random(80)
'password' => Str::random(80),
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32])
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32]),
]);
$this->flushSession();
@ -88,12 +86,12 @@ class AuthControllerTest extends TestCase
$this->postJson(
'/auth/login', [
'identification' => $user->email,
'password' => 'wrong-password'
'password' => 'wrong-password',
])->assertJson(
[
'errno' => 1,
'msg' => trans('auth.validation.password'),
'login_fails' => 1
'login_fails' => 1,
]
);
$this->assertCacheHas($loginFailsCacheKey);
@ -108,7 +106,7 @@ class AuthControllerTest extends TestCase
'password' => '12345678',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'captcha'])
'msg' => trans('validation.required', ['attribute' => 'captcha']),
]);
$this->flushCache();
@ -118,10 +116,10 @@ class AuthControllerTest extends TestCase
$this->postJson(
'/auth/login', [
'identification' => 'nope@nope.net',
'password' => '12345678'
'password' => '12345678',
])->assertJson([
'errno' => 2,
'msg' => trans('auth.validation.user')
'msg' => trans('auth.validation.user'),
]);
$this->flushSession();
@ -130,11 +128,11 @@ class AuthControllerTest extends TestCase
$this->withCache([$loginFailsCacheKey => 1])
->postJson('/auth/login', [
'identification' => $user->email,
'password' => '12345678'
'password' => '12345678',
])->assertJson(
[
'errno' => 0,
'msg' => trans('auth.login.success')
'msg' => trans('auth.login.success'),
]
);
$this->assertCacheMissing($loginFailsCacheKey);
@ -146,12 +144,12 @@ class AuthControllerTest extends TestCase
$this->postJson(
'/auth/login', [
'identification' => $player->player_name,
'password' => '12345678'
'password' => '12345678',
]
)->assertJson(
[
'errno' => 0,
'msg' => trans('auth.login.success')
'msg' => trans('auth.login.success'),
]
);
$this->assertAuthenticated();
@ -162,14 +160,14 @@ class AuthControllerTest extends TestCase
$this->postJson('/auth/logout')
->assertJson([
'errno' => 1,
'msg' => trans('auth.logout.fail')
'msg' => trans('auth.logout.fail'),
]);
$user = factory(User::class)->create();
$this->actingAs($user)->postJson('/auth/logout')->assertJson(
[
'errno' => 0,
'msg' => trans('auth.logout.success')
'msg' => trans('auth.logout.success'),
]
);
$this->assertGuest();
@ -194,7 +192,7 @@ class AuthControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'email'])
'msg' => trans('validation.required', ['attribute' => 'email']),
]);
// Should return a warning if `email` is invalid
@ -204,7 +202,7 @@ class AuthControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.email', ['attribute' => 'email'])
'msg' => trans('validation.email', ['attribute' => 'email']),
]);
// An existed user
@ -215,7 +213,7 @@ class AuthControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.unique', ['attribute' => 'email'])
'msg' => trans('validation.unique', ['attribute' => 'email']),
]);
// Should return a warning if `password` is empty
@ -225,7 +223,7 @@ class AuthControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'password'])
'msg' => trans('validation.required', ['attribute' => 'password']),
]);
// Should return a warning if length of `password` is lower than 8
@ -233,12 +231,12 @@ class AuthControllerTest extends TestCase
'/auth/register',
[
'email' => 'a@b.c',
'password' => '1'
'password' => '1',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8])
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8]),
]);
// Should return a warning if length of `password` is greater than 32
@ -246,11 +244,11 @@ class AuthControllerTest extends TestCase
'/auth/register',
[
'email' => 'a@b.c',
'password' => Str::random(33)
'password' => Str::random(33),
]
)->assertJson([
'errno' => 1,
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32])
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32]),
]);
// The register_with_player_name option is set to true by default.
@ -260,11 +258,11 @@ class AuthControllerTest extends TestCase
[
'email' => 'a@b.c',
'password' => '12345678',
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Should return a warning if `player_name` is invalid
@ -275,11 +273,11 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'player_name' => '角色名',
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson([
'errno' => 1,
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Should return a warning if `player_name` is too long
@ -289,14 +287,14 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'player_name' => Str::random(option('player_name_length_max') + 10),
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson([
'errno' => 1,
'msg' => trans('validation.max.string', [
'attribute' => trans('validation.attributes.player_name'),
'max' => option('player_name_length_max')
])
'max' => option('player_name_length_max'),
]),
]);
// Existed player
@ -307,11 +305,11 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'player_name' => $player->player_name,
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson([
'errno' => 2,
'msg' => trans('user.player.add.repeated')
'msg' => trans('user.player.add.repeated'),
]);
option(['register_with_player_name' => false]);
@ -322,12 +320,12 @@ class AuthControllerTest extends TestCase
[
'email' => 'a@b.c',
'password' => '12345678',
'captcha' => 'a'
'captcha' => 'a',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'nickname'])
'msg' => trans('validation.required', ['attribute' => 'nickname']),
]);
// Should return a warning if `nickname` is invalid
@ -337,12 +335,12 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => '\\',
'captcha' => 'a'
'captcha' => 'a',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.no_special_chars', ['attribute' => 'nickname'])
'msg' => trans('validation.no_special_chars', ['attribute' => 'nickname']),
]);
// Should return a warning if `nickname` is too long
@ -352,12 +350,12 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => Str::random(256),
'captcha' => 'a'
'captcha' => 'a',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.max.string', ['attribute' => 'nickname', 'max' => 255])
'msg' => trans('validation.max.string', ['attribute' => 'nickname', 'max' => 255]),
]);
// Should return a warning if `captcha` is empty
@ -366,15 +364,14 @@ class AuthControllerTest extends TestCase
[
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => 'nickname'
'nickname' => 'nickname',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'captcha'])
'msg' => trans('validation.required', ['attribute' => 'captcha']),
]);
// Should be forbidden if registering is closed
Option::set('user_can_register', false);
$this->postJson(
@ -383,12 +380,12 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => 'nickname',
'captcha' => 'a'
'captcha' => 'a',
],
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 7,
'msg' => trans('auth.register.close')
'msg' => trans('auth.register.close'),
]);
// Reopen for test
@ -402,11 +399,11 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => 'nickname',
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson([
'errno' => 7,
'msg' => trans('auth.register.max', ['regs' => option('regs_per_ip')])
'msg' => trans('auth.register.max', ['regs' => option('regs_per_ip')]),
]);
Option::set('regs_per_ip', 100);
@ -418,13 +415,13 @@ class AuthControllerTest extends TestCase
'email' => 'a@b.c',
'password' => '12345678',
'nickname' => 'nickname',
'captcha' => 'a'
'captcha' => 'a',
]
);
$newUser = User::where('email', 'a@b.c')->first();
$response->assertJson([
'errno' => 0,
'msg' => trans('auth.register.success')
'msg' => trans('auth.register.success'),
]);
$this->assertTrue($newUser->verifyPassword('12345678'));
$this->assertDatabaseHas('users', [
@ -432,7 +429,7 @@ class AuthControllerTest extends TestCase
'nickname' => 'nickname',
'score' => option('user_initial_score'),
'ip' => '127.0.0.1',
'permission' => User::NORMAL
'permission' => User::NORMAL,
]);
$this->assertAuthenticated();
@ -444,7 +441,7 @@ class AuthControllerTest extends TestCase
'email' => 'abc@test.org',
'password' => '12345678',
'player_name' => 'name',
'captcha' => 'a'
'captcha' => 'a',
]
)->assertJson(['errno' => 0]);
$this->assertNotNull(Player::where('player_name', 'name'));
@ -465,10 +462,10 @@ class AuthControllerTest extends TestCase
// Should be forbidden if "forgot password" is closed
config(['mail.driver' => '']);
$this->postJson('/auth/forgot', [
'captcha' => 'a'
'captcha' => 'a',
])->assertJson([
'errno' => 1,
'msg' => trans('auth.forgot.disabled')
'msg' => trans('auth.forgot.disabled'),
]);
config(['mail.driver' => 'smtp']);
@ -476,12 +473,12 @@ class AuthControllerTest extends TestCase
// Should be forbidden if sending email frequently
$this->withCache([
$lastMailCacheKey => time()
$lastMailCacheKey => time(),
])->postJson('/auth/forgot', [
'captcha' => 'a'
'captcha' => 'a',
])->assertJson([
'errno' => 2,
'msg' => trans('auth.forgot.frequent-mail')
'msg' => trans('auth.forgot.frequent-mail'),
]);
$this->flushCache();
$this->flushSession();
@ -490,18 +487,18 @@ class AuthControllerTest extends TestCase
$user = factory(User::class)->create();
$this->withSession(['phrase' => 'a'])->postJson('/auth/forgot', [
'email' => 'nope@nope.net',
'captcha' => 'a'
'captcha' => 'a',
])->assertJson([
'errno' => 1,
'msg' => trans('auth.forgot.unregistered')
'msg' => trans('auth.forgot.unregistered'),
]);
$this->postJson('/auth/forgot', [
'email' => $user->email,
'captcha' => 'a'
'captcha' => 'a',
])->assertJson([
'errno' => 0,
'msg' => trans('auth.forgot.success')
'msg' => trans('auth.forgot.success'),
]);
$this->assertCacheHas($lastMailCacheKey);
$this->flushCache();
@ -517,10 +514,10 @@ class AuthControllerTest extends TestCase
$this->withSession(['phrase' => 'a'])
->postJson('/auth/forgot', [
'email' => $user->email,
'captcha' => 'a'
'captcha' => 'a',
])->assertJson([
'errno' => 2,
'msg' => trans('auth.forgot.failed', ['msg' => 'A fake exception.'])
'msg' => trans('auth.forgot.failed', ['msg' => 'A fake exception.']),
]);
// Addition: Mailable test
@ -549,32 +546,32 @@ class AuthControllerTest extends TestCase
// Should return a warning if `password` is empty
$this->postJson(
$url, [], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'password'])
'msg' => trans('validation.required', ['attribute' => 'password']),
]);
// Should return a warning if `password` is too short
$this->postJson(
$url, [
'password' => '123'
'password' => '123',
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8])
'msg' => trans('validation.min.string', ['attribute' => 'password', 'min' => 8]),
]);
// Should return a warning if `password` is too long
$this->postJson(
$url, [
'password' => Str::random(33)
'password' => Str::random(33),
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32])
'msg' => trans('validation.max.string', ['attribute' => 'password', 'max' => 32]),
]);
// Success
@ -583,7 +580,7 @@ class AuthControllerTest extends TestCase
'password' => '12345678',
])->assertJson([
'errno' => 0,
'msg' => trans('auth.reset.success')
'msg' => trans('auth.reset.success'),
]);
// We must re-query the user model,
// because the old instance hasn't been changed

View File

@ -49,6 +49,7 @@ class BrowserKitTestCase extends TestCase
$role = factory(\App\Models\User::class, $role)->create();
}
}
return $this->actingAs($role);
}

View File

@ -5,8 +5,6 @@ namespace Tests;
use App\Models\User;
use App\Models\Closet;
use App\Models\Texture;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ClosetControllerTest extends TestCase
@ -44,7 +42,7 @@ class ClosetControllerTest extends TestCase
->assertJsonStructure([
'category',
'total_pages',
'items' => [['tid', 'name', 'type', 'add_at']]
'items' => [['tid', 'name', 'type', 'add_at']],
]);
// Responsive
@ -67,8 +65,8 @@ class ClosetControllerTest extends TestCase
'tid' => $cape->tid,
'name' => 'custom_name',
'type' => 'cape',
'add_at' => $closet->get($cape->tid)['add_at']
]]
'add_at' => $closet->get($cape->tid)['add_at'],
]],
]);
// Search by keyword
@ -81,8 +79,8 @@ class ClosetControllerTest extends TestCase
'tid' => $random->tid,
'name' => $random->name,
'type' => $random->type,
'add_at' => $closet->get($random->tid)['add_at']
]]
'add_at' => $closet->get($random->tid)['add_at'],
]],
]);
}
@ -96,7 +94,7 @@ class ClosetControllerTest extends TestCase
$this->postJson('/user/closet/add', [], ['X-Requested-With' => 'XMLHttpRequest'])
->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'tid'])
'msg' => trans('validation.required', ['attribute' => 'tid']),
]);
// `tid` is not a integer
@ -106,7 +104,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'tid'])
'msg' => trans('validation.integer', ['attribute' => 'tid']),
]);
// Missing `name` field
@ -116,7 +114,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'name'])
'msg' => trans('validation.required', ['attribute' => 'name']),
]);
// `name` field has special characters
@ -126,7 +124,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.no_special_chars', ['attribute' => 'name'])
'msg' => trans('validation.no_special_chars', ['attribute' => 'name']),
]);
// The user doesn't have enough score to add a texture
@ -136,7 +134,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid, 'name' => $name]
)->assertJson([
'errno' => 7,
'msg' => trans('user.closet.add.lack-score')
'msg' => trans('user.closet.add.lack-score'),
]);
// Add a not-existed texture
@ -146,7 +144,7 @@ class ClosetControllerTest extends TestCase
['tid' => -1, 'name' => 'my']
)->assertJson([
'errno' => 1,
'msg' => trans('user.closet.add.not-found')
'msg' => trans('user.closet.add.not-found'),
]);
// Add a texture successfully
@ -155,7 +153,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid, 'name' => $name]
)->assertJson([
'errno' => 0,
'msg' => trans('user.closet.add.success', ['name' => $name])
'msg' => trans('user.closet.add.success', ['name' => $name]),
]);
$this->assertEquals($texture->likes + 1, Texture::find($texture->tid)->likes);
$this->user = User::find($this->user->uid);
@ -169,7 +167,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid, 'name' => $name]
)->assertJson([
'errno' => 1,
'msg' => trans('user.closet.add.repeated')
'msg' => trans('user.closet.add.repeated'),
]);
}
@ -182,7 +180,7 @@ class ClosetControllerTest extends TestCase
$this->postJson('/user/closet/rename', [], ['X-Requested-With' => 'XMLHttpRequest'])
->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'tid'])
'msg' => trans('validation.required', ['attribute' => 'tid']),
]);
// `tid` is not a integer
@ -192,7 +190,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'tid'])
'msg' => trans('validation.integer', ['attribute' => 'tid']),
]);
// Missing `new_name` field
@ -202,7 +200,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'new name'])
'msg' => trans('validation.required', ['attribute' => 'new name']),
]);
// `new_name` field has special characters
@ -212,7 +210,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.no_special_chars', ['attribute' => 'new name'])
'msg' => trans('validation.no_special_chars', ['attribute' => 'new name']),
]);
// Rename a not-existed texture
@ -221,7 +219,7 @@ class ClosetControllerTest extends TestCase
['tid' => -1, 'new_name' => $name]
)->assertJson([
'errno' => 1,
'msg' => trans('user.closet.remove.non-existent')
'msg' => trans('user.closet.remove.non-existent'),
]);
// Rename a closet item successfully
@ -234,7 +232,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid, 'new_name' => $name]
)->assertJson([
'errno' => 0,
'msg' => trans('user.closet.rename.success', ['name' => 'new'])
'msg' => trans('user.closet.rename.success', ['name' => 'new']),
]);
$closet->save();
$closet = new Closet($this->user->uid);
@ -249,7 +247,7 @@ class ClosetControllerTest extends TestCase
$this->postJson('/user/closet/remove', [], ['X-Requested-With' => 'XMLHttpRequest'])
->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => 'tid'])
'msg' => trans('validation.required', ['attribute' => 'tid']),
]);
// `tid` is not a integer
@ -259,7 +257,7 @@ class ClosetControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.integer', ['attribute' => 'tid'])
'msg' => trans('validation.integer', ['attribute' => 'tid']),
]);
// Rename a not-existed texture
@ -268,7 +266,7 @@ class ClosetControllerTest extends TestCase
['tid' => -1]
)->assertJson([
'errno' => 1,
'msg' => trans('user.closet.remove.non-existent')
'msg' => trans('user.closet.remove.non-existent'),
]);
// Should return score if `return_score` is true
@ -281,7 +279,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid]
)->assertJson([
'errno' => 0,
'msg' => trans('user.closet.remove.success')
'msg' => trans('user.closet.remove.success'),
]);
$closet = new Closet($this->user->uid);
$this->assertEquals($texture->likes - 1, Texture::find($texture->tid)->likes);
@ -300,7 +298,7 @@ class ClosetControllerTest extends TestCase
['tid' => $texture->tid]
)->assertJson([
'errno' => 0,
'msg' => trans('user.closet.remove.success')
'msg' => trans('user.closet.remove.success'),
]);
$closet = new Closet($this->user->uid);
$this->assertEquals($texture->likes - 1, Texture::find($texture->tid)->likes);

View File

@ -5,9 +5,6 @@ namespace Tests;
use Faker;
use Artisan;
use App\Models\Player;
use App\Console\Commands\MigratePlayersTable;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class MigratePlayersTableTest extends TestCase

View File

@ -25,8 +25,8 @@ trait GeneratesFakePlugins
'url' => 'https://'.Str::random(10).'.test',
'namespace' => Str::random(10),
'require' => [
'blessing-skin-server' => '^3.4.0 || ^4.0.0'
]
'blessing-skin-server' => '^3.4.0 || ^4.0.0',
],
], $info);
}
@ -42,8 +42,8 @@ trait GeneratesFakePlugins
'dist' => [
'type' => 'zip',
'url' => 'https://plugins-registry.test/'.Str::random(10).'.zip',
'shasum' => strtolower(Str::random(40))
]
'shasum' => strtolower(Str::random(40)),
],
], $info));
}
@ -61,8 +61,8 @@ trait GeneratesFakePlugins
$plugins = [
[
'name' => func_get_arg(0),
'version' => func_get_arg(1)
]
'version' => func_get_arg(1),
],
];
}
@ -80,7 +80,7 @@ trait GeneratesFakePlugins
}
return json_encode([
'packages' => $packages
'packages' => $packages,
]);
}

View File

@ -72,6 +72,7 @@ trait InteractsWithCache
{
if (is_array($key)) {
$this->assertCacheHasAll($key);
return $this;
}
@ -80,6 +81,7 @@ trait InteractsWithCache
} else {
$this->assertEquals($value, $this->app['cache.store']->get($key));
}
return $this;
}

View File

@ -39,7 +39,7 @@ trait MocksGuzzleClient
* Add responses to Guzzle client's mock queue.
* Pass a Response or RequestException instance, or an array of them.
*
* @param array|Response|RequestException|integer $response
* @param array|Response|RequestException|int $response
* @param array $headers
* @param string $body
* @param string $version
@ -55,6 +55,7 @@ trait MocksGuzzleClient
foreach ($response as $single) {
$this->appendToGuzzleQueue($single);
}
return;
}

View File

@ -3,12 +3,9 @@
namespace Tests;
use stdClass;
use App\Events\RenderingHeader;
use App\Events\RenderingFooter;
use App\Events\RenderingHeader;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class HomeControllerTest extends TestCase
{

View File

@ -27,10 +27,10 @@ class MarketControllerTest extends TestCase
// Try to download a non-existent plugin
$this->appendToGuzzleQueue(200, [], $this->generateFakePluginsRegistry());
$this->postJson('/admin/plugins/market/download', [
'name' => 'non-existent-plugin'
'name' => 'non-existent-plugin',
])->assertJson([
'errno' => 1,
'msg' => trans('admin.plugins.market.non-existent', ['plugin' => 'non-existent-plugin'])
'msg' => trans('admin.plugins.market.non-existent', ['plugin' => 'non-existent-plugin']),
]);
// Can't download due to connection error
@ -39,10 +39,10 @@ class MarketControllerTest extends TestCase
new RequestException('Connection Error', new Request('GET', 'whatever')),
]);
$this->postJson('/admin/plugins/market/download', [
'name' => 'fake-test-download'
'name' => 'fake-test-download',
])->assertJson([
'errno' => 2,
'msg' => trans('admin.plugins.market.download-failed', ['error' => 'Connection Error'])
'msg' => trans('admin.plugins.market.download-failed', ['error' => 'Connection Error']),
]);
// Downloaded plugin archive was tampered
@ -52,10 +52,10 @@ class MarketControllerTest extends TestCase
new Response(200, [], fopen($fakeArchive, 'r')),
]);
$this->postJson('/admin/plugins/market/download', [
'name' => 'fake-test-download'
'name' => 'fake-test-download',
])->assertJson([
'errno' => 3,
'msg' => trans('admin.plugins.market.shasum-failed')
'msg' => trans('admin.plugins.market.shasum-failed'),
]);
// Download and extract plugin
@ -67,17 +67,17 @@ class MarketControllerTest extends TestCase
'version' => '0.0.1',
'dist' => [
'url' => 'whatever',
'shasum' => $shasum
]
]
'shasum' => $shasum,
],
],
])),
new Response(200, [], fopen($fakeArchive, 'r')),
]);
$this->postJson('/admin/plugins/market/download', [
'name' => 'fake-test-download'
'name' => 'fake-test-download',
])->assertJson([
'errno' => 0,
'msg' => trans('admin.plugins.market.install-success')
'msg' => trans('admin.plugins.market.install-success'),
]);
$this->assertTrue(is_dir(base_path('plugins/fake-test-download')));
$this->assertTrue(empty(glob(base_path('plugins/fake-test-download_*.zip'))));
@ -92,17 +92,17 @@ class MarketControllerTest extends TestCase
'version' => '0.0.1',
'dist' => [
'url' => 'whatever',
'shasum' => $shasum
]
]
'shasum' => $shasum,
],
],
])),
new Response(200, [], fopen($fakeArchive, 'r')),
]);
$this->postJson('/admin/plugins/market/download', [
'name' => 'fake-test-download'
'name' => 'fake-test-download',
])->assertJson([
'errno' => 4,
'msg' => trans('admin.plugins.market.unzip-failed', ['error' => 19])
'msg' => trans('admin.plugins.market.unzip-failed', ['error' => 19]),
]);
}
@ -115,7 +115,7 @@ class MarketControllerTest extends TestCase
$this->getJson('/admin/plugins/market/check')
->assertJson([
'available' => false,
'plugins' => []
'plugins' => [],
]);
// Generate fake plugin and refresh plugin manager
@ -127,7 +127,7 @@ class MarketControllerTest extends TestCase
$this->getJson('/admin/plugins/market/check')
->assertJson([
'available' => false,
'plugins' => []
'plugins' => [],
]);
// New version available
@ -136,8 +136,8 @@ class MarketControllerTest extends TestCase
->assertJson([
'available' => true,
'plugins' => [[
'name' => 'fake-test-update'
]]
'name' => 'fake-test-update',
]],
]);
}
@ -164,11 +164,11 @@ class MarketControllerTest extends TestCase
'description',
'author',
'dist',
'dependencies'
]
'dependencies',
],
]);
File::deleteDirectory(base_path('plugins/' . $package['name']));
File::deleteDirectory(base_path('plugins/'.$package['name']));
}
protected function tearDown(): void

View File

@ -6,8 +6,6 @@ use DB;
use App\Models\User;
use App\Services\Facades\Option;
use Illuminate\Support\Facades\Schema;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class MiddlewareTest extends TestCase
@ -111,7 +109,7 @@ class MiddlewareTest extends TestCase
$this->get('/setup')->assertSee('Already installed');
$tables = [
'closets', 'migrations', 'options', 'players', 'textures', 'users'
'closets', 'migrations', 'options', 'players', 'textures', 'users',
];
array_walk($tables, function ($table) {
Schema::dropIfExists($table);
@ -154,17 +152,17 @@ class MiddlewareTest extends TestCase
$this->actAs($user)
->postJson('/user/player/rename', [
'pid' => -1,
'new_player_name' => 'name'
'new_player_name' => 'name',
])->assertJson([
'errno' => 1,
'msg' => trans('general.unexistent-player')
'msg' => trans('general.unexistent-player'),
]);
$this->actAs($user)
->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => 'name'
'new_player_name' => 'name',
])->assertJson([
'errno' => 0
'errno' => 0,
]);
}
@ -180,18 +178,18 @@ class MiddlewareTest extends TestCase
$this->actAs($other_user)
->postJson('/user/player/rename', [
'pid' => $player->pid
'pid' => $player->pid,
])->assertJson([
'errno' => 1,
'msg' => trans('admin.players.no-permission')
'msg' => trans('admin.players.no-permission'),
]);
$this->actAs($owner)
->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => 'name'
'new_player_name' => 'name',
])->assertJson([
'errno' => 0
'errno' => 0,
]);
}

View File

@ -5,8 +5,6 @@ namespace Tests;
use App\Models\User;
use App\Models\Closet;
use App\Models\Texture;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ClosetTest extends TestCase
@ -27,7 +25,7 @@ class ClosetTest extends TestCase
$other = factory(User::class)->create();
$texture = factory(Texture::class)->create([
'uploader' => $other->uid,
'public' => false
'public' => false,
]);
$user = factory(User::class)->create();
$closet = new Closet($user->uid);

View File

@ -4,8 +4,6 @@ namespace Tests;
use App\Models\Player;
use App\Models\Texture;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PlayerTest extends TestCase

View File

@ -3,8 +3,6 @@
namespace Tests;
use App\Models\User;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserTest extends TestCase
@ -14,7 +12,7 @@ class UserTest extends TestCase
public function testSign()
{
$user = factory(User::class)->make([
'last_sign_at' => get_datetime_string(time())
'last_sign_at' => get_datetime_string(time()),
]);
$user->sign();
$this->assertFalse($user->sign());

View File

@ -6,8 +6,6 @@ use App\Events;
use App\Models\User;
use App\Models\Player;
use App\Models\Texture;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PlayerControllerTest extends TestCase
@ -37,7 +35,7 @@ class PlayerControllerTest extends TestCase
[
'pid' => $player->pid,
'player_name' => $player->player_name,
]
],
]);
}
@ -47,7 +45,7 @@ class PlayerControllerTest extends TestCase
$this->postJson('/user/player/add', [], ['X-Requested-With' => 'XMLHttpRequest'])
->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Only A-Za-z0-9_ are allowed
@ -58,7 +56,7 @@ class PlayerControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Custom player name rule (regexp)
@ -70,7 +68,7 @@ class PlayerControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 1,
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Lack of score
@ -82,7 +80,7 @@ class PlayerControllerTest extends TestCase
['X-Requested-With' => 'XMLHttpRequest']
)->assertJson([
'errno' => 7,
'msg' => trans('user.player.add.lack-score')
'msg' => trans('user.player.add.lack-score'),
]);
$this->expectsEvents(Events\CheckPlayerExists::class);
@ -91,10 +89,10 @@ class PlayerControllerTest extends TestCase
$user = factory(User::class)->create();
$score = $user->score;
$this->actAs($user)->postJson('/user/player/add', [
'player_name' => '角色名'
'player_name' => '角色名',
])->assertJson([
'errno' => 0,
'msg' => trans('user.player.add.success', ['name' => '角色名'])
'msg' => trans('user.player.add.success', ['name' => '角色名']),
]);
$this->expectsEvents(Events\PlayerWillBeAdded::class);
$this->expectsEvents(Events\PlayerWasAdded::class);
@ -111,7 +109,7 @@ class PlayerControllerTest extends TestCase
$this->postJson('/user/player/add', ['player_name' => '角色名'])
->assertJson([
'errno' => 6,
'msg' => trans('user.player.add.repeated')
'msg' => trans('user.player.add.repeated'),
]);
}
@ -125,7 +123,7 @@ class PlayerControllerTest extends TestCase
->postJson('/user/player/delete', ['pid' => $player->pid])
->assertJson([
'errno' => 0,
'msg' => trans('user.player.delete.success', ['name' => $player->player_name])
'msg' => trans('user.player.delete.success', ['name' => $player->player_name]),
]);
$this->assertNull(Player::find($player->pid));
$this->expectsEvents(Events\PlayerWasDeleted::class);
@ -142,7 +140,7 @@ class PlayerControllerTest extends TestCase
->postJson('/user/player/delete', ['pid' => $player->pid])
->assertJson([
'errno' => 0,
'msg' => trans('user.player.delete.success', ['name' => $player->player_name])
'msg' => trans('user.player.delete.success', ['name' => $player->player_name]),
]);
$this->assertEquals(
$user->score,
@ -167,57 +165,57 @@ class PlayerControllerTest extends TestCase
->postJson('/user/player/rename', [
'pid' => $player->pid,
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.required', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Only A-Za-z0-9_ are allowed
option(['player_name_rule' => 'official']);
$this->postJson('/user/player/rename',[
$this->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => '角色名'
'new_player_name' => '角色名',
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Other invalid characters
option(['player_name_rule' => 'cjk']);
$this->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => '\\'
'new_player_name' => '\\',
], [
'X-Requested-With' => 'XMLHttpRequest'
'X-Requested-With' => 'XMLHttpRequest',
])->assertJson([
'errno' => 1,
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')])
'msg' => trans('validation.player_name', ['attribute' => trans('validation.attributes.player_name')]),
]);
// Use a duplicated player name
$name = factory(Player::class)->create()->player_name;
$this->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => $name
'new_player_name' => $name,
])->assertJson([
'errno' => 6,
'msg' => trans('user.player.rename.repeated')
'msg' => trans('user.player.rename.repeated'),
]);
// Success
$this->expectsEvents(Events\PlayerProfileUpdated::class);
$this->postJson('/user/player/rename', [
'pid' => $player->pid,
'new_player_name' => 'new_name'
'new_player_name' => 'new_name',
])->assertJson([
'errno' => 0,
'msg' => trans(
'user.player.rename.success',
['old' => $player->player_name, 'new' => 'new_name']
)
),
]);
}
@ -232,39 +230,39 @@ class PlayerControllerTest extends TestCase
$this->actAs($user)
->postJson('/user/player/set', [
'pid' => $player->pid,
'tid' => ['skin' => -1]
'tid' => ['skin' => -1],
])->assertJson([
'errno' => 6,
'msg' => trans('skinlib.un-existent')
'msg' => trans('skinlib.un-existent'),
]);
// Set for "skin" type
$this->postJson('/user/player/set', [
'pid' => $player->pid,
'tid' => ['skin' => $skin->tid]
'tid' => ['skin' => $skin->tid],
])->assertJson([
'errno' => 0,
'msg' => trans('user.player.set.success', ['name' => $player->player_name])
'msg' => trans('user.player.set.success', ['name' => $player->player_name]),
]);
$this->assertEquals($skin->tid, Player::find($player->pid)->tid_skin);
// Set for "cape" type
$this->postJson('/user/player/set', [
'pid' => $player->pid,
'tid' => ['cape' => $cape->tid]
'tid' => ['cape' => $cape->tid],
])->assertJson([
'errno' => 0,
'msg' => trans('user.player.set.success', ['name' => $player->player_name])
'msg' => trans('user.player.set.success', ['name' => $player->player_name]),
]);
$this->assertEquals($cape->tid, Player::find($player->pid)->tid_cape);
// Invalid texture type is acceptable
$this->postJson('/user/player/set', [
'pid' => $player->pid,
'tid' => ['nope' => $skin->tid] // TID must be valid
'tid' => ['nope' => $skin->tid], // TID must be valid
])->assertJson([
'errno' => 0,
'msg' => trans('user.player.set.success', ['name' => $player->player_name])
'msg' => trans('user.player.set.success', ['name' => $player->player_name]),
]);
}
@ -275,7 +273,7 @@ class PlayerControllerTest extends TestCase
$player->setTexture([
'tid_skin' => 1,
'tid_cape' => 2
'tid_cape' => 2,
]);
$player = Player::find($player->pid);
@ -288,7 +286,7 @@ class PlayerControllerTest extends TestCase
'nope' => 1, // Invalid texture type is acceptable
])->assertJson([
'errno' => 0,
'msg' => trans('user.player.clear.success', ['name' => $player->player_name])
'msg' => trans('user.player.clear.success', ['name' => $player->player_name]),
]);
$this->assertEquals(0, Player::find($player->pid)->tid_skin);
$this->assertEquals(0, Player::find($player->pid)->tid_cape);

View File

@ -2,12 +2,8 @@
namespace Tests;
use App\Events;
use ZipArchive;
use Illuminate\Support\Facades\File;
use Tests\Concerns\GeneratesFakePlugins;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PluginControllerTest extends TestCase
@ -55,72 +51,72 @@ class PluginControllerTest extends TestCase
$this->postJson('/admin/plugins/manage', ['name' => 'nope'])
->assertJson([
'errno' => 1,
'msg' => trans('admin.plugins.operations.not-found')
'msg' => trans('admin.plugins.operations.not-found'),
]);
// Invalid action
$this->postJson('/admin/plugins/manage', ['name' => 'fake-plugin-for-test'])
->assertJson([
'errno' => 1,
'msg' => trans('admin.invalid-action')
'msg' => trans('admin.invalid-action'),
]);
// Enable a plugin with unsatisfied dependencies
app('plugins')->getPlugin('fake-plugin-for-test')->setRequirements([
'blessing-skin-server' => '^3.4.0 || ^4.0.0',
'fake-plugin-with-config-view' => '^6.6.6',
'whatever' => '^1.0.0'
'whatever' => '^1.0.0',
]);
app('plugins')->enable('fake-plugin-with-config-view');
$this->postJson('/admin/plugins/manage', [
'name' => 'fake-plugin-for-test',
'action' => 'enable'
'action' => 'enable',
])->assertJson([
'errno' => 1,
'msg' => trans('admin.plugins.operations.unsatisfied.notice'),
'reason' => [
trans('admin.plugins.operations.unsatisfied.version', [
'name' => 'fake-plugin-with-config-view',
'constraint' => '^6.6.6'
'constraint' => '^6.6.6',
]),
trans('admin.plugins.operations.unsatisfied.disabled', [
'name' => 'whatever'
])
]
'name' => 'whatever',
]),
],
]);
// Enable a plugin
app('plugins')->getPlugin('fake-plugin-for-test')->setRequirements([]);
$this->postJson('/admin/plugins/manage', [
'name' => 'fake-plugin-for-test',
'action' => 'enable'
'action' => 'enable',
])->assertJson([
'errno' => 0,
'msg' => trans(
'admin.plugins.operations.enabled',
['plugin' => plugin('fake-plugin-for-test')->title]
)
),
]);
// Disable a plugin
$this->postJson('/admin/plugins/manage', [
'name' => 'fake-plugin-for-test',
'action' => 'disable'
'action' => 'disable',
])->assertJson([
'errno' => 0,
'msg' => trans(
'admin.plugins.operations.disabled',
['plugin' => plugin('fake-plugin-for-test')->title]
)
),
]);
// Delete a plugin
$this->postJson('/admin/plugins/manage', [
'name' => 'fake-plugin-for-test',
'action' => 'delete'
'action' => 'delete',
])->assertJson([
'errno' => 0,
'msg' => trans('admin.plugins.operations.deleted')
'msg' => trans('admin.plugins.operations.deleted'),
]);
$this->assertFalse(file_exists(base_path('plugins/fake-plugin-for-test/')));
}
@ -138,8 +134,8 @@ class PluginControllerTest extends TestCase
'url',
'enabled',
'config',
'dependencies'
]
'dependencies',
],
]);
}

View File

@ -15,7 +15,7 @@ class HookTest extends TestCase
Hook::addMenuItem('user', 0, [
'title' => 'Link A',
'link' => '/to/a',
'icon' => 'fa-book'
'icon' => 'fa-book',
]);
$this->actAs('normal')
->get('/user')
@ -27,7 +27,7 @@ class HookTest extends TestCase
Hook::addMenuItem('user', 10, [
'title' => 'Link B',
'link' => '/to/b',
'icon' => 'fa-book'
'icon' => 'fa-book',
]);
$this->actAs('normal')
->get('/user')

View File

@ -5,9 +5,6 @@ namespace Tests;
use App\Services\Minecraft;
use org\bovigo\vfs\vfsStream;
use App\Http\Controllers\TextureController;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class MinecraftTest extends TestCase
{

View File

@ -3,8 +3,6 @@
namespace Tests;
use App\Services\Repositories\OptionRepository;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class OptionRepositoryTest extends TestCase
@ -23,7 +21,7 @@ class OptionRepositoryTest extends TestCase
$repo = new OptionRepository();
$repo->set([
'k1' => 'v1',
'k2' => 'v2'
'k2' => 'v2',
]);
$this->assertEquals('v1', $repo->get('k1'));
$this->assertEquals('v2', $repo->get('k2'));
@ -39,7 +37,7 @@ class OptionRepositoryTest extends TestCase
]);
$this->assertArraySubset([
'k1' => 'v1',
'k2' => 'v2'
'k2' => 'v2',
], $repo->only(['k1', 'k2']));
}
}

View File

@ -3,9 +3,6 @@
namespace Tests;
use App\Services\Repositories\Repository;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class RepositoryTest extends TestCase
{
@ -34,7 +31,7 @@ class RepositoryTest extends TestCase
$repo->set([
'k2' => 'v2',
'k3' => 'v3'
'k3' => 'v3',
]);
$this->assertEquals('v2', $repo->get('k2'));
$this->assertEquals('v3', $repo->get('k3'));
@ -53,14 +50,14 @@ class RepositoryTest extends TestCase
$repo->set('k1', 'v1');
$repo->set([
'k2' => 'v2',
'k3' => 'v3'
'k3' => 'v3',
]);
$repo->push('a');
$this->assertArraySubset([
'k1' => 'v1',
'k2' => 'v2',
'k3' => 'v3',
0 => 'a'
0 => 'a',
], $repo->all());
}
@ -70,7 +67,8 @@ class RepositoryTest extends TestCase
$repo->set('k1', 'v1');
$this->assertEquals(
'v1',
$repo->remember('k1', function () {})
$repo->remember('k1', function () {
})
);
$this->assertEquals(
@ -90,7 +88,7 @@ class RepositoryTest extends TestCase
$repo->set([
'k2' => 'v2',
'k3' => 'v3'
'k3' => 'v3',
]);
$repo->forget(['k2', 'k3']);
$this->assertFalse($repo->has('k2'));

View File

@ -2,10 +2,7 @@
namespace Tests;
use App\Models\User;
use App\Services\Repositories\UserRepository;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserRepositoryTest extends TestCase

View File

@ -9,10 +9,8 @@ use Illuminate\Support\Str;
use AddVerificationToUsersTable;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class SetupControllerTest extends TestCase
@ -35,7 +33,7 @@ class SetupControllerTest extends TestCase
protected function dropAllTables()
{
$tables = [
'closets', 'migrations', 'options', 'players', 'textures', 'users'
'closets', 'migrations', 'options', 'players', 'textures', 'users',
];
array_walk($tables, function ($table) {
Schema::dropIfExists($table);
@ -60,8 +58,8 @@ class SetupControllerTest extends TestCase
'password' => env('DB_PASSWORD'),
'prefix' => '',
];
File::shouldReceive('get')->with('..' . DIRECTORY_SEPARATOR . '.env')->andReturn('');
File::shouldReceive('put')->with('..' . DIRECTORY_SEPARATOR . '.env', '');
File::shouldReceive('get')->with('..'.DIRECTORY_SEPARATOR.'.env')->andReturn('');
File::shouldReceive('put')->with('..'.DIRECTORY_SEPARATOR.'.env', '');
$this->post('/setup/database', $fake)->assertRedirect('/setup/info');
}
@ -70,7 +68,7 @@ class SetupControllerTest extends TestCase
$this->post('/setup/database', ['type' => 'sqlite', 'host' => 'placeholder', 'db' => 'test'])
->assertSee(trans('setup.database.connection-error', [
'type' => 'SQLite',
'msg' => 'Database (test) does not exist.'
'msg' => 'Database (test) does not exist.',
]));
}
@ -96,39 +94,39 @@ class SetupControllerTest extends TestCase
// Empty nickname
$this->post('/setup/finish', [
'email' => 'a@b.c'
'email' => 'a@b.c',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Invalid characters in nickname
$this->post('/setup/finish', [
'email' => 'a@b.c',
'nickname' => '\\'
'nickname' => '\\',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Too long nickname
$this->post('/setup/finish', [
'email' => 'a@b.c',
'nickname' => Str::random(256)
'nickname' => Str::random(256),
])->assertDontSee(trans('setup.wizard.finish.title'));
// Without `password` field
$this->post('/setup/finish', [
'email' => 'a@b.c',
'nickname' => 'nickname'
'nickname' => 'nickname',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Password is too short
$this->post('/setup/finish', [
'email' => 'a@b.c',
'nickname' => 'nickname',
'password' => '1'
'password' => '1',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Password is too long
$this->post('/setup/finish', [
'email' => 'a@b.c',
'nickname' => 'nickname',
'password' => Str::random(17)
'password' => Str::random(17),
])->assertDontSee(trans('setup.wizard.finish.title'));
// Confirmation is not OK
@ -136,7 +134,7 @@ class SetupControllerTest extends TestCase
'email' => 'a@b.c',
'nickname' => 'nickname',
'password' => '12345678',
'password_confirmation' => '12345679'
'password_confirmation' => '12345679',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Without `site_name` field
@ -144,7 +142,7 @@ class SetupControllerTest extends TestCase
'email' => 'a@b.c',
'nickname' => 'nickname',
'password' => '12345678',
'password_confirmation' => '12345678'
'password_confirmation' => '12345678',
])->assertDontSee(trans('setup.wizard.finish.title'));
// Regenerate keys
@ -172,7 +170,7 @@ class SetupControllerTest extends TestCase
'password' => '12345678',
'password_confirmation' => '12345678',
'site_name' => 'bs',
'generate_random' => true
'generate_random' => true,
])->assertSee(trans('setup.wizard.finish.title'))
->assertSee('a@b.c')
->assertSee('12345678');

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