WSClient::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 6
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Vtiger Web Services PHP Client Library
5
 *
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2015, Zhmayev Yaroslav <[email protected]>
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a copy
11
 * of this software and associated documentation files (the "Software"), to deal
12
 * in the Software without restriction, including without limitation the rights
13
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
 * copies of the Software, and to permit persons to whom the Software is
15
 * furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included in
18
 * all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
 * THE SOFTWARE.
27
 *
28
 * @author    Zhmayev Yaroslav <[email protected]>
29
 * @copyright 2015-2016 Zhmayev Yaroslav
30
 * @license   The MIT License (MIT)
31
 */
32
33
namespace Salaros\Vtiger\VTWSCLib;
34
35
use Salaros\Vtiger\VTWSCLib\Entities;
36
use Salaros\Vtiger\VTWSCLib\Modules;
37
use Salaros\Vtiger\VTWSCLib\Session;
38
use Salaros\Vtiger\VTWSCLib\WSException;
39
40
/**
41
 * Vtiger Web Services PHP Client
42
 *
43
 * Class WSClient
44
 * @package Salaros\Vtiger\VTWSCLib
45
 */
46
class WSClient
47
{
48
    private $session = null;
49
    
50
    public $modules = null;
51
    public $entities = null;
52
53
    const USE_ACCESSKEY = 1;
54
    const USE_PASSWORD = 2;
55
    
56
    /**
57
     * Class constructor
58
     * @param string $vtigerUrl  The URL of the remote WebServices server
59
     * @param  string $username  User name
60
     * @param  string $secret  Access key token (shown on user's profile page) or password, depends on $loginMode
61
     * @param  integer [$loginMode = self::USE_ACCESSKEY|USE_PASSWORD]  Login mode, defaults to username + accessKey
62
     * @param string [$wsBaseURL = 'webservice.php']  WebServices base URL appended to vTiger root URL
63
     * @param int Optional request timeout in seconds
64
     */
65
    public function __construct($vtigerUrl, $username, $secret, $loginMode = self::USE_ACCESSKEY, $wsBaseURL = 'webservice.php', $requestTimeout = 0)
66
    {
67
        $this->modules = new Modules($this);
68
        $this->entities = new Entities($this);
69
        $this->session = new Session($vtigerUrl, $wsBaseURL, $requestTimeout);
70
71
        $loginOK = false;
72
        switch ($loginMode) {
73
            case self::USE_ACCESSKEY:
74
                $loginOK = $this->session->login($username, $secret);
75
                break;
76
77
            case self::USE_PASSWORD:
78
                $loginOK = $this->session->loginPassword($username, $secret);
79
                break;
80
            
81
            default:
82
                throw new WSException(sprintf('Unknown login mode: %s', $loginMode));
83
        }
84
85
        if (!$loginOK) {
86
            throw new WSException(sprintf(
87
                'Failed to log into vTiger CRM (User: %s, URL: %s)',
88
                $username,
89
                $vtigerUrl
90
            ));
91
        }
92
    }
93
94
    /**
95
     * Invokes custom operation (defined in vtiger_ws_operation table)
96
     * @access public
97
     * @param  string  $operation  Name of the webservice to invoke
98
     * @param  array   [$params = null] Parameter values to operation
99
     * @param  string  [$method = 'POST'] HTTP request method (GET, POST etc)
100
     * @return array Result object
101
     */
102
    public function invokeOperation($operation, array $params = null, $method = 'POST')
103
    {
104
        if (is_array($params) && !empty($params) && !is_assoc_array($params)) {
105
            throw new WSException(
106
                "You have to specified a list of operation parameters, but apparently 
107
                it's not an associative array ('prop' => value)!"
108
            );
109
        }
110
111
        $params[ 'operation' ] = $operation;
112
        return $this->session->sendHttpRequest($params, $method);
113
    }
114
115
    /**
116
     * VTiger provides a simple query language for fetching data.
117
     * This language is quite similar to select queries in SQL.
118
     * There are limitations, the queries work on a single Module,
119
     * embedded queries are not supported, and does not support joins.
120
     * But this is still a powerful way of getting data from Vtiger.
121
     * Query always limits its output to 100 records,
122
     * Client application can use limit operator to get different records.
123
     * @access public
124
     * @param  string $query SQL-like expression
125
     * @return array  Query results
126
     */
127
    public function runQuery($query)
128
    {
129
        // Make sure the query ends with ;
130
        $query = (strripos($query, ';') != strlen($query) - 1)
131
            ? trim($query .= ';')
132
            : trim($query);
133
134
        return $this->invokeOperation('query', [ 'query' => $query ], 'GET');
135
    }
136
137
    /**
138
     * Gets an array containing the basic information about current API user
139
     * @access public
140
     * @return array Basic information about current API user
141
     */
142
    public function getCurrentUser()
143
    {
144
        return $this->session->getUserInfo();
145
    }
146
147
    /**
148
     * Gets an array containing the basic information about the connected vTiger instance
149
     * @access public
150
     * @return array Basic information about the connected vTiger instance
151
     */
152
    public function getVtigerInfo()
153
    {
154
        return [
155
            'vtiger' => $this->session->getVtigerVersion(),
156
            'api' => $this->session->getVtigerApiVersion(),
157
        ];
158
    }
159
}
160
161
if (!function_exists('is_assoc_array')) {
162
163
    /**
164
     * Checks if an array is associative or not
165
     * @param  string  Array to test
166
     * @return boolean Returns true in a given array is associative and false if it's not
167
     */
168
    function is_assoc_array(array $array)
169
    {
170
        if (empty($array) || !is_array($array)) {
171
            return false;
172
        }
173
174
        foreach (array_keys($array) as $key) {
175
            if (!is_int($key)) {
176
                return true;
177
            }
178
        }
179
        return false;
180
    }
181
}
182