1 <?php
2
3 namespace Docolight\Support;
4
5 use CActiveRecord;
6 use Docolight\Http\Contracts\Arrayable;
7
8 /**
9 * You want to send your CActiveRecord implementation to a json response? Use this class.
10 *
11 * ```php
12 *
13 * // Get a model
14 * $model = MyModel::model()->findByPk(1);
15 *
16 * // Wrap your model
17 * $wrapper = new ActiveRecordWrapper($model);
18 *
19 * // Get a JsonResponse instance
20 * $response = container('response')->produce('json');
21 *
22 * // Set response body
23 * $response->setBody($wrapper);
24 *
25 * // Send response to client
26 * $response->send();
27 *
28 * // To send your json request in a short way, you can use `response()` function
29 * response('json', 200, $wrapper)->send();
30 * ```
31 *
32 * @author Krisan Alfa Timur <krisanalfa@docotel.co.id>
33 */
34 class ActiveRecordWrapper implements Arrayable
35 {
36 /**
37 * Our model implementation
38 *
39 * @var CActiveRecord
40 */
41 protected $model;
42
43 /**
44 * Initialize the class.
45 *
46 * @param \CActiveRecord $default Default attribute inside this class
47 */
48 public function __construct(CActiveRecord $model)
49 {
50 $this->fill($model);
51 }
52
53 /**
54 * Initialize the class statically.
55 *
56 * @param \CActiveRecord $default Default attribute inside this class
57 */
58 public static function make(CActiveRecord $model)
59 {
60 return new static($model);
61 }
62
63 /**
64 * {@inheritdoc}
65 */
66 public function castToArray()
67 {
68 return Arr::arToArray($this->model);
69 }
70
71 /**
72 * {@inheritdoc}
73 */
74 public function fill($model)
75 {
76 $this->innerFill($model);
77 }
78
79 /**
80 * Inner fill to maintain type hint.
81 *
82 * @param \CActiveRecord $model
83 *
84 * @return void
85 */
86 protected function innerFill(CActiveRecord $model)
87 {
88 $this->model = $model;
89 }
90 }
91