Skip to content

Commit

Permalink
Merge pull request #21 from Mello21century/bug-trowable-request-fix
Browse files Browse the repository at this point in the history
Fix in exception in form request classes if the php failed to get rules
  • Loading branch information
kevincobain2000 committed Oct 11, 2021
2 parents 807980f + 70d67c6 commit 319837e
Showing 1 changed file with 38 additions and 4 deletions.
42 changes: 38 additions & 4 deletions src/LaravelRequestDocs.php
Expand Up @@ -37,7 +37,7 @@ public function getDocs()
return array_filter($docs);
}

public function sortDocs(array $docs, $sortBy = 'default'): Array
public function sortDocs(array $docs, $sortBy = 'default'): array
{
if ($sortBy === 'route_names') {
sort($docs);
Expand Down Expand Up @@ -72,7 +72,7 @@ public function sortDocs(array $docs, $sortBy = 'default'): Array
return $sorted;
}

public function getControllersInfo(): Array
public function getControllersInfo(): array
{
$controllersInfo = [];
$routes = collect(Route::getRoutes());
Expand Down Expand Up @@ -105,7 +105,7 @@ public function getControllersInfo(): Array
return $controllersInfo;
}

public function appendRequestRules(Array $controllersInfo)
public function appendRequestRules(array $controllersInfo)
{
foreach ($controllersInfo as $index => $controllerInfo) {
$controller = $controllerInfo['controller_full_path'];
Expand All @@ -125,7 +125,11 @@ public function appendRequestRules(Array $controllersInfo)
//throw $th;
}
if ($requestClass instanceof FormRequest) {
$controllersInfo[$index]['rules'] = $this->flattenRules($requestClass->rules());
try {
$controllersInfo[$index]['rules'] = $this->flattenRules($requestClass->rules());
} catch (\ErrorException $th) {
$controllerInfo[$index]['rules'] = $this->rulesByRegex($requestClassName);
}
$controllersInfo[$index]['docBlock'] = $this->lrdDocComment($reflectionMethod->getDocComment());
}
}
Expand Down Expand Up @@ -184,4 +188,34 @@ public function flattenRules($mixedRules)

return $rules;
}

public function rulesByRegex($requestClassName)
{
$data = new ReflectionMethod($requestClassName, 'rules');
$lines = file($data->getFileName());
$rules = [];
for ($i = $data->getStartLine() - 1; $i <= $data->getEndLine() - 1; $i++) {
preg_match_all("/(?:'|\").*?(?:'|\")/", $lines[$i], $matches);
$rules[] = $matches;
}

$rules = collect($rules)
->filter(function ($item) {
return count($item[0]) > 0;
})
->transform(function ($item) {
$fieldName = Str::of($item[0][0])->replace(['"', "'"], '');
$definedFieldRules = collect(array_slice($item[0], 1))->transform(function ($rule) {
return Str::of($rule)->replace(['"', "'"], '')->__toString();
})->toArray();

return ['key' => $fieldName, 'rules' => $definedFieldRules];
})
->keyBy('key')
->transform(function ($item) {
return $item['rules'];
})->toArray();

return $rules;
}
}

0 comments on commit 319837e

Please sign in to comment.