Esempio n. 1
0
File: type.php Progetto: amekusa/plz
 /**
  * Returns whether the type of `$X` matches a specific type
  * @example Demonstration
  * ```php
  * $var = '123';
  * var_dump( type::matches($var, 'boolean') );
  * var_dump( type::matches($var, 'bool')    ); // Shorten name
  * echo "\n";
  * var_dump( type::matches($var, 'integer') );
  * var_dump( type::matches($var, 'int')     ); // Shorten name
  * echo "\n";
  * var_dump( type::matches($var, 'string')  );
  * var_dump( type::matches($var, 'str')     ); // Shorten name
  * echo "\n";
  * var_dump( type::matches($var, 'array')   );
  * var_dump( type::matches($var, 'arr')     ); // Shorten name
  * ```
  * @example Pseudo type matching
  * ```php
  * $var1 = '123';
  * var_dump( type::matches($var1, 'numeric') );
  * echo "\n";
  * $var2 = array (1, 2, 3);
  * var_dump( type::matches($var2, 'scalar') );
  * var_dump( type::matches($var2, 'vector') );
  * echo "\n";
  * $var3 = function () { };
  * var_dump( type::matches($var3, 'callable') );
  * ```
  * @example Class matching
  * ```php
  * class Cat { }
  * class Dog { }
  * class Collie extends Dog { }
  *
  * $dog = new Collie();
  * var_dump( type::matches($dog, 'Collie') ); // Matches
  * var_dump( type::matches($dog, 'Dog')    ); // Also matches with super-class
  * var_dump( type::matches($dog, 'Cat')    ); // Never matches
  * ```
  * @param mixed $X A variable to check type
  * @param integer|string $Type A type expression
  * @return boolean
  */
 static function matches($X, $Type)
 {
     switch (is_int($Type) ? $Type : T::enum($Type)) {
         case T::BOOL:
             return is_bool($X);
         case T::INT:
             return is_int($X);
         case T::FLOAT:
             return is_float($X);
         case T::STR:
             return is_string($X);
         case T::ARR:
             return is_array($X);
         case T::OBJ:
             return is_object($X);
         case T::RES:
             return is_resource($X);
         case T::UNKNOWN:
             if (!is_string($Type)) {
                 return false;
             }
             switch ($Type) {
                 case 'mixed':
                     return true;
                 case 'numeric':
                     return is_numeric($X);
                 case 'callable':
                     return is_callable($X);
                 case 'scalar':
                     return is_scalar($X);
                 case 'vector':
                     return !is_scalar($X);
                 default:
                     if (is_object($X)) {
                         // Assumes class name
                         if (is_a($X, $Type)) {
                             return true;
                         }
                     }
                     if (gettype($X) == $Type) {
                         return true;
                     }
             }
     }
     return false;
 }