Completed
Push — master ( 345654...ff532e )
by Gabriel
214:01 queued 148:58
created

AddIndicatorAttributeForJsonRequests   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 27
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelRequest() 0 4 3
A isJsonRequest() 0 2 1
A isJsonPRequest() 0 3 2
A getSubscribedEvents() 0 5 1
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\App\EventHandlers;
6
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpKernel\Event\KernelEvent;
10
use Symfony\Component\HttpKernel\KernelEvents;
11
12
/**
13
 * Add indicator attribute `request_stack.is_json` to request for JSON/JSONP requests,
14
 * based on the HTTP `Accept` (accepted content type) header.
15
 *
16
 * @todo When https://phabricator.wikimedia.org/T263436 is done, use Symfony's "_format" parameter instead,
17
 *       see https://symfony.com/doc/current/routing.html#special-parameters
18
 */
19
class AddIndicatorAttributeForJsonRequests implements EventSubscriberInterface {
20
21
	private const PRIORITY = 64;
22
	public const REQUEST_IS_JSON_ATTRIBUTE = 'request_stack.is_json';
23
24
	public static function getSubscribedEvents() {
25
		return [
26
			// Priority needs to be higher than the one for error handling interception,
27
			// to be able to recognize JSON requests when creating an error handling response
28
			KernelEvents::REQUEST => [ 'onKernelRequest', self::PRIORITY ],
29
		];
30
	}
31
32
	public function onKernelRequest( KernelEvent $event ): void {
33
		$request = $event->getRequest();
34
		if ( $this->isJsonRequest( $request ) || $this->isJsonPRequest( $request ) ) {
35
			$request->attributes->set( self::REQUEST_IS_JSON_ATTRIBUTE, true );
36
		}
37
	}
38
39
	private function isJsonRequest( Request $request ): bool {
40
		return in_array( 'application/json', $request->getAcceptableContentTypes() );
41
	}
42
43
	private function isJsonPRequest( Request $request ): bool {
44
		return in_array( 'application/javascript', $request->getAcceptableContentTypes() )
45
			&& $request->get( 'callback', null );
46
	}
47
}
48