-
Notifications
You must be signed in to change notification settings - Fork 0
/
RESTModel.php
69 lines (56 loc) · 1.73 KB
/
RESTModel.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
<?php
namespace caminstech\rest;
use Yii;
abstract class RESTModel extends \yii\base\Model
{
private $isNewRecord = true;
abstract protected static function getClient();
abstract protected static function getUrl();
public static function primaryKey()
{
return 'id';
}
protected static function getViewUrl($id)
{
return static::getUrl().'/'.$id;
}
protected static function getListUrl()
{
return static::getUrl();
}
public function getIsNewRecord()
{
return $this->isNewRecord;
}
public static function findById($id)
{
$response = static::getClient()->get(self::getViewUrl($id), $validCodes = [ RESTClient::HTTP_OK, RESTClient::HTTP_NOT_FOUND ]);
if ($response['code'] == RESTClient::HTTP_NOT_FOUND) {
return null;
}
$response['data'] = json_decode($response['data'], true);
$classname = self::className();
$model = new $classname();
foreach($response['data'] as $attribute => $value) {
$model->$attribute = $value;
}
$model->isNewRecord = false;
return $model;
}
public static function findAll()
{
$response = static::getClient()->get(self::getListUrl(), $validCodes = [ RESTClient::HTTP_OK ]);
$response['data'] = json_decode($response['data'], true);
$models = [];
$classname = self::className();
foreach($response['data'] as $elem) {
$model = new $classname();
foreach($elem as $attribute => $value) {
$model->$attribute = $value;
}
$model->isNewRecord = false;
$models[] = $model;
}
return $models;
}
}