Improve code quality while utilizing Guzzle in Laravel - laravel

I am new with laravel so please don't be harsh.
I am bulding a simple web which connects to an external API(several endpoints) via Guzzle,fetching some data,cleaning them and storing them.
At the moment -and from one endpoint- i have something the following Job:
public function handle(Client $client)
{
try {
$request= $client->request('GET', 'https://api.url./something', [
'headers' => [
'X-RapidAPI-Key'=> env("FOOTBALL_API_KEY"),
'Accept' => 'application/json'
]
]);
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
foreach ($val['leagues'] as $id) {
League::firstOrCreate(collect($id)->except(['coverage'])->toArray());
}
}
} catch (GuzzleException $e) {
};
}
Therefore i would like some code recommendations, how can i make my code better from design point of view.
My thoughts are:
a)Bind Guzzle as service provider.
b)use a design pattern for implementing calls to endpoints.URI builder maybe?
Any assistance will be appreciated.
May the force be with you.

Detailed feedback
Some pointers specific to the provided code itself:
A guzzle client request returns a response, which does not match the name of the parameter you assign it to
Calls to json_decode can fail in which case they'll return null. In terms of defensive programming it's good to check for those fail cases
Your case makes some assumptions about the data in the response. It's best to check if the response is in the actual format you expect before using it.
You catch all GuzzleExceptions, but do nothing in those cases. I think you could improve this by either:
Logging the exception
Throwing another exception which you will catch at a class, calling the handle() method
Both of the options above
You could choose to inject the api key, rather than fetching it directly via the env() method. This will prevent issues described in the warning block here
General feedback
It feels like your code is mixing responsibilities, which is considered bad practice. The handle() method now does the following:
Send API requests
Decode API requests
Validate API responses
Parse API responses
Create models
You could consider moving some or all of these to separate classes, like so:
ApiClient which is responsible for sending out requests
ResponseDecoder which is responsible for turning a response into \stdClass
ResponseValidator which is responsible for checking if the response has the expected data structure
RepsonseParser which is responsible for turning the response \stdClass into collections
LeagueFactory which is responsible for turning collections into League models
One could argue that the first four classes should be put into a single class called ApiClient. That's purely up to you.
So in the end you would come up with something like this:
<?php
namespace App\Example;
use Psr\Log\LoggerInterface;
class LeagueApiHandler
{
/**
* #var ApiClient
*/
private $apiClient;
/**
* #var ResponseDecoder
*/
private $decoder;
/**
* #var ResponseValidator
*/
private $validator;
/**
* #var ResponseParser
*/
private $parser;
/**
* #var LeagueFactory
*/
private $factory;
/**
* #var LoggerInterface
*/
private $logger;
public function __construct(
ApiClient $apiClient,
ResponseDecoder $decoder,
ResponseValidator $validator,
ResponseParser $parser,
LeagueFactory $factory,
LoggerInterface $logger
) {
$this->apiClient = $apiClient;
$this->decoder = $decoder;
$this->validator = $validator;
$this->parser = $parser;
$this->factory = $factory;
$this->logger = $logger;
}
public function handle()
{
try {
$response = $this->apiClient->send();
} catch (\RuntimeException $e) {
$this->logger->error('Unable to send api request', $e->getMessage());
return;
};
try {
$decodedResponse = $this->decoder->decode($response);
} catch (\RuntimeException $e) {
$this->logger->error('Unable to decode api response');
return;
};
if (!$this->validator->isValid($decodedResponse)) {
$this->logger->error('Unable to decode api response');
return;
}
$collections = $this->parser->toCollection($decodedResponse);
foreach ($collections as $collection) {
$this->factory->create($collection);
}
}
}
namespace App\Example;
use GuzzleHttp\Client;
class ApiClient
{
/**
* #var Client
*/
private $client;
/**
* #var string
*/
private $apiKey;
public function __construct(Client $client, string $apiKey)
{
$this->client = $client;
$this->apiKey = $apiKey;
}
public function send()
{
try {
return $this->client->request('GET', 'https://api.url./something', [
'headers' => [
'X-RapidAPI-Key' => $this->apiKey,
'Accept' => 'application/json'
]
]);
} catch (GuzzleException $e) {
throw new \RuntimeException('Unable to send request to api', 0, $e);
};
}
}
namespace App\Example;
use Psr\Http\Message\ResponseInterface;
class ResponseDecoder
{
public function decode(ResponseInterface $response): \stdClass
{
$response = json_decode($response->getBody()->getContents(), true);
if ($response === null) {
throw new \RuntimeException('Unable to decode api response');
}
return $response;
}
}
namespace App\Example;
class ResponseValidator
{
public function isValid(\stdClass $response): bool
{
if (is_array($response) === false) {
return false;
}
foreach ($response as $array) {
if (!isset($array['leagues'])) {
return false;
}
}
return true;
}
}
namespace App\Example;
use Illuminate\Support\Collection;
class ResponseParser
{
/**
* #param \stdClass $response
* #return Collection[]
*/
public function toCollection(\stdClass $response): array
{
$collections = [];
foreach ($response as $array => $val) {
foreach ($val['leagues'] as $id) {
$collections[] = collect($id)->except(['coverage'])->toArray();
}
}
return $collections;
}
}
namespace App\Example;
use Illuminate\Support\Collection;
class LeagueFactory
{
public function create(Collection $collection): void
{
League::firstOrCreate($collection);
}
}

Related

Laravel Http client before request send add headers

I'm using Http client for making outgoing HTTP requests. I've used it many places in the project.Now project has new requirement that I have to add a new header to every outgoing
requests. I can do this by adding it to every places. But I want to know , is there any kind of trigger or event which can give me ability to modify the headers just before the request send. There is an event Illuminate\Http\Client\Events\RequestSending which is only useful for inspecting the request.
This is possible to achieve without the need of a package. You can simple do something like this in a service provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Client\Factory as Http;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->extend(Http::class, function ($service, $app) {
return $service->withOptions(['foo' => 'bar']);
});
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
}
Yes, this is possible with a fantastic package here. After installing the package you just set the default headers like,
Http::withDefaultOptions([
'headers' => [
'X-Bar-Header' => 'bar'
],
]);
But I was unfortunate, the package was not installed with my laravel 9-dev. So I had to extract the code for me. First, create a Factory class in your app\HttpClient directory,
<?php
namespace App\HttpClient;
use Illuminate\Http\Client\Factory as BaseFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Arr;
class Factory extends BaseFactory
{
protected $ignoreDefaultOptions = false;
protected $defaultOptions = [];
public function ignoreDefaultOptions()
{
$this->ignoreDefaultOptions = true;
return $this;
}
public function withoutDefaultOptions($keys = null)
{
if ($keys === null) {
return $this->ignoreDefaultOptions();
}
if (func_num_args() > 1) {
$keys = func_get_args();
}
$this->defaultOptions = with($this->defaultOptions, function ($options) use ($keys) {
foreach (Arr::wrap($keys) as $key) {
Arr::forget($options, $key);
}
return $options;
});
return $this;
}
public function withDefaultOptions(array $options)
{
$this->defaultOptions = array_merge_recursive($this->defaultOptions, $options);
return $this;
}
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if ($this->defaultOptions && ! $this->ignoreDefaultOptions) {
return tap(new PendingRequest($this), function ($request) {
$request->withOptions($this->defaultOptions)
->stub($this->stubCallbacks);
})->{$method}(...$parameters);
}
return parent::__call($method, $parameters);
}
}
Then, create a HttpServiceProver,
php artisan make:provider HttpServiceProvider
And put the following code there,
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Http\Client\Factory as BaseFactory;
use App\HttpClient\Factory;
class HttpServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(
BaseFactory::class,
function ($app) {
return new Factory($app->make(Dispatcher::class));
}
);
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
Now, register the newly created service provider in AppServiceProvider.php
public function register()
{
//...
app()->register(HttpServiceProvider::class);
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//....
Http::withDefaultOptions([
'headers' => [
'X-Bar-Header' => 'bar'
],
]);
}
There are other options in this package. Please check it the package link for details.

how to avoid creating a slug that already exists as a Route "Symfony 4"

I have the entity Page identified by slug. Also I have the action to view a page in the Page controler :
class PageController extends AbstractController
{
/**
* #Route("/{slug}", name="fronend_page")
*/
public function show(Page $page)
{
return $this->render("font_end/page/show.html.twig", [
"page" => $page,
]);
}
}
I am looking for good practice to validate the slug ( check if exist in routes) before save it in the database without use prefixes
Example :
route exist : #route ("/blog")
check if blog exist before create slug : /{slug} = /blog
thanks
You can use the UniqueEntity annotation for checking slug for unique.
For example, in your entity add UniqueEntity annotation with the slug field.
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #UniqueEntity("slug")
*/
class Page
{
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank
*/
private $slug;
public function __construct(string $slug)
{
$this->slug = $slug;
}
}
Then you can create some service or do validation in your controller.
/**
* #Route("/{slug}")
*/
public function show($slug, ValidatorInterface $validator)
{
$page = new Page($slug);
$errors = $validator->validate($author);
if (count($errors) > 0) {
// handle errors
}
// save entity
}
Update:
For checking already existing routes probably you can do something like this
public function isRouteExist(string $slug): bool
{
/** #var Symfony\Component\Routing\RouterInterface $router */
$routes = array_filter(array_map(function (\Symfony\Component\Routing\Route $route) {
if (!$route->compile()->getVariables()) {
return $route->getPath();
}
return null;
}, $router->getRouteCollection()->all()));
return in_array(sprintf('/%s', $slug), $routes, true);
}
I created a validation Symfony :
class ContainsCheckSlugValidator extends ConstraintValidator
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ContainsCheckSlug) {
throw new UnexpectedTypeException($constraint, ContainsCheckSlug::class);
}
// custom constraints should ignore null and empty values to allow
// other constraints (NotBlank, NotNull, etc.) take care of that
if (null === $value || "" === $value) {
return;
}
$routes = $this->router->getRouteCollection()->all();
$routes = array_map(function($route){
return $route->getPath();
},$routes);
if (in_array(sprintf("/{_locale}/%s/", $value), $routes, true)) {
$this->context->buildViolation($constraint->message)
->setParameter("{{ string }}", $value)
->addViolation();
}
}
}
Thanks #Ihor_Kostrov :)

Extra data on a collection operation

Does anybody know how to add extra data on a collection?
The doc says much about how to add extra data on an item which translates into decorating the ItemNormalizer service, and it works pretty well.
But I’m struggling in finding out which normalizer to decorate when it comes to add some data on a collection of entities. The extra data could be anything: the current user logged in, a detailed pager, some debug parameters, ... that are not related to a specific entity, but rather on the request itself.
The only working solution for now is to hook on a Kernel event but that's definitely not the code I like to write:
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class SerializeListener implements EventSubscriberInterface
{
/**
* #var Security
*/
private $security;
/**
* #var NormalizerInterface
*/
private $normalizer;
public function __construct(
Security $security,
NormalizerInterface $normalizer
) {
$this->security = $security;
$this->normalizer = $normalizer;
}
public function addCurrentUser(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
if ($request->attributes->has('_api_respond')) {
$serialized = $event->getControllerResult();
$data = json_decode($serialized, true);
$data['hydra:user'] = $this->normalizer->normalize(
$this->security->getUser(),
$request->attributes->get('_format'),
$request->attributes->get('_api_normalization_context')
);
$event->setControllerResult(json_encode($data));
}
}
/**
* #inheritDoc
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
'addCurrentUser',
EventPriorities::POST_SERIALIZE,
],
];
}
}
Any ideas?
Thank you,
Ben
Alright, I finally managed to do this.
namespace App\Api;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class ApiCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
/**
* #var NormalizerInterface|NormalizerAwareInterface
*/
private $decorated;
public function __construct(NormalizerInterface $decorated)
{
if (!$decorated instanceof NormalizerAwareInterface) {
throw new \InvalidArgumentException(
sprintf('The decorated normalizer must implement the %s.', NormalizerAwareInterface::class)
);
}
$this->decorated = $decorated;
}
/**
* #inheritdoc
*/
public function normalize($object, $format = null, array $context = [])
{
$data = $this->decorated->normalize($object, $format, $context);
if ('collection' === $context['operation_type'] && 'get' === $context['collection_operation_name']) {
$data['hydra:meta'] = ['foo' => 'bar'];
}
return $data;
}
/**
* #inheritdoc
*/
public function supportsNormalization($data, $format = null)
{
return $this->decorated->supportsNormalization($data, $format);
}
/**
* #inheritdoc
*/
public function setNormalizer(NormalizerInterface $normalizer)
{
$this->decorated->setNormalizer($normalizer);
}
}
# config/services.yaml
services:
App\Api\ApiCollectionNormalizer:
decorates: 'api_platform.hydra.normalizer.collection'
arguments: [ '#App\Api\ApiCollectionNormalizer.inner' ]
Keep it for the records :)

Remove header when return response

I am using expressive 2 for a webservice, but when I return a JsonResponse it return the X-Powered-By →PHP/7.1.1 header, how to remove it from response?
class ProfileAction
{
/** #var UsersTable */
private $usersTable;
public function __construct( UsersTable $usersTable )
{
$this->usersTable = $usersTable;
}
public function __invoke( ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
// TODO: Implement __invoke() method.
return new JsonResponse(['profile'=>true]);
}
}
I just found the answer on Google just disable on php.ini expose_php=Off.

Laravel Form Request issue with validation

I am trying to use form request in my REST API built using laravel 5.2. My controller is
public function save(SbcEntityFormRequest $request)
{
$requestData = Input::all();
try {
list($success, $message) = $this->sbcService->saveSbcEntity($requestData);
if ($success) {
return $this->successJsonResponse($request, ['id' => $message]);
}
return $this->errorJsonResponse($request, Response::HTTP_BAD_REQUEST, [$message]);
} catch (Exception $e) {
AppLog::write($e);
$message = [config('messages.save_failed')];
return $this->errorJsonResponse($request, Response::HTTP_BAD_REQUEST, $message);
}
}
My form request is
namespace App\Http\Requests;
use Illuminate\Http\Request;
class SbcEntityFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'logo' => 'Required',
'bio' => 'Required|Max:150'
];
}
}
My validation rules are never called. I put a die statement in authorize() function and it is neither called. When I printed $request->all() in the controller it shows empty array. Any Idea on what is wrong here?

Resources