Advertisement
sami-jnih

[Class] TypeHint

May 11th, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.14 KB | None | 0 0
  1. <?php
  2.  
  3. define('TYPEHINT_PCRE', '/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/');
  4.  
  5. class Typehint
  6. {
  7.  
  8.     private static $Typehints = array(
  9.         'Bool'  => 'is_bool',
  10.         'Int'  => 'is_int',
  11.         'Float'    => 'is_float',
  12.         'String'   => 'is_string',
  13.         'Resource' => 'is_resource'
  14.     );
  15.  
  16.     private function __construct() {}
  17.  
  18.     public static function initializeHandler()
  19.     {
  20.         set_error_handler('Typehint::handleTypehint');
  21.  
  22.         return true;
  23.     }
  24.  
  25.     private static function getTypehintedArgument($ThBackTrace, $ThFunction, $ThArgIndex, &$ThArgValue)
  26.     {
  27.         foreach ($ThBackTrace as $ThTrace)
  28.         {
  29.             // Match the function; Note we could do more defensive error checking.
  30.             if (isset($ThTrace['function']) && $ThTrace['function'] == $ThFunction) {
  31.                 $ThArgValue = $ThTrace['args'][$ThArgIndex - 1];
  32.  
  33.                 return true;
  34.             }
  35.         }
  36.  
  37.         return false;
  38.     }
  39.  
  40.     public static function handleTypehint($ErrLevel, $ErrMessage)
  41.     {
  42.         if ($ErrLevel == E_RECOVERABLE_ERROR) {
  43.             if (preg_match(TYPEHINT_PCRE, $ErrMessage, $ErrMatches)) {
  44.                 list($ErrMatch, $ThArgIndex, $ThClass, $ThFunction, $ThHint, $ThType) = $ErrMatches;
  45.  
  46.                 if (isset(self::$Typehints[$ThHint])) {
  47.                     $ThBacktrace = debug_backtrace();
  48.                     $ThArgValue  = NULL;
  49.  
  50.                     if (self::getTypehintedArgument($ThBacktrace, $ThFunction, $ThArgIndex, $ThArgValue)) {
  51.                         if (call_user_func(self::$Typehints[$ThHint], $ThArgValue)) {
  52.                             return true;
  53.                         }
  54.                     }
  55.                 }
  56.             }
  57.         }
  58.  
  59.         return false;
  60.     }
  61. }
  62.  
  63. Typehint::initializeHandler();
  64.  
  65. ?>
  66.  
  67. An are some examples of the class in use:
  68.  
  69. <?php
  70.  
  71. function teststring(String $string) { echo $string; }
  72. function testinteger(Int $integer) { echo $integer; }
  73. function testfloat(Float $float) { echo $float; }
  74.  
  75. // This will work for class methods as well.
  76.  
  77. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement