phpsec::arrayCheck

  1. phpsec
    1. dev
    2. b-0.2
    3. b-0.3
Versions
b-0.3 public static phpsec::arrayCheck($array, $structure, $strict = true)

Check structure of an array. This method checks the structure of an array (only the first layer of it) against a defined set of rules.

Parameters

array $array Array to check.

array $structure Expected array structure. Defined for example like this: array( 'string' => array( 'callback' => 'strlen', 'params' => array('%val'), 'match' => 3, ), 'not allowed' = false, // Only makes sense with $strict = false 'needed' = true, ),

bool $strict If strict is set to false we will allow keys that's not defined in the structure.

Code

./phpsec.class.php, line 255

<?php
public static function arrayCheck($array, $structure, $strict = true) {
  $success = true;
  /* First compare the size of the two arrays. Return error if strict is enabled. */
  if (sizeof($array) != sizeof($structure) && $strict === true) {
    self::error('Array does not match defined structure');
    return false;
  }

  /* Loop trough all the defined keys defined in the structure. */
  foreach ($structure as $key => $callbackArray) {
    if (isset($array[$key])) {
      /* The key exists in the array we are checking. */

      if (is_array($callbackArray) && isset($callbackArray['callback'])) {
        /* We have a callback. */

        /* Replace %val with the acutal value of the key. */
        $callbackArray['params'] = str_replace('%val', $array[$key], $callbackArray['params']);

        if (call_user_func_array($callbackArray['callback'], $callbackArray['params']) !== $callbackArray['match']) {
          /* Call the *duh* callback. If this returns false throw error, or an axe. */
          self::error('Array does not match defined structure. The ' . $key . ' key did not pass the ' . $callbackArray['callback'] . ' callback');
          $success = false;
        }
      }
      elseif ($callbackArray === false) {
        /* We don't have a callback, but we have found a disallowed key. */
        self::error('Array does not match defined structure. ' . $key . ' is not allowed');
        $success = false;
      }
    }
    else {
      /* The key don't exist in the array we are checking. */

      if ($callbackArray !== false) {
        /* As long as this is not a disallowed key, sound the general alarm. */
        self::error('Array does not match defined structure. ' . $key . ' not defined');
        $success = false;
      }
    }
  }
  return $success;
}
?>

Copyright (c) 2011, 2012 Audun Larsen.

Drupal theme by Kiwi Themes.