[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/google/Google/ -> Model.php (source)

   1  <?php
   2  /*
   3   * Copyright 2011 Google Inc.
   4   *
   5   * Licensed under the Apache License, Version 2.0 (the "License");
   6   * you may not use this file except in compliance with the License.
   7   * You may obtain a copy of the License at
   8   *
   9   *     http://www.apache.org/licenses/LICENSE-2.0
  10   *
  11   * Unless required by applicable law or agreed to in writing, software
  12   * distributed under the License is distributed on an "AS IS" BASIS,
  13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14   * See the License for the specific language governing permissions and
  15   * limitations under the License.
  16   */
  17  
  18  /**
  19   * This class defines attributes, valid values, and usage which is generated
  20   * from a given json schema.
  21   * http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
  22   *
  23   * @author Chirag Shah <[email protected]>
  24   *
  25   */
  26  class Google_Model implements ArrayAccess
  27  {
  28    protected $modelData = array();
  29    protected $processed = array();
  30  
  31    /**
  32     * Polymorphic - accepts a variable number of arguments dependent
  33     * on the type of the model subclass.
  34     */
  35    public function __construct()
  36    {
  37      if (func_num_args() == 1 && is_array(func_get_arg(0))) {
  38        // Initialize the model with the array's contents.
  39        $array = func_get_arg(0);
  40        $this->mapTypes($array);
  41      }
  42    }
  43  
  44    public function __get($key)
  45    {
  46      $keyTypeName = $this->keyType($key);
  47      $keyDataType = $this->dataType($key);
  48      if (isset($this->$keyTypeName) && !isset($this->processed[$key])) {
  49        if (isset($this->modelData[$key])) {
  50          $val = $this->modelData[$key];
  51        } else if (isset($this->$keyDataType) &&
  52            ($this->$keyDataType == 'array' || $this->$keyDataType == 'map')) {
  53          $val = array();
  54        } else {
  55          $val = null;
  56        }
  57  
  58        if ($this->isAssociativeArray($val)) {
  59          if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
  60            foreach ($val as $arrayKey => $arrayItem) {
  61                $this->modelData[$key][$arrayKey] =
  62                  $this->createObjectFromName($keyTypeName, $arrayItem);
  63            }
  64          } else {
  65            $this->modelData[$key] = $this->createObjectFromName($keyTypeName, $val);
  66          }
  67        } else if (is_array($val)) {
  68          $arrayObject = array();
  69          foreach ($val as $arrayIndex => $arrayItem) {
  70            $arrayObject[$arrayIndex] =
  71              $this->createObjectFromName($keyTypeName, $arrayItem);
  72          }
  73          $this->modelData[$key] = $arrayObject;
  74        }
  75        $this->processed[$key] = true;
  76      }
  77  
  78      return $this->modelData[$key];
  79    }
  80  
  81    /**
  82     * Initialize this object's properties from an array.
  83     *
  84     * @param array $array Used to seed this object's properties.
  85     * @return void
  86     */
  87    protected function mapTypes($array)
  88    {
  89      // Hard initilise simple types, lazy load more complex ones.
  90      foreach ($array as $key => $val) {
  91        if ( !property_exists($this, $this->keyType($key)) &&
  92          property_exists($this, $key)) {
  93            $this->$key = $val;
  94            unset($array[$key]);
  95        } elseif (property_exists($this, $camelKey = Google_Utils::camelCase($key))) {
  96            // This checks if property exists as camelCase, leaving it in array as snake_case
  97            // in case of backwards compatibility issues.
  98            $this->$camelKey = $val;
  99        }
 100      }
 101      $this->modelData = $array;
 102    }
 103  
 104    /**
 105     * Create a simplified object suitable for straightforward
 106     * conversion to JSON. This is relatively expensive
 107     * due to the usage of reflection, but shouldn't be called
 108     * a whole lot, and is the most straightforward way to filter.
 109     */
 110    public function toSimpleObject()
 111    {
 112      $object = new stdClass();
 113  
 114      // Process all other data.
 115      foreach ($this->modelData as $key => $val) {
 116        $result = $this->getSimpleValue($val);
 117        if ($result !== null) {
 118          $object->$key = $result;
 119        }
 120      }
 121  
 122      // Process all public properties.
 123      $reflect = new ReflectionObject($this);
 124      $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
 125      foreach ($props as $member) {
 126        $name = $member->getName();
 127        $result = $this->getSimpleValue($this->$name);
 128        if ($result !== null) {
 129          $object->$name = $result;
 130        }
 131      }
 132  
 133      return $object;
 134    }
 135  
 136    /**
 137     * Handle different types of values, primarily
 138     * other objects and map and array data types.
 139     */
 140    private function getSimpleValue($value)
 141    {
 142      if ($value instanceof Google_Model) {
 143        return $value->toSimpleObject();
 144      } else if (is_array($value)) {
 145        $return = array();
 146        foreach ($value as $key => $a_value) {
 147          $a_value = $this->getSimpleValue($a_value);
 148          if ($a_value !== null) {
 149            $return[$key] = $a_value;
 150          }
 151        }
 152        return $return;
 153      }
 154      return $value;
 155    }
 156  
 157    /**
 158     * Returns true only if the array is associative.
 159     * @param array $array
 160     * @return bool True if the array is associative.
 161     */
 162    protected function isAssociativeArray($array)
 163    {
 164      if (!is_array($array)) {
 165        return false;
 166      }
 167      $keys = array_keys($array);
 168      foreach ($keys as $key) {
 169        if (is_string($key)) {
 170          return true;
 171        }
 172      }
 173      return false;
 174    }
 175  
 176    /**
 177     * Given a variable name, discover its type.
 178     *
 179     * @param $name
 180     * @param $item
 181     * @return object The object from the item.
 182     */
 183    private function createObjectFromName($name, $item)
 184    {
 185      $type = $this->$name;
 186      return new $type($item);
 187    }
 188  
 189    /**
 190     * Verify if $obj is an array.
 191     * @throws Google_Exception Thrown if $obj isn't an array.
 192     * @param array $obj Items that should be validated.
 193     * @param string $method Method expecting an array as an argument.
 194     */
 195    public function assertIsArray($obj, $method)
 196    {
 197      if ($obj && !is_array($obj)) {
 198        throw new Google_Exception(
 199            "Incorrect parameter type passed to $method(). Expected an array."
 200        );
 201      }
 202    }
 203  
 204    public function offsetExists($offset)
 205    {
 206      return isset($this->$offset) || isset($this->modelData[$offset]);
 207    }
 208  
 209    public function offsetGet($offset)
 210    {
 211      return isset($this->$offset) ?
 212          $this->$offset :
 213          $this->__get($offset);
 214    }
 215  
 216    public function offsetSet($offset, $value)
 217    {
 218      if (property_exists($this, $offset)) {
 219        $this->$offset = $value;
 220      } else {
 221        $this->modelData[$offset] = $value;
 222        $this->processed[$offset] = true;
 223      }
 224    }
 225  
 226    public function offsetUnset($offset)
 227    {
 228      unset($this->modelData[$offset]);
 229    }
 230  
 231    protected function keyType($key)
 232    {
 233      return $key . "Type";
 234    }
 235  
 236    protected function dataType($key)
 237    {
 238      return $key . "DataType";
 239    }
 240  
 241    public function __isset($key)
 242    {
 243      return isset($this->modelData[$key]);
 244    }
 245  
 246    public function __unset($key)
 247    {
 248      unset($this->modelData[$key]);
 249    }
 250  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1