1 <?php
2 /**
3 * Copyright 2015 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 Klarna_Checkout_UserAgent class
18 *
19 * PHP version 5.3
20 *
21 * @category Payment
22 * @package Klarna_Checkout
23 * @author Klarna <support@klarna.com>
24 * @copyright 2015 Klarna AB
25 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0
26 * @link http://developers.klarna.com/
27 */
28
29 /**
30 * UserAgent string builder
31 *
32 * @category Payment
33 * @package Klarna_Checkout
34 * @author David K. <david.keijser@klarna.com>
35 * @copyright 2015 Klarna AB
36 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0
37 * @link http://developers.klarna.com/
38 */
39 class Klarna_Checkout_UserAgent
40 {
41 /**
42 * Components of the user-agent
43 *
44 * @var array
45 */
46 private $_fields;
47
48 /**
49 * Initialise user-agent with default fields
50 */
51 public function __construct()
52 {
53 $this->_fields = array(
54 'Library' => array(
55 'name' => 'Klarna.ApiWrapper',
56 'version' => '4.0.0',
57 ),
58 'OS' => array(
59 'name' => php_uname('s'),
60 'version' => php_uname('r')
61 ),
62 'Language' => array(
63 'name' => 'PHP',
64 'version' => phpversion()
65 )
66 );
67 }
68
69 /**
70 * Add a new field to the user agent
71 *
72 * @param string $field Name of field
73 * @param array $data data array with name, version and possibly options
74 *
75 * @return void
76 * @throws Klarna_Checkout_Exception
77 */
78 public function addField($field, array $data)
79 {
80 if (array_key_exists($field, $this->_fields)) {
81 throw new Klarna_Checkout_Exception(
82 "Unable to redefine field {$field}"
83 );
84 }
85 $this->_fields[$field] = $data;
86 }
87
88 /**
89 * Serialise fields to a user agent string
90 *
91 * @return string
92 */
93 public function __toString()
94 {
95 $parts = array();
96 foreach ($this->_fields as $key => $value) {
97 $parts[] = "$key/{$value['name']}_{$value['version']}";
98 if (array_key_exists('options', $value)) {
99 $parts[] = '(' . implode(' ; ', $value['options']) . ')';
100 }
101 }
102 return implode(' ', $parts);
103 }
104 }
105