Upgrade to Laravel 10

This commit is contained in:
Jonny Barnes 2023-02-18 09:34:57 +00:00
commit 16b120bc73
Signed by: jonny
SSH key fingerprint: SHA256:CTuSlns5U7qlD9jqHvtnVmfYV3Zwl2Z7WnJ4/dqOaL8
72 changed files with 1676 additions and 2019 deletions

View file

@ -25,22 +25,10 @@ class MigratePlaceDataFromPostgis extends Command
*/
protected $description = 'Copy Postgis data to normal latitude longitude fields';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
public function handle(): int
{
$locationColumn = DB::selectOne(DB::raw("
SELECT EXISTS (

View file

@ -6,6 +6,7 @@ namespace App\Console\Commands;
use App\Models\WebMention;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\FileSystem\FileSystem;
class ParseCachedWebMentions extends Command
@ -27,9 +28,9 @@ class ParseCachedWebMentions extends Command
/**
* Execute the console command.
*
* @return mixed
* @throws FileNotFoundException
*/
public function handle(FileSystem $filesystem)
public function handle(FileSystem $filesystem): void
{
$htmlFiles = $filesystem->allFiles(storage_path() . '/HTML');
foreach ($htmlFiles as $file) {
@ -49,8 +50,6 @@ class ParseCachedWebMentions extends Command
/**
* Determine the source URL from a filename.
*
* @param string
*/
private function urlFromFilename(string $filepath): string
{

View file

@ -24,22 +24,10 @@ class ReDownloadWebMentions extends Command
*/
protected $description = 'Redownload the HTML content of webmentions';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
public function handle(): void
{
$webmentions = WebMention::all();
foreach ($webmentions as $webmention) {

View file

@ -10,7 +10,7 @@ class Kernel extends ConsoleKernel
/**
* The Artisan commands provided by your application.
*
* @var array
* @var array<int, string>
*/
protected $commands = [
Commands\ParseCachedWebMentions::class,
@ -20,11 +20,9 @@ class Kernel extends ConsoleKernel
/**
* Define the application's command schedule.
*
* @return void
*
* @codeCoverageIgnore
*/
protected function schedule(Schedule $schedule)
protected function schedule(Schedule $schedule): void
{
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->command('cache:prune-stale-tags')->hourly();
@ -32,10 +30,8 @@ class Kernel extends ConsoleKernel
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
protected function commands(): void
{
$this->load(__DIR__ . '/Commands');

View file

@ -21,46 +21,34 @@ class Handler extends ExceptionHandler
/**
* A list of the exception types that are not reported.
*
* @var array
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
NotFoundHttpException::class,
ModelNotFoundException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @return void
*
* @throws Exception
* @throws Throwable
*/
public function report(Throwable $throwable)
public function report(Throwable $e): void
{
parent::report($throwable);
parent::report($e);
if (config('logging.slack') && $this->shouldReport($throwable)) {
if (config('logging.slack') && $this->shouldReport($e)) {
$guzzle = new Client([
'headers' => [
'Content-Type' => 'application/json',
],
]);
$exceptionName = get_class($throwable) ?? 'Unknown Exception';
$title = $exceptionName . ': ' . $throwable->getMessage();
$exceptionName = get_class($e) ?? 'Unknown Exception';
$title = $exceptionName . ': ' . $e->getMessage();
$guzzle->post(
config('logging.slack'),

View file

@ -27,10 +27,8 @@ class ArticlesController extends Controller
/**
* Show a single article.
*
* @return RedirectResponse|View
*/
public function show(int $year, int $month, string $slug)
public function show(int $year, int $month, string $slug): RedirectResponse|View
{
try {
$article = Article::where('titleurl', $slug)->firstOrFail();
@ -49,8 +47,7 @@ class ArticlesController extends Controller
}
/**
* We only have the ID, work out post title, year and month
* and redirect to it.
* We only have the ID, work out post title, year and month and redirect to it.
*/
public function onlyIdInUrl(string $idFromUrl): RedirectResponse
{

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
@ -12,10 +13,8 @@ class AuthController extends Controller
{
/**
* Show the login form.
*
* @return View|RedirectResponse
*/
public function showLogin()
public function showLogin(): View|RedirectResponse
{
if (Auth::check()) {
return redirect('/');
@ -25,12 +24,11 @@ class AuthController extends Controller
}
/**
* Log in a user, set a session variable, check credentials against
* the .env file.
* Log in a user, set a session variable, check credentials against the `.env` file.
*/
public function login(): RedirectResponse
public function login(Request $request): RedirectResponse
{
$credentials = request()->only('name', 'password');
$credentials = $request->only('name', 'password');
if (Auth::attempt($credentials, true)) {
return redirect()->intended('/');
@ -40,11 +38,9 @@ class AuthController extends Controller
}
/**
* Show the form to logout a user.
*
* @return View|RedirectResponse
* Show the form to allow a user to log-out.
*/
public function showLogout()
public function showLogout(): View|RedirectResponse
{
if (Auth::check() === false) {
// The user is not logged in, just redirect them home
@ -56,8 +52,6 @@ class AuthController extends Controller
/**
* Log the user out from their current session.
*
* @return RedirectResponse;
*/
public function logout(): RedirectResponse
{

View file

@ -96,10 +96,8 @@ class FeedsController extends Controller
/**
* Returns the notes JSON feed.
*
* @return array
*/
public function notesJson()
public function notesJson(): array
{
$notes = Note::latest()->with('media')->take(20)->get();
$data = [

View file

@ -7,6 +7,7 @@ use App\Models\Bookmark;
use App\Models\Like;
use App\Models\Note;
use App\Services\ActivityStreamsService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
@ -14,12 +15,10 @@ class FrontPageController extends Controller
{
/**
* Show all the recent activity.
*
* @return Response|View
*/
public function index()
public function index(Request $request): Response|View
{
if (request()->wantsActivityStream()) {
if ($request->wantsActivityStream()) {
return (new ActivityStreamsService())->siteOwnerResponse();
}

View file

@ -115,34 +115,34 @@ class MicropubController extends Controller
* appropriately. Further if the request has the query parameter
* syndicate-to we respond with the known syndication endpoints.
*/
public function get(): JsonResponse
public function get(Request $request): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
$tokenData = $this->tokenService->validateToken($request->input('access_token'));
} catch (RequiredConstraintsViolated|InvalidTokenStructure) {
return (new MicropubResponses())->invalidTokenResponse();
}
if (request()->input('q') === 'syndicate-to') {
if ($request->input('q') === 'syndicate-to') {
return response()->json([
'syndicate-to' => SyndicationTarget::all(),
]);
}
if (request()->input('q') === 'config') {
if ($request->input('q') === 'config') {
return response()->json([
'syndicate-to' => SyndicationTarget::all(),
'media-endpoint' => route('media-endpoint'),
]);
}
if (request()->has('q') && substr(request()->input('q'), 0, 4) === 'geo:') {
if ($request->has('q') && str_starts_with($request->input('q'), 'geo:')) {
preg_match_all(
'/([0-9.\-]+)/',
request()->input('q'),
$request->input('q'),
$matches
);
$distance = (count($matches[0]) == 3) ? 100 * $matches[0][2] : 1000;
$distance = (count($matches[0]) === 3) ? 100 * $matches[0][2] : 1000;
$places = Place::near(
(object) ['latitude' => $matches[0][0], 'longitude' => $matches[0][1]],
$distance
@ -168,22 +168,19 @@ class MicropubController extends Controller
/**
* Determine the client id from the access token sent with the request.
*
*
* @throws RequiredConstraintsViolated
*/
private function getClientId(): string
{
return resolve(TokenService::class)
->validateToken(request()->input('access_token'))
->validateToken(app('request')->input('access_token'))
->claims()->get('client_id');
}
/**
* Save the details of the micropub request to a log file.
*
* @param array $request This is the info from request()->all()
*/
private function logMicropubRequest(array $request)
private function logMicropubRequest(array $request): void
{
$logger = new Logger('micropub');
$logger->pushHandler(new StreamHandler(storage_path('logs/micropub.log')));

View file

@ -98,14 +98,13 @@ class MicropubMediaController extends Controller
/**
* Process a media item posted to the media endpoint.
*
*
* @throws BindingResolutionException
* @throws Exception
*/
public function media(): JsonResponse
public function media(Request $request): JsonResponse
{
try {
$tokenData = $this->tokenService->validateToken(request()->input('access_token'));
$tokenData = $this->tokenService->validateToken($request->input('access_token'));
} catch (RequiredConstraintsViolated|InvalidTokenStructure $exception) {
$micropubResponses = new MicropubResponses();
@ -124,7 +123,7 @@ class MicropubMediaController extends Controller
return $micropubResponses->insufficientScopeResponse();
}
if (request()->hasFile('file') === false) {
if ($request->hasFile('file') === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
@ -132,7 +131,7 @@ class MicropubMediaController extends Controller
], 400);
}
if (request()->file('file')->isValid() === false) {
if ($request->file('file')->isValid() === false) {
return response()->json([
'response' => 'error',
'error' => 'invalid_request',
@ -140,11 +139,11 @@ class MicropubMediaController extends Controller
], 400);
}
$filename = $this->saveFile(request()->file('file'));
$filename = $this->saveFile($request->file('file'));
$manager = resolve(ImageManager::class);
try {
$image = $manager->make(request()->file('file'));
$image = $manager->make($request->file('file'));
$width = $image->width();
} catch (NotReadableException $exception) {
// not an image
@ -152,9 +151,9 @@ class MicropubMediaController extends Controller
}
$media = Media::create([
'token' => request()->bearerToken(),
'token' => $request->bearerToken(),
'path' => 'media/' . $filename,
'type' => $this->getFileTypeFromMimeType(request()->file('file')->getMimeType()),
'type' => $this->getFileTypeFromMimeType($request->file('file')->getMimeType()),
'image_widths' => $width,
]);
@ -226,7 +225,6 @@ class MicropubMediaController extends Controller
/**
* Save an uploaded file to the local disk.
*
*
* @throws Exception
*/
private function saveFile(UploadedFile $file): string

View file

@ -9,6 +9,7 @@ use App\Services\ActivityStreamsService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
use Jonnybarnes\IndieWeb\Numbers;
@ -19,12 +20,10 @@ class NotesController extends Controller
{
/**
* Show all the notes. This is also the homepage.
*
* @return View|Response
*/
public function index()
public function index(Request $request): View|Response
{
if (request()->wantsActivityStream()) {
if ($request->wantsActivityStream()) {
return (new ActivityStreamsService())->siteOwnerResponse();
}
@ -39,11 +38,8 @@ class NotesController extends Controller
/**
* Show a single note.
*
* @param string $urlId The id of the note
* @return View|JsonResponse|Response
*/
public function show(string $urlId)
public function show(string $urlId): View|JsonResponse|Response
{
try {
$note = Note::nb60($urlId)->with('webmentions')->firstOrFail();
@ -60,8 +56,6 @@ class NotesController extends Controller
/**
* Redirect /note/{decID} to /notes/{nb60id}.
*
* @param int $decId The decimal id of the note
*/
public function redirect(int $decId): RedirectResponse
{

View file

@ -35,17 +35,15 @@ class ShortURLsController extends Controller
/**
* Redirect a short url of this site out to a long one based on post type.
* Further redirects may happen.
*
* @param string Post type
* @param string Post ID
* Further redirects may happen.
*/
public function expandType(string $type, string $postId): RedirectResponse
{
if ($type == 't') {
if ($type === 't') {
$type = 'notes';
}
if ($type == 'b') {
if ($type === 'b') {
$type = 'blog/s';
}

View file

@ -24,9 +24,6 @@ class TokenEndpointController extends Controller
*/
protected GuzzleClient $guzzle;
/**
* @var TokenService The Token handling service.
*/
protected TokenService $tokenService;
/**

View file

@ -7,6 +7,7 @@ namespace App\Http\Controllers;
use App\Jobs\ProcessWebMention;
use App\Models\Note;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
use Jonnybarnes\IndieWeb\Numbers;
@ -27,10 +28,10 @@ class WebMentionsController extends Controller
/**
* Receive and process a webmention.
*/
public function receive(): Response
public function receive(Request $request): Response
{
//first we trivially reject requests that lack all required inputs
if ((request()->has('target') !== true) || (request()->has('source') !== true)) {
if (($request->has('target') !== true) || ($request->has('source') !== true)) {
return response(
'You need both the target and source parameters',
400
@ -38,15 +39,15 @@ class WebMentionsController extends Controller
}
//next check the $target is valid
$path = parse_url(request()->input('target'), PHP_URL_PATH);
$path = parse_url($request->input('target'), PHP_URL_PATH);
$pathParts = explode('/', $path);
if ($pathParts[1] == 'notes') {
if ($pathParts[1] === 'notes') {
//we have a note
$noteId = $pathParts[2];
try {
$note = Note::findOrFail(resolve(Numbers::class)->b60tonum($noteId));
dispatch(new ProcessWebMention($note, request()->input('source')));
dispatch(new ProcessWebMention($note, $request->input('source')));
} catch (ModelNotFoundException $e) {
return response('This note doesn’t exist.', 400);
}
@ -56,7 +57,7 @@ class WebMentionsController extends Controller
202
);
}
if ($pathParts[1] == 'blog') {
if ($pathParts[1] === 'blog') {
return response(
'I don’t accept webmentions for blog posts yet.',
501

View file

@ -11,7 +11,7 @@ class Kernel extends HttpKernel
*
* These middleware are run during every request to your application.
*
* @var array
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
@ -26,7 +26,7 @@ class Kernel extends HttpKernel
/**
* The application's route middleware groups.
*
* @var array
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
@ -44,21 +44,23 @@ class Kernel extends HttpKernel
],
'api' => [
'throttle:api',
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
* The application's middleware aliases.
*
* These middleware may be assigned to groups or used individually.
* Aliases may be used to conveniently assign middleware to routes and groups.
*
* @var array
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

View file

@ -6,15 +6,14 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ActivityStreamLinks
{
/**
* Handle an incoming request.
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
if ($request->path() === '/') {

View file

@ -3,6 +3,7 @@
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
/**
* @codeCoverageIgnore
@ -11,14 +12,9 @@ class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
protected function redirectTo(Request $request): ?string
{
if (! $request->expectsJson()) {
return route('login');
}
return $request->expectsJson() ? null : route('login');
}
}

View file

@ -5,16 +5,14 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;
class CSPHeader
{
/**
* Handle an incoming request.
*
* @param Request $request
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next): Response
{
if (App::environment('local', 'development')) {
return $next($request);

View file

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

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