Advertisement
Guest User

CarListSorter

a guest
May 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | None | 0 0
  1. class CarListSorter
  2. {
  3.     public const DIRECTION_ASC = 'ASC';
  4.     public const DIRECTION_DESC = 'DESC';
  5.  
  6.     private static $properties = [
  7.         'brandName', 'modelName', 'auctionName', 'auctionDateTime', 'transmissionType', 'gearType', 'year',
  8.         'enginePowerHp', 'mileageKm', 'color', 'lot', 'bodyModel', 'rate', 'startPriceJpy', 'finishPriceJpy',
  9.         'avgPriceJpy'
  10.     ];
  11.  
  12.     private $sorting = [];
  13.  
  14.     public function __isset($name)
  15.     {
  16.         if (!in_array($name, self::$properties))
  17.             throw new LogicException("Property '{$name}' is not available for list sorting");
  18.  
  19.         return isset($this->sorting[$name]);
  20.     }
  21.  
  22.     public function __set($name, ?string $value = null)
  23.     {
  24.         // todo: valid options in message
  25.         if ($value !== null && !in_array($value, [self::DIRECTION_ASC, self::DIRECTION_DESC], true))
  26.             throw new LogicException("Sorting value '{$value}' is incorrect.");
  27.  
  28.         if (!in_array($name, $this->sorting) && $value !== null)
  29.             $this->sorting[$name] = $value;
  30.         if ($value === null)
  31.             unset($this->sorting[$name]);
  32.     }
  33.  
  34.     public function __get($name)
  35.     {
  36.         if (!in_array($name, self::$properties))
  37.             throw new LogicException("Property '{$name}' is not available for list sorting");
  38.  
  39.         return $this->sorting[$name] ?? null;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement