AlreadyDonatedController::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\BannerServer\Controller;
6
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
10
/**
11
 * This controller allows to set the cookie lifetime dynamically with the "d" (="duration") query parameter.
12
 */
13
class AlreadyDonatedController extends AbstractCookieController {
14
15
	public const MAX_INTERVAL_LENGTH = 'P28D';
16
17
	private \DateInterval $cookieLifetime;
18
19
	public function __construct() {
20
		$this->cookieLifetime = new \DateInterval( self::MAX_INTERVAL_LENGTH );
21
	}
22
23
	public function index( Request $request ): Response {
24
		if ( $request->query->has( 'd' ) ) {
25
			$potentialLifetime = $this->getDurationHours( $request->query->get( 'd' ) );
26
			$now = new \DateTimeImmutable();
27
			if ( $now->add( $potentialLifetime ) < $now->add( new \DateInterval( self::MAX_INTERVAL_LENGTH ) ) ) {
28
				$this->cookieLifetime = $potentialLifetime;
29
			}
30
		}
31
		return parent::index( $request );
32
	}
33
34
	protected function getCookieLifetime(): \DateInterval {
35
		return $this->cookieLifetime;
36
	}
37
38
	private function getDurationHours( float|bool|int|string|null $durationInHours ): \DateInterval {
39
		$durationInHours = filter_var( $durationInHours, FILTER_VALIDATE_INT );
40
		if ( $durationInHours === false ) {
41
			return new \DateInterval( self::MAX_INTERVAL_LENGTH );
42
		}
43
		return new \DateInterval( 'PT' . $durationInHours . 'H' );
44
	}
45
}
46