1<?php 2 3namespace LesserPHP\Utils; 4 5use Exception; 6 7class Asserts 8{ 9 /** 10 * Check that the number of arguments is correct and return them 11 * 12 * @throws Exception 13 */ 14 public static function assertArgs($value, $expectedArgs, $name = '') 15 { 16 if ($expectedArgs == 1) { 17 return $value; 18 } else { 19 if ($value[0] !== 'list' || $value[1] != ',') { 20 throw new Exception('expecting list'); 21 } 22 $values = $value[2]; 23 $numValues = count($values); 24 if ($expectedArgs != $numValues) { 25 if ($name) { 26 $name = $name . ': '; 27 } 28 29 throw new Exception("{$name}expecting $expectedArgs arguments, got $numValues"); 30 } 31 32 return $values; 33 } 34 } 35 36 /** 37 * Check that the number of arguments is at least the expected number and return them 38 * 39 * @throws Exception 40 */ 41 public static function assertMinArgs($value, $expectedMinArgs, $name = '') 42 { 43 if ($value[0] !== 'list' || $value[1] != ',') { 44 throw new Exception('expecting list'); 45 } 46 $values = $value[2]; 47 $numValues = count($values); 48 if ($expectedMinArgs > $numValues) { 49 if ($name) { 50 $name = $name . ': '; 51 } 52 53 throw new Exception("${name}expecting at least $expectedMinArgs arguments, got $numValues"); 54 } 55 56 return $values; 57 } 58 59 /** 60 * Checks that the value is a number and returns it as float 61 * 62 * @param array $value The parsed value triplet 63 * @param string $error The error message to throw 64 * @throws Exception 65 */ 66 public static function assertNumber(array $value, string $error = 'expecting number'): float 67 { 68 if ($value[0] == 'number') return (float)$value[1]; 69 throw new Exception($error); 70 } 71 72 /** 73 * @throws Exception 74 */ 75 public static function assertColor(array $value, $error = 'expected color value'): array 76 { 77 $color = Color::coerceColor($value); 78 if (is_null($color)) throw new Exception($error); 79 return $color; 80 } 81} 82