PHP code example of solventt / slim-route-strategy

1. Go to this page and download the library: Download solventt/slim-route-strategy 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/ */

    

solventt / slim-route-strategy example snippets


$app->get('/profile/{id:\d+}', [ProfileController::class, 'show']);

...

public function show(int $id): Response
{
   // incoming $id has integer type instead of default's string
}

public function show($request, $response, $id) {}

[
   'request' => 'value_1', 
   'response' => 'value_2', 
   'id' = '1'
]

public function show($request, $response, $id)
{
  echo $request;   // 'value_1'
  echo $response;  // 'value_2'
  echo $id;        // '1' - string, because the IdIntegerTypeRule is off
}

public function show(Twig $twig, self $surrentClass) 
{
   // The Twig and declaring class instances will be automatically resolved
}

public function show(?string $name, ?int $count = 5) 
{
   var_dump($name);   // null
   echo $count;       // 5
}

public function update(Dto $dto, int $id)
{
   // do something with $dto
}

return [
    'dtoFactories' => [
         
         // key - is a parameter name of a controller method
         // value - a corresponding DTO factory class
         
         'dto' => UserUpdateDtoFactory::class 
    ]
];

class UserUpdateDtoFactory
{
   public function __invoke(array $requestData): UserUpdateDto
   {
      $dto = new UserUpdateDto();

      foreach ($requestData as $field => $value) {

         $value = match ($field) {
                'phoneType' => (int) $value,
                'date' => new \DateTime($value),
                'isActive' => (bool) $value,
                 default => $value
            };

         $dto->$field = $value;
      }
      
      return $dto;
   }
}

public function update(UserUpdateDto $dto)
{
   // do something with $dto
}



use DI\Container;
use Slim\Factory\AppFactory;
use SlimRouteStrategy\CustomRulesAggregator;

w CustomRulesAggregator($container);

$app->getRouteCollector()->setDefaultInvocationStrategy($strategy);

$app->get('/hello/{name}', function ($response, $name) {
    $response->getBody()->write($name);

    return $response;
});

$app->run();



use Slim\App;
use Slim\Container;
use SlimRouteStrategy\CustomRulesAggregator;

ggregator($container);

$app = new App($container);

$app->get('/hello/{name}', function ($response, $name) {
    $response->getBody()->write($name);

    return $response;
});

$app->run();

...

$strategyRules = [

    IdIntegerTypeRule::class,
    FlexibleSignatureRule::class,
    MakeDtoRule::class,
    TypeHintContainerRule::class,
    NullTypeRule::class
    
];

$strategy = new CustomRulesAggregator($container, $strategyRules);

...

...

$strategy = new CustomRulesAggregator($container, [FlexibleSignatureRule::class]);

...

$app->get('/profile/{user:\d+}', [ProfileController::class, 'show']);

public function show(User $user){}

class FindUserEntityRule implements AggregatorRuleInterface
{
    public function __construct(private UserRepository $users){}

    /**
     * @param ReflectionParameter[]  $unresolvedParams parameters that have not yet been resolved
     * @param array $routeParams     request/response objects, route placeholders values, request attributes
     * @param array $resolvedParams  parameters resolved by previous rule (indexed by parameter position)
     * @return array                 parameters resolved by this + by previous rule
     */
    public function resolveParameters(array $unresolvedParams,
                                      array $routeParams,
                                      array $resolvedParams): array
    {
        foreach ($unresolvedParams as $position => $parameter) {

            if ($parameter->name === 'user' && $this->hasAppropriateType($parameter)) {
                if (array_key_exists($parameter->name, $routeParams)) {

                    $userId = (int) $routeParams[$parameter->name];
                    $user = $this->users->findOne($userId);

                    $resolvedParams[$position] = $user;
                }
            }
        }

        return $resolvedParams;
    }

    private function hasAppropriateType(ReflectionParameter $parameter): bool
    {
        $type = $parameter->getType();

        return !$type instanceof ReflectionUnionType && $type->getName() === User::class;
    }
}

// php 7.4+
composer r 
$response
$id
$id
index.php
index.php