Skip to content

Instantly share code, notes, and snippets.

@Tiriel
Created September 20, 2022 08:57
Show Gist options
  • Save Tiriel/172196bc148271f0ce57b3dd9c680efe to your computer and use it in GitHub Desktop.
Save Tiriel/172196bc148271f0ce57b3dd9c680efe to your computer and use it in GitHub Desktop.
SensioLabs SF5MASTER Dependency Injection exercise base
#config/packages/framework.yaml
framework:
# ...
http_client:
scoped_clients:
omdb_client:
base_uri: 'http://www.omdbapi.com/'
query:
apikey: # To be filled
# src/Provider/MovieProvider.php
<?php
namespace App\Provider;
use App\Entity\Movie;
class MovieProvider
{
public function getMovieByTitle(string $title): Movie
{
}
}
# src/Consumer/OmdbApiConsumer.php
<?php
namespace App\Consumer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class OmdbApiConsumer
{
public const MODE_ID = 'i';
public const MODE_TITLE = 't';
public function __construct(private HttpClientInterface $omdbClient)
{
}
public function fetchMovie(string $mode, string $value)
{
if (!\in_array($mode, [self::MODE_ID, self::MODE_TITLE])) {
throw new \RuntimeException(sprintf("Unknown mode \"%s\"", $mode));
}
$data = $this->omdbClient->request(
Request::METHOD_GET,
'',
['query' => [$mode => $value]]
)->toArray();
if (isset($data['Response']) && $data['Response'] === 'False') {
throw new NotFoundHttpException(sprintf('Movie with %s "%s" not found.', $mode, $value));
}
return $data;
}
}
# src/Transformer/OmdbMovieTransformer.php
<?php
namespace App\Transformer;
use App\Entity\Movie;
use Symfony\Component\Form\DataTransformerInterface;
class OmdbMovieTransformer implements DataTransformerInterface
{
public function transform(mixed $value): Movie
{
// TODO: Implement transform() method.
}
public function reverseTransform(mixed $value)
{
throw new \RuntimeException('Method not implemented.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment