Home > Back-end >  PHP- combining two params within match() expression to be set dynamically
PHP- combining two params within match() expression to be set dynamically

Time:10-21

I am trying to set two parameters within my PHP project. One is sortBy and second is orderBy..

I am trying to define the best logic for it using match() expression, available from PHP 8.0 version.

   $orderBy = $params['order'] ?? 'DESC';

   if (!preg_match('[ASC|DESC]', strtoupper($orderBy))) {
        throw new Exception("Invalid Value for Order $orderBy allowed option ASC, DESC", 400);
    }

    $sortBy = match($params['sort']) {
        'createdAt' => 'user.created_at',
        'firstName' => 'user.first_name',
        'lastName'  => 'user.last_name',
        'username'  => 'user.username',
         default    => 'user.rank',
    };

My code works as expected as I first wanted to set default DESC but then figured out that will not be the best approach and I ran out of ides of how can I have $params['order'] default to DESC in just two cases, on createdAt and rank and for others, logically, I want them on ASC but STILL to be able to set them dynamically.

I wanted to add another match() for orderBy but I guess I can maybe implement this logic in the already defined match so I do not need to write second one.

Does someone have better idea? Thanks

CodePudding user response:

Put the default order that depends on the sortBy in another variable, and use that when setting $orderBy.

$defaultOrder = match($params['sort']) {
    'createdAt', 'rank' => 'DESC',
    default => 'ASC'
};

$orderBy = $params['order'] ?? $defaultOrder;
  • Related