4 * This file is part of the civicrm-cxn-rpc package.
6 * Copyright (c) CiviCRM LLC <info@civicrm.org>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this package.
12 namespace Civi\Cxn\Rpc
;
14 use Civi\Cxn\Rpc\Exception\GarbledMessageException
;
15 use Civi\Cxn\Rpc\Exception\InvalidMessageException
;
16 use Civi\Cxn\Rpc\Http\ViaPortHttp
;
17 use Civi\Cxn\Rpc\Message\GarbledMessage
;
18 use Civi\Cxn\Rpc\Message\StdMessage
;
20 class ApiClient
extends Agent
{
32 * @param array $appMeta
33 * @param CxnStore\CxnStoreInterface $cxnStore
34 * @param string $cxnId
36 public function __construct($appMeta, $cxnStore, $cxnId) {
37 parent
::__construct(NULL, $cxnStore);
38 $this->appMeta
= $appMeta;
39 $this->cxnId
= $cxnId;
40 $this->http
= new Http\
PhpHttp();
46 * Protocol errors will be reported as exceptions.
48 * @param string $entity
49 * @param string $action
50 * @param array $params
51 * @throws GarbledMessageException
52 * @throws InvalidMessageException
55 public function call($entity, $action, $params = array()) {
56 $this->log
->debug("Send API call: {entity}.{action} over {cxnId}", array(
59 'cxnId' => $this->cxnId
,
61 $cxn = $this->cxnStore
->getByCxnId($this->cxnId
);
62 $req = new StdMessage($cxn['cxnId'], $cxn['secret'],
63 array($entity, $action, $params, $this->appMeta
['appCert']));
65 $http = empty($cxn['viaPort']) ?
$this->http
: new ViaPortHttp($this->http
, $cxn['viaPort']);
67 list($respHeaders, $respCiphertext, $respCode) = $http->send('POST', $cxn['siteUrl'], $req->encode(), array(
68 'Content-type' => Constants
::MIME_TYPE
,
70 $respMessage = $this->decode(array(StdMessage
::NAME
, GarbledMessage
::NAME
), $respCiphertext);
71 if ($respMessage instanceof GarbledMessage
) {
72 throw new GarbledMessageException($respMessage);
74 elseif ($respMessage instanceof StdMessage
) {
75 if ($respMessage->getCxnId() != $cxn['cxnId']) {
77 throw new InvalidMessageException('Received response from incorrect connection.');
79 return $respMessage->getData();
82 throw new InvalidMessageException('Unrecognized message type.');
89 * This is the same as call(), except that it wraps the request in a try-catch
90 * block and converts any exceptions to array(is_error=>...) format.
94 * @param array $params
97 public function callSafe($entity, $action, $params = array()) {
99 return $this->call($entity, $action, $params);
101 catch (GarbledMessageException
$e) {
104 'error_message' => "Client exception: " . $e->getMessage(),
105 'garbled_message' => substr($e->getGarbledMessage()->getData(), 0, 77),
108 catch (\Exception
$e) {
111 'error_message' => "Client exception: " . $e->getMessage(),
112 'trace' => $e->getTraceAsString(),