1: <?php
2: /**
3: * PHP OpenCloud library.
4: *
5: * @copyright 2013 Rackspace Hosting, Inc. See LICENSE for information.
6: * @license https://www.apache.org/licenses/LICENSE-2.0
7: * @author Glen Campbell <glen.campbell@rackspace.com>
8: * @author Jamie Hannaford <jamie.hannaford@rackspace.com>
9: */
10:
11: namespace OpenCloud\Compute\Resource;
12:
13: use OpenCloud\Common\PersistentObject;
14: use OpenCloud\Compute\Exception\KeyPairException;
15: use OpenCloud\Common\Exceptions\InvalidArgumentError;
16:
17: /**
18: * Description of KeyPair
19: *
20: * @link
21: */
22: class KeyPair extends PersistentObject
23: {
24:
25: private $name;
26: private $fingerprint;
27: private $privateKey;
28: private $publicKey;
29: private $userId;
30:
31: public $aliases = array(
32: 'private_key' => 'privateKey',
33: 'public_key' => 'publicKey',
34: 'user_id' => 'userId'
35: );
36:
37: protected static $url_resource = 'os-keypairs';
38: protected static $json_name = 'keypair';
39: protected static $json_collection_element = 'keypair';
40:
41: public function setName($name)
42: {
43: if (preg_match('#[^\w\d\s-_]#', $name) || strlen($name) > 255) {
44: throw new InvalidArgumentError(sprintf(
45: 'The key name may not exceed 255 characters. It can contain the'
46: . ' following characters: alphanumeric, spaces, dashes and'
47: . ' underscores. You provided [%s].',
48: $name
49: ));
50: }
51: $this->name = $name;
52: return $this;
53: }
54:
55: public function getName()
56: {
57: return $this->name;
58: }
59:
60: /**
61: * {@inheritDoc}
62: */
63: public function createJson()
64: {
65: $object = (object) array(
66: 'name' => $this->getName()
67: );
68: if (null !== ($key = $this->getPublicKey())) {
69: $object->public_key = $key;
70: }
71: return (object) array('keypair' => $object);
72: }
73:
74: /**
75: * {@inheritDoc}
76: */
77: public function create($params = array())
78: {
79: $this->setPublicKey(null);
80: return parent::create($params);
81: }
82:
83: /**
84: * Upload an existing public key to a new keypair.
85: *
86: * @param array $options
87: * @return type
88: * @throws KeyPairException
89: */
90: public function upload(array $options = array())
91: {
92: if (isset($options['path'])) {
93: if (!file_exists($options['path'])) {
94: throw new KeyPairException('%s does not exist.');
95: }
96: $contents = file_get_contents($options['path']);
97: $this->setPublicKey($contents);
98: } elseif (isset($options['data'])) {
99: $this->setPublicKey($options['data']);
100: } elseif (!$this->getPublicKey()) {
101: throw new KeyPairException(
102: 'In order to upload a keypair, the public key must be set.'
103: );
104: }
105: return parent::create();
106: }
107:
108: /**
109: * {@inheritDoc}
110: */
111: public function update($params = array())
112: {
113: return $this->noUpdate();
114: }
115:
116: /**
117: * {@inheritDoc}
118: */
119: public function primaryKeyField()
120: {
121: return 'name';
122: }
123:
124: }