Skip to content

Instantly share code, notes, and snippets.

@devgnx
Created September 30, 2020 04:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devgnx/93b7c35ab19f0ceb87d7ab19f292dab4 to your computer and use it in GitHub Desktop.
Save devgnx/93b7c35ab19f0ceb87d7ab19f292dab4 to your computer and use it in GitHub Desktop.
Symfony Request using illuminate/validation
<?php
namespace App\Request;
use Domain\Shared\MagicGetterSetter;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Factory as ValidatorFactory;
use Symfony\Component\HttpFoundation\FileBag;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\ServerBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* @var ParameterBag $attributes
* @var InputBag|ParameterBag $request
* @var InputBag $query
* @var ServerBag $server
* @var FileBag $files
* @var InputBag $cookies
* @var HeaderBag $headers
* @method initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
* @method createFromGlobals()
* @method create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null)
* @method setFactory(?callable $callable)
* @method duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
* @method overrideGlobals()
* @method setTrustedProxies(array $proxies, int $trustedHeaderSet)
* @method getTrustedProxies()
* @method getTrustedHeaderSet()
* @method setTrustedHosts(array $hostPatterns)
* @method getTrustedHosts()
* @method normalizeQueryString(?string $qs)
* @method enableHttpMethodParameterOverride()
* @method getHttpMethodParameterOverride()
* @method get(string $key, $default = null)
* @method getSession()
* @method hasPreviousSession()
* @method hasSession()
* @method setSession(SessionInterface $session)
* @method setSessionFactory(callable $factory)
* @method getClientIps()
* @method getClientIp()
* @method getScriptName()
* @method getPathInfo()
* @method getBasePath()
* @method getBaseUrl()
* @method getScheme()
* @method getPort()
* @method getUser()
* @method getPassword()
* @method getUserInfo()
* @method getHttpHost()
* @method getRequestUri()
* @method getSchemeAndHttpHost()
* @method getUri()
* @method getUriForPath(string $path)
* @method getRelativeUriForPath(string $path)
* @method getQueryString()
* @method isSecure()
* @method getHost()
* @method setMethod(string $method)
* @method getMethod()
* @method getRealMethod()
* @method getMimeType(string $format)
* @method getMimeTypes(string $format)
* @method getFormat(?string $mimeType)
* @method setFormat(?string $format, $mimeTypes)
* @method getRequestFormat(?string $default = 'html')
* @method setRequestFormat(?string $format)
* @method getContentType()
* @method setDefaultLocale(string $locale)
* @method getDefaultLocale()
* @method setLocale(string $locale)
* @method getLocale()
* @method isMethod(string $method)
* @method isMethodSafe()
* @method isMethodIdempotent()
* @method isMethodCacheable()
* @method getProtocolVersion()
* @method getContent(bool $asResource = false)
* @method getETags()
* @method isNoCache()
* @method getPreferredFormat(?string $default = 'html'): ?string
* @method getPreferredLanguage(array $locales = null)
* @method getLanguages()
* @method getCharsets()
* @method getEncodings()
* @method getAcceptableContentTypes()
* @method isXmlHttpRequest()
* @method preferSafeContent(): bool
* @method isFromTrustedProxy()
*/
abstract class BaseRequest
{
use MagicGetterSetter;
protected Request $httpRequest;
public function __construct(RequestStack $request)
{
$currentRequest = $request->getCurrentRequest();
if (!($currentRequest instanceof Request)) {
dump($request);
throw new \Exception('Invalid request'); // TODO throw propper exception
}
$this->httpRequest = $currentRequest;
$this->validate();
}
public function request()
{
return $this->httpRequest;
}
abstract public function rules(): array;
public function messages(): array
{
return [];
}
public function all()
{
$data = $this->httpRequest->request->all();
if (Request::METHOD_GET === $this->httpRequest->getMethod()) {
$data = $this->httpRequest->query->all();
}
return $data;
}
public function validate()
{
$this->validateArray($this->all(), $this->rules(), $this->messages());
}
/**
* Validate array of data with given rules
*/
public function validateArray(array $source, array $rules, array $messages)
{
$translator = new Translator(new ArrayLoader(), 'en_US');
$validatorFactory = new ValidatorFactory($translator);
$validator = $validatorFactory->make($source, $rules, $messages);
if ($validator->fails()) {
throw new ValidationException($validator);
}
}
/**
* Get/Set property or methods
*
* @param string $name
* @param mixed $arguments
* @return $this|void
*/
public function __call($name, $arguments)
{
$is_getter = preg_match('/^get/', $name);
$is_setter = preg_match('/^set/', $name);
$property = lcfirst(preg_replace('/^(g|s)et/', '', $name));
if (!$is_getter && !$is_setter) {
$is_getter = true;
}
if (property_exists($this->httpRequest, $property)) {
if ($is_getter) {
return $this->httpRequest->{$property};
} else if (array_key_exists(0, $arguments)) {
$this->httpRequest->{$property} = $arguments[0];
return $this;
} else {
throw new \BadMethodCallException("for " . __CLASS__ . "::{$name}()");
}
}
throw new \BadMethodCallException();
}
public function isJsonRequest(Request $request)
{
return 'json' === $request->getContentType();
}
}
@devgnx
Copy link
Author

devgnx commented Sep 30, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment