Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

PHP Source Code


Welcome to Dream.In.Code
Become a PHP Expert!

Join 244,258 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 1,284 people online right now. Registration is fast and FREE... Join Now!





Strict_args (v0.2)

A class to provide rudimentary strongly typed arguments for functions and class methods in the PHP language.

Submitted By: snoj
Actions:
Rating:
Views: 634

Language: PHP

Last Modified: December 31, 1969
Instructions: See test1() and test2() at the end for examples on the basics of how to use. Also, reading the PHPDoc styled comments should be of help. You can find a "live" version here.

Snippet


  1. <?php
  2. /*
  3.     Copyright (C) 2007  Josh Erickson <josh @ josherickson.org>
  4.     This program is free software; you can redistribute it and/or modify
  5.     it under the terms of the GNU General Public License as published by
  6.     the Free Software Foundation; either version 2 of the License, or
  7.     (at your option) any later version.
  8.     This program is distributed in the hope that it will be useful,
  9.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.     GNU General Public License for more details.
  12.     You should have received a copy of the GNU General Public License
  13.     along with this program; if not, write to the Free Software
  14.     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  15. */
  16.  
  17. /*
  18. * Version 0.1:
  19. *         First version.
  20. *
  21. * Version 0.2:
  22. *         -Fixed issue with specifying $type as 'any' which would result in a "Unknown Error".
  23. */
  24.  
  25. /**
  26. * A class to provide rudimentary strongly typed arguments for functions and class methods.
  27. */
  28. class strict_args {
  29.         /**
  30.         * This holds the function and arguments for the functions we're working with.
  31.         *
  32.         * @static
  33.         * @name $funcs
  34.         * @access private
  35.         */
  36.         private static $funcs = array();
  37.        
  38.         /**
  39.         * This holds the last error.
  40.         *
  41.         * @static       
  42.         * @name $lastError
  43.         * @access private
  44.         */
  45.         private static $lastError = null;
  46.        
  47.         /**
  48.         * Add an argument you wish to have parsed.
  49.         *
  50.         * Only supplied arguments will be returned after parsing is done. False on error. Check strict_args::lastError() for details.
  51.         *
  52.         * @static
  53.         * @name add
  54.         * $param string $function The name of the function this argument will apply to.
  55.         * $param string|int $argument The argument name that will be used.
  56.         * $param string $type The type of variable it is suppose to be. 'any' is default. See http://us.php.net/manual/en/language.types.php for valid types.
  57.         * $param mixed $default The default value of the argument if none is given. Default value is NULL.
  58.         * $param bool $require Whether or not the argument is require. If false, default value is given. Default value is FALSE.
  59.         * $param bool $strict Whether or not the supplied argument is suppose to be of a specific type or not. Default value is FALSE.
  60.         * @return bool Always returns true.
  61.         * @access public
  62.         */
  63.         public static function add($function,$arg,$type='any',$default=null,$require=false,$strict=false) {
  64.                 //$hash = md5($name,$type,$default,$require,$strict);
  65.                 //self::$funcs[$hash] = array($name,$type,$default,$require,$strict);
  66.                 self::$funcs[$function][$arg] = array($type,$default,$require,$strict);
  67.                 return true;
  68.         }
  69.        
  70.         /**
  71.         * Get the last error, if there be one
  72.         *
  73.         * Returns the last error if there is one or false if there are none.
  74.         *
  75.         * @static
  76.         * @return mixed
  77.         */
  78.         public static function lastError() {
  79.                 if(self::$lastError===null) {
  80.                         return false;
  81.                 } else {
  82.                         return self::$lastError;
  83.                 }
  84.                 return false;
  85.         }
  86.         /**
  87.         * Checks whether or not the functions supplied arguments are valid or not based on provided criteria.
  88.         *
  89.         * <p>Returns an array of values if they all match up to supplied parameters for them. However if
  90.         * $onlyReturnBool is set to TRUE, it will only return a boolean as to whether or the check
  91.         * succeeds.</p>
  92.         * <p>The $arguments parameter must contain keys that align to the argument names provided to
  93.         * strict_args::add().</p>
  94.         *
  95.         * @static
  96.         * @param string $function The name of the function that will be checked.
  97.         * @param array $arguments The arguments that are to be checked.
  98.         * @param bool $onlyReturnBool If set to true, will only return a boolean value to whether or not it succeeds. Default is false;
  99.         * @return mixed
  100.         */
  101.         public static function check($function,$arguments,$onlyReturnBool = false) {
  102.                 if(!isset(self::$funcs[$function])) {
  103.                         self::$lastError = "The function '{$function}' is never supplied to strict_args.";
  104.                         return false;
  105.                 }
  106.                 foreach(self::$funcs[$function] AS $k => $v) {
  107.                         //Do we have corresponding values?
  108.                         //Check if arg exists in provided, if not, is it required?
  109.                         $val = null;
  110.                         if(!isset($arguments[$k]) AND self::$funcs[$function][$k][2]==true) {
  111.                                 self::$lastError = "Argument '{$k}' is required but not given.";
  112.                                 return false;
  113.                         } elseif(!isset($arguments[$k]) AND self::$funcs[$function][$k][2]==false) {
  114.                                 $val = self::$funcs[$function][$k][1];
  115.                         } else {
  116.                                 $val = $arguments[$k];
  117.                         }
  118.                        
  119.                         $strict = self::$funcs[$function][$k][3];
  120.                         if($strict == true AND self::$funcs[$function][$k][0] != 'any') {
  121.                                 switch(self::$funcs[$function][$k][0]) {
  122.                                         case 'array':
  123.                                                 if(!is_array($val)) { self::$lastError = "Argument '{$k}' is required to be an array."; return false;}
  124.                                                 break;
  125.                                         case 'bool':
  126.                                                 if(!is_bool($val)) { self::$lastError = "Argument '{$k}' is required to be a boolean."; return false;}
  127.                                                 break;
  128.                                         case 'float':
  129.                                                 if(!is_float($val)) { self::$lastError = "Argument '{$k}' is required to be a float."; return false;}
  130.                                                 break;
  131.                                         case 'int':
  132.                                                 if(!is_int($val)) { self::$lastError = "Argument '{$k}' is required to be an integer."; return false;}
  133.                                                 break;
  134.                                         case 'null':
  135.                                                 if(!is_null($val)) { self::$lastError = "Argument '{$k}' is required to be null."; return false;}
  136.                                                 break;
  137.                                         case 'numeric':
  138.                                                 if(!is_muneric($val)) { self::$lastError = "Argument '{$k}' is required to be numeric."; return false;}
  139.                                                 break;
  140.                                         case 'object':
  141.                                                 if(!is_object($val)) { self::$lastError = "Argument '{$k}' is required to be an object."; return false;}
  142.                                                 break;
  143.                                         case 'resource':
  144.                                                 if(!is_resource($val)) { self::$lastError = "Argument '{$k}' is required to be a resource."; return false;}
  145.                                                 break;
  146.                                         case 'scalar':
  147.                                                 if(!is_scalar($val)) { self::$lastError = "Argument '{$k}' is required to be scalar."; return false;}
  148.                                                 break;
  149.                                         case 'string':
  150.                                                 if(!is_string($val)) { self::$lastError = "Argument '{$k}' is required to be a string."; return false;}
  151.                                                 break;
  152.                                         default:
  153.                                                 self::$lastError = "Unknown Error";
  154.                                                 return false;
  155.                                 }
  156.                         }
  157.                         $rtn[$k] = $val;
  158.                 }
  159.                 return ($onlyReturnBool==true)?(bool)$rtn:$rtn;
  160.         }
  161. }
  162.  
  163. //Typical function definition.
  164. function test1($a,$b,$c=false) {
  165.         /*
  166.                 $a should be an integer.
  167.                 $b and $c should be a boolean.
  168.         */
  169.         strict_args::add(__FUNCTION__,0,'int');
  170.         strict_args::add(__FUNCTION__,1,'bool',null,true,true);
  171.         strict_args::add(__FUNCTION__,2,'string',null,true,true);
  172.        
  173.         $args = func_get_args();
  174.         $parsed_args = strict_args::check(__FUNCTION__,$args);
  175.        
  176.         if($parsed_args == false) {
  177.                 echo strict_args::lastError();
  178.         } else {
  179.                 echo "Arguments have passed check.";
  180.         }
  181. }
  182.  
  183. //Overloading a function
  184. function test2() {
  185.         $args = func_get_args();
  186.         /*
  187.         Try #1. Same as test1()
  188.                 $a should be an integer.
  189.                 $b and $c should be a boolean.
  190.         */
  191.         strict_args::add(__FUNCTION__,0,'int');
  192.         strict_args::add(__FUNCTION__,1,'bool',null,true,true);
  193.         strict_args::add(__FUNCTION__,2,'string',null,true,true);
  194.        
  195.         if(strict_args::check(__FUNCTION__,$args,true)) {
  196.                 //We could just call test1() right here! :O
  197.                 echo "try #1 passed.";
  198.         } else {
  199.                 echo "try #1 did not passed.";
  200.         }
  201.        
  202.         /*
  203.         Try #2. slightly modified.
  204.                 $a should be an integer.
  205.                 $b should be a boolean.
  206.                 $c should be a string.
  207.         */
  208.         strict_args::add(__FUNCTION__,0,'int');
  209.         strict_args::add(__FUNCTION__,1,'bool',null,true,true);
  210.         strict_args::add(__FUNCTION__,2,'string',null,'lol',true);
  211.        
  212.         if(strict_args::check(__FUNCTION__,$args,true)) {
  213.                 echo "try #2 passed.";
  214.         } else {
  215.                 echo "try #2 did not passed.";
  216.         }
  217.        
  218.         /*
  219.         Try #3. ...And yet a little more slightly modified.
  220.                 $a should be an integer.
  221.                 $b should be a boolean.
  222.                 $c should be a string.
  223.         */
  224.         strict_args::add(__FUNCTION__,0,'int');
  225.         strict_args::add(__FUNCTION__,1,'bool',null,true,true);
  226.         strict_args::add(__FUNCTION__,2,'string','lol',false,false);
  227.        
  228.         if(strict_args::check(__FUNCTION__,$args,true)) {
  229.                 echo "try #3 passed.";
  230.         } else {
  231.                 echo "try #3 did not passed.";
  232.         }
  233.        
  234. }
  235. test1(1,false,true);
  236. test2(1,false);
  237. ?>

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live PHP Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month