1: <?php
2: /**
3: * PHP OpenCloud library.
4: *
5: * @copyright Copyright 2013 Rackspace US, Inc. See COPYING for licensing information.
6: * @license https://www.apache.org/licenses/LICENSE-2.0 Apache 2.0
7: * @version 1.6.0
8: * @author Jamie Hannaford <jamie.hannaford@rackspace.com>
9: */
10:
11: namespace OpenCloud\Autoscale\Resource;
12:
13: use OpenCloud\Common\PersistentObject;
14:
15: /**
16: * Contains generic, abstracted functionality for Autoscale resources.
17: */
18: abstract class AbstractResource extends PersistentObject
19: {
20: /**
21: * These are used to set the object used for JSON encode.
22: *
23: * @var array
24: */
25: public $createKeys = array();
26:
27: /**
28: * These resources are associated with this one. When this resource object
29: * is populated, if a key is found matching one of these array keys, it is
30: * set as an instantiated resource object (rather than an arbitrary string
31: * or stdClass object).
32: *
33: * @var array
34: */
35: public $associatedResources = array();
36:
37: /**
38: * Same as an associated resource, but it's instantiated as a Collection.
39: *
40: * @var array
41: */
42: public $associatedCollections = array();
43:
44: /**
45: * Returns the URL for this resource.
46: *
47: * @param string|null $subResource
48: * @param bool $includeId
49: * @return string
50: */
51: public function url($subResource = null, $includeId = true)
52: {
53: $url = $this->parent()->url($this->resourceName());
54:
55: if ($includeId && $this->id) {
56: $url .= '/' . $this->id;
57: }
58:
59: if ($subResource) {
60: $url .= '/' . $subResource;
61: }
62:
63: return $url;
64: }
65:
66: /**
67: * Creates the object which will be JSON encoded for request.
68: *
69: * @return \stdClass
70: */
71: public function createJson()
72: {
73: $object = new \stdClass;
74:
75: foreach ($this->createKeys as $key) {
76: if (!empty($this->$key)) {
77: $object->$key = $this->$key;
78: }
79: }
80:
81: if (!empty($this->metadata)) {
82: $object->metadata = new \stdClass;
83: foreach ($this->metadata as $key => $value) {
84: $object->metadata->$key = $value;
85: }
86: }
87:
88: return $object;
89: }
90:
91: /**
92: * Creates the object which will be JSON encoded for request.
93: *
94: * @return array
95: */
96: protected function updateJson($params = array())
97: {
98: $existing = array();
99: foreach ($this->createKeys as $key) {
100: $existing[$key] = $this->$key;
101: }
102:
103: return $existing + $params;
104: }
105:
106: /**
107: * Factory method for returning a resource. This is mostly used when a
108: * Collection instantiates an individual resource (i.e. in next() calls).
109: *
110: * @param string $name
111: * @param string $info
112: * @return AbstractResource
113: */
114: public function resource($name, $info)
115: {
116: return $this->getService()->resource($name, $info);
117: }
118:
119: }