1 | <?php |
||
13 | class VcrPlugin implements Plugin |
||
14 | { |
||
15 | const HEADER_VCR = 'X-VCR'; |
||
16 | const HEADER_VCR_REPLAY = 'replay'; |
||
17 | const HEADER_VCR_RECORDED = 'recorded'; |
||
18 | |||
19 | /** |
||
20 | * @var Vcr |
||
21 | */ |
||
22 | private $vcr; |
||
23 | |||
24 | 6 | public function __construct(Vcr $vcr) |
|
28 | |||
29 | 5 | public function handleRequest(RequestInterface $request, callable $next, callable $first) |
|
39 | |||
40 | 5 | private function replay(RequestInterface $request) |
|
41 | { |
||
42 | 5 | if (!$this->vcr->isTurnedOn() || !$this->vcr->hasTape()) { |
|
43 | 1 | throw new CannotBeReplayed(); |
|
44 | } |
||
45 | |||
46 | 4 | $tape = $this->vcr->getTape(); |
|
47 | |||
48 | try { |
||
49 | 4 | $track = $tape->findTrackByRequest($request); |
|
50 | 4 | } catch (NotFound $e) { |
|
51 | 1 | throw new CannotBeReplayed(); |
|
52 | } |
||
53 | |||
54 | 3 | if ($track->hasException()) { |
|
55 | 1 | return new RejectedPromise($track->getException()); |
|
56 | } |
||
57 | |||
58 | 2 | if ($track->hasResponse()) { |
|
59 | 1 | $response = $track->getResponse()->withAddedHeader(self::HEADER_VCR, self::HEADER_VCR_REPLAY); |
|
60 | |||
61 | 1 | return new FulfilledPromise($response); |
|
62 | } |
||
63 | |||
64 | 1 | throw new CannotBeReplayed(); |
|
65 | } |
||
66 | |||
67 | 3 | private function record(RequestInterface $request) |
|
68 | { |
||
69 | 3 | if (!$this->vcr->isTurnedOn() || !$this->vcr->hasTape()) { |
|
70 | 1 | return; |
|
71 | } |
||
72 | |||
73 | 2 | $tape = $this->vcr->getTape(); |
|
74 | 2 | $tape->addTrack(Track::create($request)); |
|
75 | 2 | } |
|
76 | |||
77 | 3 | private function onFulfilled(RequestInterface $request) |
|
102 | |||
103 | 3 | private function onRejected(RequestInterface $request) |
|
126 | } |
||
127 |