Completed
Push — output_formatting ( 5c6062...211baf )
by Emlyn
04:17 queued 01:36
created

HttpAcceptJson::canActivate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @package    Fuel\Foundation
4
 * @version    2.0
5
 * @author     Fuel Development Team
6
 * @license    MIT License
7
 * @copyright  2010 - 2017 Fuel Development Team
8
 * @link       http://fuelphp.com
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fuel\Foundation\Formatter;
14
15
use Fuel\Foundation\Request\RequestInterface;
16
use Fuel\Foundation\Response\ResponseInterface;
17
use Zend\Diactoros\CallbackStream;
18
19
/**
20
 * Formats data in to json if the header "Accept: application/json" is present in the request.
21
 */
22
class HttpAcceptJson extends AbstractFormatter
23
{
24
25
	/**
26
	 * {@inheritdoc}
27
	 */
28 1
	public function canActivate($data) : bool
29
	{
30
		/** @var RequestInterface $request */
31 1
		$request = $this->getContainer()->get('fuel.application.request');
32
33 1
		return $request->hasHeader('Accept') &&
34 1
			in_array('application/json', $request->getHeader('Accept'));
35
	}
36
37
	/**
38
	 * {@inheritdoc}
39
	 */
40 1
	public function format($data) : ResponseInterface
41
	{
42
		/** @var ResponseInterface $response */
43 1
		$response = $this->getContainer()->get('fuel.application.response');
44
45
		return $response
46 1
			->withBody(new CallbackStream(
47 1
				function() use ($data) {
48 1
					return json_encode($data);
49 1
				}
50
			))
51 1
			->withHeader('Content-Type', 'application/json');
52
	}
53
}
54