-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseRepository.php
125 lines (107 loc) · 2.76 KB
/
BaseRepository.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
<?php namespace Devtools;
abstract class BaseRepository
{
protected $connection;
protected $log;
protected $table;
protected $fillable;
protected $required;
protected $primaryKey;
protected $primaryName;
protected $data;
protected $count;
protected $query;
public function __get($property)
{
return !isset($this->data) || in_array($property, array_keys($this->data))
? $this->data[$property]
: null;
}
public function __set($property, $value)
{
$this->data[$property] = $value;
}
public function reset()
{
$this->query = '';
$this->data = array();
$this->params = null;
}
public function find($id)
{
$this->loadQueryStringIfEmpty();
return $this->findBy($id);
}
public function findBy($filter = null)
{
if (is_null($filter)) {
return $this->all();
}
if (is_numeric($filter)) {
$filter = array($this->primaryKey, '=', $filter);
}
if (is_string($filter)) {
$filter = array($this->primaryName, '=', $filter);
}
$this->all()->where($filter);
return $this;
}
public function findOrFail($filter = null)
{
return $this->findBy($filter)->orFail();
}
public function orFail()
{
$result = $this->get();
if (empty($result) || !$result) {
throw new \Exception('Query failed or result is empty.');
}
return $result;
}
public function count()
{
$this->count = count($this->get());
return $this->count;
}
public static function stringify($array, $force = false, $quotation="'")
{
$ret = "";
if (!is_array($array)) {
$array = array($array);
}
foreach ($array as $element) {
if (!empty($ret)) {
$ret .= ",";
}
$ret .= (!$force && is_numeric($element))
? $element
: $quotation.$element.$quotation;
}
return $ret;
}
public static function stripWhitespace($dirty)
{
return Format::stripWhitespace($dirty);
}
public static function reduceResult($result)
{
if (is_array($result) && (count($result) == 1)) {
reset($result);
return self::reduceResult($result[key($result)]);
} else {
return $result;
}
}
protected function apply(Array $values)
{
foreach ($values as $field => $value) {
$this->data[$field] = $value;
}
}
private function loadQueryStringIfEmpty()
{
if (empty($this->queryString)) {
$this->all();
}
}
}