This repository has been archived by the owner on Feb 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
ApiConnector.php
697 lines (632 loc) · 20.4 KB
/
ApiConnector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<?php
/**
* Communicates with Moneybird through REST API
* For more information about the MoneyBird API, please visit
* http://www.moneybird.nl/help/api
*
* @author Sjors van der Pluijm <[email protected]>; @sjorsvdp
*/
namespace Moneybird;
use \DateTime;
use Moneybird\HttpClient\HttpStatusException;
use Moneybird\Error\ArrayObject as ErrorArray;
use Moneybird\Domainmodel\AbstractModel;
use Moneybird\Envelope\AbstractEnvelope;
use Moneybird\Payment\AbstractPayment;
use Moneybird\Invoice\Envelope as InvoiceEnvelope;
/**
* Service for connecting with Moneybird
*/
class ApiConnector
{
const API_VERSION = '1.0';
/**
* First part of Url to connect to
*
* @access protected
* @var string
*/
protected $baseUri;
/**
* HttpRequest object
*
* @access protected
* @var Transport
*/
protected $transport;
/**
* Mapper object
*
* @access protected
* @var Mapper
*/
protected $mapper;
/**
* @var CurrentSession
* @access protected
*/
protected $currentSession;
/**
* Last error messages
* @var Array
*/
protected $errors = array();
/**
* Array of created service objects
* @var Array
*/
protected $services = array();
/**
* Array of available filters
* @var Array
*/
protected $filters = array();
/**
* Array for mapping named id's to objects
* @var Array
*/
protected $namedId = array();
/**
* Indicates if the login credentials where tested
* @var bool
*/
protected $loginTested = false;
/**
* Show debug information
* @var bool
* @static
*/
public static $debug = false;
/**
* Autoloader
* @static
* @param string $classname
*/
static public function autoload($classname)
{
if (strpos($classname, __NAMESPACE__) === 0) {
$classname = substr($classname, strlen(__NAMESPACE__) + 1);
if (file_exists(__DIR__ . '/' . str_replace('\\', '/', $classname) . '.php')) {
require_once __DIR__ . '/' . str_replace('\\', '/', $classname) . '.php';
}
}
}
/**
* Create a service object
*
* @param string $clientName Moneybird client name (<client>.moneybird.nl)
* @param Transport $transport
* @param Mapper $mapper
* @access public
* @throws NotLoggedInException
* @throws InvalidConfigException
*/
public function __construct($clientName, Transport $transport, Mapper $mapper)
{
$this->transport = $transport;
$this->mapper = $mapper;
$this->transport->setUserAgent('MoneybirdPhpApi/2.3');
if (!preg_match('/^[a-z0-9_\-]+$/', $clientName)) {
throw new InvalidConfigException('Invalid companyname/clientname');
}
$this->baseUri = 'https://' . $clientName . '.moneybird.nl/api/v' . self::API_VERSION;
$this->namedId = array(
__NAMESPACE__ . '\Contact' => array(
'customer_id',
),
__NAMESPACE__ . '\Invoice' => array(
'invoice_id',
),
);
$this->filters = array(
__NAMESPACE__ . '\Invoice' => array(
'all', 'this_month', 'last_month', 'this_quarter', 'last_quarter',
'this_year', 'last_year', 'draft', 'sent', 'open', 'late', 'paid'
),
__NAMESPACE__ . '\Estimate' => array(
'all', 'active', 'draft', 'sent', 'open', 'late', 'accepted',
'rejected', 'billed', 'archived',
'this_month', 'last_month', 'this_quarter', 'last_quarter',
'this_year', 'last_year',
),
__NAMESPACE__ . '\IncomingInvoice' => array(
'all', 'this_month', 'last_month', 'this_quarter', 'last_quarter',
'this_year', 'draft', 'sent', 'open', 'late', 'paid'
),
__NAMESPACE__ . '\RecurringTemplate' => array(
'all', 'inactive', 'weekly', 'monthly', 'quarterly', 'half_yearly',
'yearly', 'upcoming',
),
);
}
/**
* Login
* @return self
* @throws NotLoggedInException
* @access protected
*/
protected function testLogin()
{
if (!$this->loginTested) {
$this->loginTested = true;
try {
$this->getCurrentSession();
} catch (NotFoundException $e) {
throw new NotLoggedInException('Invalid companyname/clientname');
}
}
return $this;
}
/**
* Number of requests left (max 350/h)
* @return int
*/
public function requestsLeft()
{
$this->testLogin();
return $this->transport->requestsLeft();
}
/**
* Send request to Moneybird
*
* @access protected
* @return string
* @param string $url
* @param string $method (GET|POST|PUT|DELETE)
* @param string $data
*/
protected function request($url, $method, $data = null)
{
$this->testLogin();
try {
$response = $this->transport->send(
$url, $method, $data, array(
'Content-Type: ' . $this->mapper->getContentType(),
)
);
} catch (HttpStatusException $e) {
$message = $e->getMessage();
if ($e->getCode() == 403 || $e->getCode() == 422) {
$this->errors = $this->mapper->mapFromStorage($this->transport->getLastResponse());
if ($this->errors instanceof ErrorArray && count($this->errors) > 0) {
$message .= PHP_EOL . 'Errors:' . PHP_EOL . $this->errors;
}
}
if (self::$debug) {
printf(
'Url: %s' . PHP_EOL . 'Method: %s' . PHP_EOL . 'Data: %s', $url, $method, $data
);
}
switch ($e->getCode()) {
case 401:
throw new NotLoggedInException($message, 0, $e);
break;
case 403:
throw new ForbiddenException($message, 0, $e);
break;
case 404:
throw new NotFoundException($message, 0, $e);
break;
case 406:
case 422:
throw new NotValidException($message, 0, $e);
break;
default:
$message = 'Unknown error; check https://github.com/bluetools/moneybird_php_api/wiki/Common-errors';
// no break
case 500:
case 501:
throw new ServerErrorException($message, 0, $e);
break;
}
}
return $response;
}
/**
* Save object
*
* @param Storable $model
* @param AbstractModel $parent
* @return Storable
*/
public function save(Storable $model, AbstractModel $parent = null)
{
$response = $this->request(
$this->buildUrl($model, $parent), $model->getId() > 0 ? 'PUT' : 'POST', $this->mapper->mapToStorage($model)
);
return $this->mapper->mapFromStorage($response);
}
/**
* Delete object
* @param Storable $model
* @param AbstractModel $parent
* @return self
* @throws ForbiddenException
*/
public function delete(Storable $model, AbstractModel $parent = null)
{
$types = array('Invoice', 'Estimate', 'RecurringTemplate', 'IncomingInvoice');
foreach ($types as $type) {
$interface = $type . '\Subject';
$method = 'get' . $type . 's';
if (($model instanceof $interface) && count($model->$method($this->getService($type))) > 0) {
throw new ForbiddenException('Unable to delete ' . $type . 'Subject with ' . strtolower($type) . 's');
}
}
$this->request(
$this->buildUrl($model, $parent), 'DELETE'
);
return $this;
}
/**
* Send invoice or estimate
*
* @param Sendable $model
* @param AbstractEnvelope $envelope
* @return Sendable
*/
public function send(Sendable $model, AbstractEnvelope $envelope)
{
$classname = $this->getType($model);
if (intval($model->getId()) == 0) {
$model->save($this->getService($classname));
}
$response = $this->request(
$this->buildUrl($model, null, '/send_' . strtolower($classname)), 'PUT', $this->mapper->mapToStorage($envelope)
);
return $this->mapper->mapFromStorage($response);
}
/**
* Register payment
*
* @access public
* @param Payable $invoice invoice to register payment for
* @param AbstractPayment $payment payment to register
* @return Payable
*/
public function registerPayment(Payable $invoice, AbstractPayment $payment)
{
$classname = $this->getType($invoice);
if (intval($invoice->getId()) == 0) {
$invoice->save($this->getService($classname));
}
$idProperty = strtolower($classname) . 'Id';
$payment->setData(array(
$idProperty => $invoice->getId()
));
$response = $this->request(
$this->buildUrl($invoice, null, '/payments'), 'POST', $this->mapper->mapToStorage($payment)
);
return $this->mapper->mapFromStorage($response);
}
/**
* Send reminder
*
* @param Invoice $invoice
* @param InvoiceEnvelope $envelope
* @return ApiConnector
*/
public function remind(Invoice $invoice, InvoiceEnvelope $envelope)
{
$envelope->setData(array(
'invoiceId' => $invoice->getId()
));
$response = $this->request(
$this->buildUrl($invoice, null, '/send_reminder'), 'PUT', $this->mapper->mapToStorage($envelope)
);
return $this->mapper->mapFromStorage($response);
}
/**
* Get raw PDF content
*
* @return string
* @param PdfDocument $model
* @param AbstractModel $parent
*/
public function getPdf(PdfDocument $model, AbstractModel $parent = null)
{
return $this->request($this->buildUrl($model, $parent, null, 'pdf'), 'GET');
}
/**
* Build the url for the request
*
* @param AbstractModel $subject
* @param AbstractModel $parent
* @param string $appendUrl Filter url
* @param string $docType (pdf|xml|json)
* @return string
*/
protected function buildUrl(AbstractModel $subject, AbstractModel $parent = null, $appendUrl = null, $docType = null)
{
if (is_null($docType)) {
$docType = substr($this->mapper->getContentType(), strpos($this->mapper->getContentType(), '/') + 1);
}
$url = $this->baseUri;
if (!is_null($parent) && intval($parent->getId()) > 0) {
$url .= '/' . $this->mapTypeName($parent) . '/' . $parent->getId();
}
$url .= '/' . $this->mapTypeName($subject);
if (intval($subject->getId()) > 0) {
$url .= '/' . $subject->getId();
}
if (!is_null($appendUrl)) {
$url .= $appendUrl;
}
return $url . '.' . $docType;
}
/**
* Return the last errors
*
* @access public
* @return ErrorArray
*/
public function getErrors()
{
$errors = $this->errors;
$this->errors = new ErrorArray;
return $errors;
}
/**
* Maps object to an url-part
*
* @access protected
* @param AbstractModel $model
* @return string
*/
protected function mapTypeName(AbstractModel $model)
{
if ($model instanceof CurrentSession) {
$mapped = 'current_session';
} else {
$classname = $this->getType($model);
$mapped = str_replace(
array(
'\\',
'invoice_History',
'contact_Note',
), array(
'_',
'historie',
'note',
), lcfirst($classname)
);
if (false !== ($pos = strpos($mapped, '_'))) {
$mapped = substr($mapped, 0, $pos);
}
$mapped = strtolower(
preg_replace_callback('/([A-Z])/', array($this, 'classnameToUrlpartCallback'), $mapped)
) . 's';
}
return $mapped;
}
/**
* Callback to rewrite classname to url-part
*
* @param Array $match
* @return string
* @access protected
*/
protected function classnameToUrlpartCallback($match)
{
return '_' . strtolower($match[1]);
}
/**
* Get current session
*
* @return CurrentSession
*/
public function getCurrentSession()
{
if (is_null($this->currentSession)) {
$this->currentSession = $this->mapper->mapFromStorage(
$this->request($this->buildUrl(new CurrentSession()), 'GET')
);
}
if (!($this->currentSession instanceof CurrentSession)) {
$this->currentSession = null;
throw new NotLoggedInException('Authorization required');
}
return $this->currentSession;
}
/**
* Get sync status
*
* @param string $classname
* @return ArrayObject
*/
public function getSyncList($classname)
{
$classname = $classname . '\Sync';
$response = $this->request($this->buildUrl(new $classname(), null, '/sync_list_ids'), 'GET');
return $this->mapper->mapFromStorage($response);
}
/**
* Get objects by ids (array)
*
* @param string $classname
* @param Array $ids
* @return ArrayObject
*/
public function getByIds($classname, Array $ids)
{
$classname = $classname . '\Sync';
$classnameArray = $classname . '\ArrayObject';
$objects = new $classnameArray();
$objects->append(new $classname(array('id' => $ids)));
$response = $this->request(
$this->buildUrl(new $classname(), null, '/sync_fetch_ids'), 'POST', $this->mapper->mapToStorage($objects)
);
return $this->mapper->mapFromStorage($response);
}
/**
* Get object by id
*
* @param string $classname
* @param int $id
* @return AbstractModel
*/
public function getById($classname, $id)
{
if (!preg_match('/^[0-9]+$/D', $id)) {
throw new InvalidIdException('Invalid id: ' . $id);
}
$response = $this->request($this->buildUrl(new $classname(array('id' => $id))), 'GET');
return $this->mapper->mapFromStorage($response);
}
/**
* Get all objects
*
* @param string $classname
* @param string|integer $filter Filter name or id (advanced filters)
* @param AbstractModel $parent
* @return ArrayObject
* @throws InvalidFilterException
*/
public function getAll($classname, $filter = null, AbstractModel $parent = null)
{
$filterUrl = '';
if (!is_null($filter)) {
if (
isset($this->filters[$classname]) &&
in_array($filter, $this->filters[$classname])) {
$filterUrl = '/filter/' . $filter;
} elseif (
isset($this->filters[$classname]) &&
preg_match('/^[0-9]+$/D', $filter)) {
$filterUrl = '/filter/' . $filter;
} else {
$message = 'Unknown filter "' . $filter . '" for ' . $classname;
if (isset($this->filters[$classname])) {
$message .= '; available filters: ' . implode(', ', $this->filters[$classname]);
}
throw new InvalidFilterException($message);
}
}
$response = $this->request($this->buildUrl(new $classname(), $parent, $filterUrl), 'GET');
return $this->mapper->mapFromStorage($response);
}
/**
* Get an object by it's named id (customer_id, invoice_id)
*
* @param string $classname
* @param string $name
* @param string $id
* @return AbstractModel
* @throws InvalidNamedIdExeption
* @throws InvalidIdException
*/
public function getByNamedId($classname, $name, $id)
{
if (!isset($this->namedId[$classname]) || !in_array($name, $this->namedId[$classname])) {
throw new InvalidNamedIdExeption('NamedId ' . $name . ' is not a valid type');
}
if (!preg_match('/^[a-zA-Z0-9\- _]+$/D', $id)) {
throw new InvalidIdException('Invalid id: ' . $id);
}
$response = $this->request($this->buildUrl(new $classname(), null, '/' . $name . '/' . $id), 'GET');
return $this->mapper->mapFromStorage($response);
}
/**
* Settle the payments
*
* @param Payable $invoiceA
* @param Payable $invoiceB
* @param bool $sendEmail
* @throws InvalidStateException
* @throws UnableToSettleException
*/
public function settle(Payable $invoiceA, Payable $invoiceB, $sendEmail = false)
{
if ($invoiceA->state != 'open' && $invoiceA->state != 'late') {
throw new InvalidStateException('Invalid state for invoice '.$invoiceA->id);
}
if ($invoiceB->state != 'open' && $invoiceB->state != 'late') {
throw new InvalidStateException('Invalid state for invoice '.$invoiceB->id);
}
$typeA = $this->getType($invoiceA);
$typeB = $this->getType($invoiceB);
if ($typeA != $typeB) {
throw new UnableToSettleException('Unable to settle invoices, types are not equal');
}
if (
($invoiceA->totalUnpaid > 0 && $invoiceB->totalUnpaid > 0) ||
($invoiceA->totalUnpaid < 0 && $invoiceB->totalUnpaid < 0)
) {
throw new UnableToSettleException('Unable to settle invoices, signs are equal');
}
$price = min(abs($invoiceA->totalUnpaid), abs($invoiceB->totalUnpaid));
$paymentClassA = __NAMESPACE__.'\\'.$typeA.'\\Payment';
$paymentClassB = __NAMESPACE__.'\\'.$typeB.'\\Payment';
$paymentA = new $paymentClassA(array(
'paymentDate' => new DateTime(),
'paymentMethod' => 'credit_invoice',
'price' => ($invoiceA->totalUnpaid > 0 ? 1 : -1) * $price,
'sendEmail' => $sendEmail,
));
$paymentB = new $paymentClassB(array(
'paymentDate' => new DateTime(),
'paymentMethod' => 'credit_invoice',
'price' => ($invoiceB->totalUnpaid > 0 ? 1 : -1) * $price,
'sendEmail' => $sendEmail,
));
$invoiceA->registerPayment($this->getService($typeA), $paymentA);
$invoiceB->registerPayment($this->getService($typeB), $paymentB);
}
/**
* Build a service object for contacts, invoices, etc
* @param string $type
* @return Service
*/
public function getService($type)
{
if (!isset($this->services[$type])) {
if (!file_exists(__DIR__ . '/' . $type . '/Service.php')) {
throw new InvalidServiceTypeException('No service for type ' . $type);
}
$classname = __NAMESPACE__ . '\\' . $type . '\Service';
$this->services[$type] = new $classname($this);
}
return $this->services[$type];
}
/**
* Checks if service name is a valid service
* @param string $type
* @return boolean
*/
public function hasService($type) {
if (!isset($this->services[$type])) {
if (!file_exists(__DIR__.'/'.$type.'/Service.php')) {
return false;
}
}
return true;
}
/**
* Determine the type of $model
* @param AbstractModel $model
* @return string
*/
protected function getType(AbstractModel $model)
{
$types = array(
'Contact',
'Invoice',
'Estimate',
'IncomingInvoice',
'RecurringTemplate',
'CurrentSession',
'TaxRate',
'Product',
'Contact\Sync',
'Contact\Note',
'Invoice\History',
);
foreach ($types as $type) {
$classname = __NAMESPACE__ . '\\' . $type;
if ($model instanceof $classname) {
return $type;
}
}
return substr(get_class($model), strlen(__NAMESPACE__) + 1);
}
}