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