PHP code example of timacdonald / has-parameters

1. Go to this page and download the library: Download timacdonald/has-parameters library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

timacdonald / has-parameters example snippets




class ThrottleRequests
{
    use HasParameters;

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
    {
        //
    }
}



Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'maxAttempts' => 120,
        ]),
    ]);



// before...
Route::stuff()
    ->middleware([
        'throttle:10,1' // what does 10 or 1 stand for here?
    ]);

// after...
Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'decayMinutes' => 1,
            'maxAttempts' => 10,
        ]),
    ]);



Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'prefix' => 'admins',
        ]),
    ]);



public function handle(Request $request, Closure $next, string $ability, string ...$models)



Route::stuff()
    ->middleware([
        Authorize::with([
            'ability' => PostVideoPolicy::UPDATE,
            'models' => [Post::class, Video::class],
        ]),
    ]);



// a named rate limiter...

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});

// using the rate limiter WITHOUT an alias...

Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'maxAttempts' => 'api',
        ]),
    ]);



Route::stuff()
    ->middleware([
        ThrottleRequests::with([
            'limiter' => 'api',
        ]),
    ]);



class ThrottleRequests
{
    use HasParameters;

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
    {
        //
    }

    protected static function parameterAliasMap(): array
    {
        return [
            'limiter' => 'maxAttempts',
            // 'alias' => 'parameter',
        ];
    }
}



public function handle(Request $request, Closure $next, string ...$states)
{
    //
}



Route::stuff()
    ->middleware([
        EnsurePostState::in([PostState::DRAFT, PostState::UNDER_REVIEW]),
    ]);

/**
 * @method static string with(array{
 *     maxAttempts?: int,
 *     decayMinutes?: float|int,
 *     prefix?: string,
 * }|'admin' $arguments)
 */
class ThrottleMiddleware
{
    use HasParameters;

    // ...
}

ThrottleMiddleware::with('admin');
// ✅

ThrottleMiddleware::with(['decayMinutes' => 10]);
// ✅

ThrottleMiddleware::with('foo');
// ❌ fails because 'foo' is not in the allowed string values

ThrottleMiddleware::with(['maxAttempts' => 'ten']);
// ❌ fails because `maxAttempts` must be an int