laravel-openapi icon indicating copy to clipboard operation
laravel-openapi copied to clipboard

generate a parameterFactory from a validation request - suggestion of feature

Open Grummfy opened this issue 3 years ago • 0 comments

Hello, To ease my process I have created the start of a command to generate Parameters from a validation request. I think it could be interesting to perhaps add this feature? But, if someone need it or my example could bootstrap something, here is my code (with the possibility of overwrite in mind)

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Routing\Route;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\ValidationRuleParser;
use Illuminate\Validation\Validator;
use Symfony\Component\Console\Input\InputOption;

class ParametersFactoryMakeCommand extends GeneratorCommand
{
	protected $name = 'mm:make-parameters';
	protected $description = 'Create a new Parameters factory class based on an existing request class';
	protected $type = 'Parameters';

	// @see https://laravel.com/docs/9.x/validation#available-validation-rules
	protected array $mapRules = [
		// @see https://swagger.io/docs/specification/data-models/data-types/
		'Numeric' => ['schema.type' => 'number'],
		'Integer' => ['schema.type' => 'integer'],
		'String' => ['schema.type' => 'string'],
		'Boolean' => ['schema.type' => 'boolean'],
		'Array' => 'mapRuleArray',

		// @see https://swagger.io/docs/specification/describing-parameters/
		'Required' => ['required' => true, 'allowEmptyValue' => false],
		'Present' => ['allowEmptyValue' => true],
		'Prohibited' => ['allowEmptyValue' => true],
		'Filled' => ['allowEmptyValue' => false],
		'Nullable' => ['nullable' => true],
		'In' => 'mapRuleIn',
	];

	protected function getOptions(): array
	{
		return [
			['request', 'r', InputOption::VALUE_OPTIONAL, 'The request class parameters being generated for'],
			['force', null, InputOption::VALUE_NONE, 'Create the class even if the factory already exists'],
			['route', 'R', InputOption::VALUE_OPTIONAL, 'The route name associated to'],
			['action', 'a', InputOption::VALUE_OPTIONAL, 'The route action associated to'],
		];
	}

	protected function getStub(): string
	{
		return resource_path('/stubs/openAPI/parameters.stub');
	}

	protected function buildClass($name)
	{
		$output = parent::buildClass($name);

		$fields = $this->extractFieldFromRequest($this->option('request'));
		$fields += $this->extractFieldFromRouteName($this->option('route'));
		$fields += $this->extractFieldFromRouteAction($this->option('action'));

		$output = $this->buildClassFromFieldsInfos($output, $fields);

		return $output;
	}

	protected function buildClassFromFieldsInfos(string $output, array $fields): string
	{
		$definition = [''];
		$spacer = '			';
		foreach ($fields as $field)
		{
			$definition []= $spacer . $this->assembleField($this->renderField($field, $spacer));
		}

		return str_replace('DummyDefinition', implode(PHP_EOL, $definition), $output);
	}

	protected function getDefaultNamespace($rootNamespace): string
	{
		return $rootNamespace . '\OpenApi\Parameters';
	}

	protected function qualifyClass($name): string
	{
		$name = parent::qualifyClass($name);

		if (Str::endsWith($name, 'Parameters'))
		{
			return $name;
		}

		return $name . 'Parameters';
	}

	protected function buildValidatorFromRequest(string $request): Validator
	{
		try
		{
			/** @var FormRequest $request */
			$request = app($request);
		}
		catch (ValidationException $e)
		{
			return $e->validator;
		}

		// if build of validation doesn't generate any error, we try to build the validator
		// see \Illuminate\Foundation\Http\FormRequest::getValidatorInstance
		/** @var ValidationFactory $factory */
		$factory = app(ValidationFactory::class);
		if (method_exists($request, 'validator'))
		{
			$validator = app()->call([$request, 'validator'], compact('factory'));
		}
		else
		{
			$validator = $factory->make(
				[],
				app()->call([$request, 'rules']),
				$request->messages(),
				$request->attributes(),
			);
		}

		return $validator;
	}

	private function extractRulesFromRequest(string $request): array
	{
		$validator = $this->buildValidatorFromRequest($request);
		$rules = [];
		if (method_exists($validator, 'getRules'))
		{
			$rules = call_user_func([$validator, 'getRules']);
		}
		return $rules;
	}

	protected function mapRule(string $field, string $attribute, string $rule, array $parameters, array $attributeRules): array
	{
		if (array_key_exists($rule, $this->mapRules))
		{
			if (is_array($this->mapRules[ $rule ]))
			{
				return $this->mapRules[$rule];
			}

			return $this->{$this->mapRules[ $rule ]}($field, $attribute, $rule, $parameters, $attributeRules);
		}

		return [];
	}

	protected function mapRuleIn(string $field, string $attribute, string $rule, array $parameters, array $attributeRules): array
	{
		return ['schema.enum' => $parameters];
	}

	protected function mapRuleArray(string $field, string $attribute, string $rule, array $parameters, array $attributeRules): array
	{
		// TODO type array or object => see $attributeRules
		return ['schema.type' => 'array'];
	}

	protected function mapRulesToField(array $fields, string $field, string $attribute, array $attributeRules): array
	{
		foreach ($attributeRules as $rule)
		{
			[$rule, $parameters] = ValidationRuleParser::parse($rule);
			if ($rule === '')
			{
				continue;
			}

			$ruleMapped = $this->mapRule($field, $attribute, $rule, $parameters, $attributeRules);
			$fields[ $field ] = $ruleMapped + $fields[ $field ];
		}

		return $fields;
	}

	protected function renderField(array $field, string $spacer): array
	{
		$field = Arr::undot($field);

		$output = [
			$spacer . 'Parameter::query()',
			$spacer . '	->name(\'' . $field['name'] . '\')',
		];

		if (array_key_exists('required', $field))
		{
			$output []= $spacer . '	->required(' . ($field['required'] ? 'true' : 'false') . ')';
		}

		if (array_key_exists('allowEmptyValue', $field))
		{
			$output []= $spacer . '	->allowEmptyValue(' . ($field['allowEmptyValue'] ? 'true' : 'false') . ')';
		}

		if (array_key_exists('schema', $field))
		{
			$schema = $field['schema'];
			$output []= $spacer . '	->schema(';
			$output = array_merge($output, $this->renderFieldSchema($schema, $spacer . '		'));
			$output []= $spacer . '	)';
		}

		return $output;
	}

	private function assembleField(array $renderField): string
	{
		return '$parameters [] = ' . implode(PHP_EOL, $renderField) . ';';
	}

	protected function renderFieldSchema(array $schema, string $spacer): array
	{
		$output = [];
		$output []= $spacer . 'Schema::' . $schema['type'] . '()';
		if (array_key_exists('enum', $schema))
		{
			$output []= $spacer . '	->enum(' . var_export($schema['enum'], true) . ')';
		}

		return $output;
	}

	protected function extractFieldFromRequest(?string $request): array
	{
		if (!$request)
		{
			return [];
		}

		if (!is_a($request, FormRequest::class, true))
		{
			throw new \InvalidArgumentException('Invalid request, it must be a FormRequest');
		}

		// extract rules from request validator
		$rules = $this->extractRulesFromRequest($request);

		// @see \Illuminate\Validation\Validator::passes
		$fields = [];
		foreach ($rules as $attribute => $attributeRules)
		{
			$field = explode('.', $attribute)[0];
			$fields[ $field ] = $fields[ $field ] ?? ['name' => $field];

			$fields = $this->mapRulesToField($fields, $field, $attribute, $attributeRules);
		}

		return $fields;
	}

	protected function extractFieldFromRouteName(?string $routeName): array
	{
		if (!$routeName)
		{
			return [];
		}

		$route = app('router')->getByName($routeName);
		return $route ? $this->routeToFields($route) : [];
	}

	protected function extractFieldFromRouteAction(?string $action): array
	{
		if (!$action)
		{
			return [];
		}

		$router = app('router')->getRoutes();
		$route = $router->getByAction($action) ?? $router->getByAction('App\\Http\\Controllers\\' . $action);
		return $route ? $this->routeToFields($route) : [];
	}

	protected function routeToFields(Route $route): array
	{
		// $parameters = $route->parameterNames(); // don't give optional parameters
		preg_match_all('/{(.*?)}/', $route->uri, $parameters);
		$parameters = collect($parameters[1]);
		if (count($parameters) > 0)
		{
			$parameters = $parameters->mapWithKeys(static fn ($parameter) => [Str::replaceLast('?', '', $parameter) => [
				'name' => Str::replaceLast('?', '', $parameter),
				'required' => ! Str::endsWith($parameter, '?'),
			]]);
		}

		/** @var \ReflectionParameter $signatureParameter */
		foreach ($route->signatureParameters() as $signatureParameter)
		{
			$parameter = $parameters[ $signatureParameter->getName() ] ?? [
				'name' => $signatureParameter->getName(),
				'required' => $signatureParameter->isOptional(),
			];

			if ($signatureParameter->hasType())
			{
				$type = ucFirst($signatureParameter->getType()->getName());
				if (is_a($type, FormRequest::class, true))
				{
					$parameters = $parameters->union($this->extractFieldFromRequest($type));
					$parameters->offsetUnset($signatureParameter->getName());
					continue;
				}

				if (array_key_exists($type, $this->mapRules) && is_array($this->mapRules[$type]))
				{
					$parameter['type'] = $this->mapRules[$type];
				}
			}

			if (!$parameter['required'])
			{
				$parameter['allowEmptyValue'] = $signatureParameter->isOptional() || $signatureParameter->allowsNull() || $signatureParameter->isDefaultValueAvailable();
			}

			$parameters->put($signatureParameter->getName(), $parameter);
		}

		return $parameters->toArray();
	}
}


Grummfy avatar Aug 23 '22 17:08 Grummfy