-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathModels.php
220 lines (185 loc) · 6.08 KB
/
Models.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
<?php
namespace LangleyFoxall\Helpers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* Class Models.
*/
abstract class Models
{
/**
* Returns a collection of class names for all Eloquent models within your app path.
*
* @return \Illuminate\Support\Collection
*/
public static function all()
{
$command = 'grep --include="*.php" --files-with-matches -r "class" '.app_path();
exec($command, $files);
return collect($files)->map(function ($file) {
return self::convertFileToClass($file);
})->filter(function ($class) {
return class_exists($class) && is_subclass_of($class, Model::class);
});
}
/**
* Converts a file name to a namespaced class name.
*
* @param string $file
*
* @return string
*/
private static function convertFileToClass(string $file)
{
$fh = fopen($file, 'r');
$namespace = '';
while (($line = fgets($fh, 5000)) !== false) {
if (str_contains($line, 'namespace')) {
$namespace = trim(str_replace(['namespace', ';'], '', $line));
break;
}
}
fclose($fh);
$class = basename(str_replace('.php', '', $file));
return $namespace.'\\'.$class;
}
/**
* UTF-8 encodes the attributes of a model.
*
* @param Model $model
*
* @return Model
*/
public static function utf8EncodeModel(Model $model)
{
foreach ($model->toArray() as $key => $value) {
if (is_numeric($value) || !is_string($value)) {
continue;
}
$model->$key = utf8_encode($value);
}
return $model;
}
/**
* UTF-8 encodes the attributes of a collection of models.
*
* @param Collection $models
*
* @return Collection
*/
public static function utf8EncodeModels(Collection $models)
{
return $models->map(function ($model) {
return self::utf8EncodeModel($model);
});
}
/**
* Gets an array of the columns in this model's database table.
*
* @param Model $model
*
* @return mixed
*/
public static function getColumns(Model $model)
{
return Schema::getColumnListing($model->getTable());
}
/**
* Gets the next auto-increment id for a model.
*
* @param Model $model
*
* @throws \Exception
*
* @return int
*/
public static function getNextId(Model $model)
{
$statement = DB::select('show table status like \''.$model->getTable().'\'');
if (!isset($statement[0]) || !isset($statement[0]->Auto_increment)) {
throw new \Exception('Unable to retrieve next auto-increment id for this model.');
}
return (int) $statement[0]->Auto_increment;
}
/**
* Check if any number of models are related to each other.
*
* @param Model[]|array[] $relations
*
* @throws \InvalidArgumentException|\Exception
*
* @return bool
*/
public static function areRelated(...$relations)
{
try {
$max_key = count($relations) - 1;
foreach ($relations as $key => $current) {
if (!is_array($current)) {
$previous = null;
if ($key > 0) {
$previous = $relations[$key - 1];
$previous = is_array($previous)
? $previous[0] : $previous;
}
$basename = strtolower(class_basename($current));
$method = Str::plural($basename);
if (!is_null($previous)) {
if (!method_exists($previous, $method)) {
$method = Str::singular($basename);
}
if (!method_exists($previous, $method)) {
throw new \Exception('UNABLE_TO_FIND_RELATIONSHIP');
}
}
$relations[$key] = [$current, $method];
}
if (!($relations[$key][0] instanceof Model)) {
throw new \InvalidArgumentException('INVALID_MODEL');
}
}
foreach ($relations as $key => $current) {
if ($key !== $max_key) {
$model = $current[0];
$relation = $relations[$key + 1];
$model->{$relation[1]}()->findOrFail($relation[0]->id);
}
}
return true;
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return false;
}
}
/**
* @param Collection|string $models Either a collection of Model's or a String representation of a Model.
* @param string $column
* @param int $maxCap Enter this is the weights are odds (Eg: Weight = 1, $maxCap = 1000 for one in a thousand.)
* @param object $ifLose If you've entered a maxCap, set what gets returned if nothing gets hit.
*
* @return Model $model
*/
public static function randomByWeightedValue($models, $column, $maxCap = null, $ifLose = null)
{
//If model string is passed in, get all model instances.
if (is_string($models)) {
$models = $models::whereNotNull($column)->get();
}
$indexToWeightArray = [];
foreach ($models as $index => $weightedBucket) {
$indexToWeightArray[$index] = $weightedBucket->$column;
}
$rand = mt_rand(1, $maxCap ?: (int) array_sum($indexToWeightArray));
$modelIndex = null;
foreach ($indexToWeightArray as $index => $value) {
$rand -= $value;
if ($rand <= 0) {
$modelIndex = $index;
break;
}
}
return $models[$modelIndex] ?? $ifLose;
}
}