Skip to content

Instantly share code, notes, and snippets.

@batFormat
Forked from stenin-nikita/ApolloUpload.php
Created May 12, 2018 13:40
Show Gist options
  • Save batFormat/8ab10a33f1ad18c2b5e9af4f948db009 to your computer and use it in GitHub Desktop.
Save batFormat/8ab10a33f1ad18c2b5e9af4f948db009 to your computer and use it in GitHub Desktop.
ApolloUpload Middleware for Laravel
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Class ApolloUpload
*/
class ApolloUpload
{
private const GRAPHQL_OPERATIONS = 'operations';
private const GRAPHQL_MAP = 'map';
/**
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($this->isApolloUpload($request)) {
$request->request->replace($this->transform($request));
}
return $next($request);
}
/**
* @param Request $request
* @return bool
*/
private function isApolloUpload(Request $request): bool
{
$contentType = $request->header('content-type');
return \mb_stripos($contentType, 'multipart/form-data') !== false
&& $request->has(self::GRAPHQL_OPERATIONS)
&& $request->has(self::GRAPHQL_MAP);
}
/**
* @param Request $request
* @return array
*/
private function transform(Request $request): array
{
$map = \json_decode($request->request->get(self::GRAPHQL_MAP), true);
$operations = \json_decode($request->request->get(self::GRAPHQL_OPERATIONS), true);
foreach ($map as $fileKey => $locations) {
foreach ($locations as $location) {
\array_set($operations, $location, $request->file($fileKey));
}
}
return $operations;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment