     1: <?php
     2: /**
     3:  * Copyright 2012-2014 Rackspace US, 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: namespace OpenCloud\LoadBalancer\Resource;
    19:
    20: use Guzzle\Http\Exception\ClientErrorResponseException;
    21: use OpenCloud\Common\Resource\PersistentResource;
    22:
    23: /**
    24:  * Class that represents abstract functionality for Load Balancer resources
    25:  *
    26:  * @package OpenCloud\LoadBalancer\Resource
    27:  */
    28: abstract class AbstractResource extends PersistentResource
    29: {
    30:     public function refresh($id = null, $url = null)
    31:     {
    32:         if (!isset($this->id)) {
    33:             return false;
    34:         }
    35:
    36:         try {
    37:             return parent::refresh($id, $url);
    38:         } catch (ClientErrorResponseException $e) {
    39:             return false;
    40:         }
    41:     }
    42:
    43:     /**
    44:      * Causes resource to refresh based on parent's URL
    45:      */
    46:     protected function refreshFromParent()
    47:     {
    48:         $url = clone $this->getParent()->getUrl();
    49:         $url->addPath($this->resourceName());
    50:
    51:         $response = $this->getClient()->get($url)->send();
    52:
    53:         if (null !== ($decoded = $this->parseResponse($response))) {
    54:             $this->populate($decoded);
    55:         }
    56:     }
    57:
    58:     protected function createJson()
    59:     {
    60:         $object = new \stdClass;
    61:
    62:         foreach ($this->createKeys as $item) {
    63:             $object->$item = $this->$item;
    64:         }
    65:
    66:         if ($top = $this->jsonName()) {
    67:             $object = array($top => $object);
    68:         }
    69:
    70:         return $object;
    71:     }
    72:
    73:     protected function updateJson($params = array())
    74:     {
    75:         return $this->createJson();
    76:     }
    77:
    78:     public function name()
    79:     {
    80:         $classArray = explode('\\', get_class($this));
    81:
    82:         return method_exists($this->getParent(), 'id')
    83:             ? sprintf('%s-%s', end($classArray), $this->getParent()->id())
    84:             : parent::name();
    85:     }
    86: }
    87: