forked from php-tmdb/api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RequestSubscriber.php
92 lines (83 loc) · 2.86 KB
/
RequestSubscriber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* This file is part of the Tmdb PHP API created by Michael Roterman.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Tmdb
* @author Michael Roterman <[email protected]>
* @copyright (c) 2013, Michael Roterman
* @version 0.0.1
*/
namespace Tmdb\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Tmdb\Exception\RuntimeException;
use Tmdb\HttpClient\HttpClientEventSubscriber;
use Tmdb\HttpClient\Response;
/**
* Class RequestSubscriber
* @package Tmdb\Event
*/
class RequestSubscriber extends HttpClientEventSubscriber
{
public static function getSubscribedEvents()
{
return [
TmdbEvents::REQUEST => 'send',
];
}
/**
* @param RequestEvent $event
* @param string $eventName
* @param EventDispatcherInterface $eventDispatcher
*
* @return string|Response
*/
public function send(RequestEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
{
// Preparation of request parameters / Possibility to use for logging and caching etc.
$eventDispatcher->dispatch(TmdbEvents::BEFORE_REQUEST, $event);
if ($event->isPropagationStopped() && $event->hasResponse()) {
return $event->getResponse();
}
$response = $this->sendRequest($event);
$event->setResponse($response);
// Possibility to cache the request
$eventDispatcher->dispatch(TmdbEvents::AFTER_REQUEST, $event);
return $response;
}
/**
* Call upon the adapter to create an response object
*
* @param RequestEvent $event
* @throws \Exception
* @return Response
*/
public function sendRequest(RequestEvent $event)
{
switch ($event->getMethod()) {
case 'GET':
$response = $this->getHttpClient()->getAdapter()->get($event->getRequest());
break;
case 'HEAD':
$response = $this->getHttpClient()->getAdapter()->head($event->getRequest());
break;
case 'POST':
$response = $this->getHttpClient()->getAdapter()->post($event->getRequest());
break;
case 'PUT':
$response = $this->getHttpClient()->getAdapter()->put($event->getRequest());
break;
case 'PATCH':
$response = $this->getHttpClient()->getAdapter()->patch($event->getRequest());
break;
case 'DELETE':
$response = $this->getHttpClient()->getAdapter()->delete($event->getRequest());
break;
default:
throw new RuntimeException(sprintf('Unknown request method "%s".', $event->getMethod()));
}
return $response;
}
}