1 <?php
2 /**
3 * Copyright 2014 Klarna AB
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 * File containing the UserAgent class.
18 */
19
20 namespace Klarna\Rest\Transport;
21
22 use GuzzleHttp\ClientInterface;
23
24 /**
25 * HTTP user agent.
26 */
27 class UserAgent implements UserAgentInterface
28 {
29 /**
30 * Name of the SDK
31 */
32 const NAME = 'Klarna.kco_rest_php';
33
34 /**
35 * Version of the SDK.
36 */
37 const VERSION = '2.2.0';
38
39 /**
40 * Components of the user agent.
41 *
42 * @var array
43 */
44 protected $fields;
45
46 /**
47 * Constructs a user agent instance.
48 */
49 public function __construct()
50 {
51 $this->fields = [];
52 }
53
54 /**
55 * Sets the specified field.
56 *
57 * @param string $key Component key, e.g. 'Language'
58 * @param string $name Component name, e.g. 'PHP'
59 * @param string $version Version identifier, e.g. '5.4.10'
60 * @param array $options Additional information
61 *
62 * @return self
63 */
64 public function setField($key, $name, $version = '', array $options = [])
65 {
66 $field = [
67 'name' => $name
68 ];
69
70 if (!empty($version)) {
71 $field['version'] = $version;
72 }
73
74 if (!empty($options)) {
75 $field['options'] = $options;
76 }
77
78 $this->fields[$key] = $field;
79
80 return $this;
81 }
82
83 /**
84 * Serialises the user agent.
85 *
86 * @return string
87 */
88 public function __toString()
89 {
90 $parts = [];
91
92 foreach ($this->fields as $key => $value) {
93 $component = "{$key}/{$value['name']}";
94 if (!empty($value['version'])) {
95 $component .= "_{$value['version']}";
96 }
97
98 $parts[] = $component;
99
100 if (empty($value['options'])) {
101 continue;
102 }
103
104 $opts = implode('; ', $value['options']);
105 $parts[] = "({$opts})";
106 }
107
108 return implode(' ', $parts);
109 }
110
111 /**
112 * Creates the default user agent.
113 *
114 * @return self
115 */
116 public static function createDefault()
117 {
118 $agent = new static();
119
120 $options = ['Guzzle/' . ClientInterface::VERSION];
121 if (extension_loaded('curl')) {
122 $options[] = 'curl/' . curl_version()['version'];
123 }
124
125 return $agent
126 ->setField('Library', static::NAME, static::VERSION, $options)
127 ->setField('OS', php_uname('s'), php_uname('r'))
128 ->setField('Language', 'PHP', phpversion());
129 }
130 }
131