-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitPutPatchVerbs.php
More file actions
73 lines (55 loc) · 2.19 KB
/
Copy pathSplitPutPatchVerbs.php
File metadata and controls
73 lines (55 loc) · 2.19 KB
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
<?php
namespace Softonic\RestApiNestedResources\Http\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
use Softonic\RestApiNestedResources\Models\MultiKeyModel;
trait SplitPutPatchVerbs
{
use PathParameters;
public function update(Request $request)
{
$parameters = $this->getPathParameters($request);
if ($request->isMethod('PATCH')) {
try {
$parameters = $this->bindModelParameters($parameters);
} catch (ModelNotFoundException $e) {
throw new ModelNotFoundException(
"{$e->getModel()} resource not found for " . json_encode($parameters, JSON_THROW_ON_ERROR)
);
}
return App::call([$this, 'modify'], $parameters);
}
return App::call([$this, 'replace'], $parameters);
}
private function bindModelParameters(array $parameters): array
{
$methodArguments = new ReflectionMethod(self::class, 'modify')->getParameters();
$modelMethodArguments = array_filter(
$methodArguments,
function (ReflectionParameter $argument): bool {
if ($argument->getType() && !$argument->getType()->isBuiltin()) {
$class = new ReflectionClass($argument->getType()->getName());
return $class->isSubclassOf(Model::class);
}
return false;
}
);
if (!empty($modelMethodArguments[0])) {
$modelMethodArgument = $modelMethodArguments[0];
$className = $modelMethodArgument->getType()->getName();
$instance = \App::make($className);
$id = ($instance instanceof MultiKeyModel) ? $instance::generateIdForField(
$instance->getKeyName(),
$parameters
) : $parameters[$instance->getKeyName()];
$modelArgument = $instance::findOrFail($id);
$parameters = [$className => $modelArgument];
}
return $parameters;
}
}