Completed
Pull Request — master (#19)
by Tim
64:58 queued 60:26
created

BannerSelectionUseCase::provideBannerRequest()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 2
nop 1
dl 0
loc 16
ccs 0
cts 12
cp 0
crap 20
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\BannerServer\UseCase\BannerSelection;
6
7
use WMDE\BannerServer\Entity\BannerSelection\Bucket;
8
use WMDE\BannerServer\Entity\BannerSelection\Campaign;
9
use WMDE\BannerServer\Entity\BannerSelection\CampaignCollection;
10
use WMDE\BannerServer\Entity\BannerSelection\ImpressionThresholdInterface;
11
12
/**
13
 * @license GNU GPL v2+
14
 */
15
class BannerSelectionUseCase {
16
17
	private $campaignCollection;
18
	private $currentCampaign;
19
	private $impressionThreshold;
20
21
	public function __construct( CampaignCollection $campaignCollection, ImpressionThresholdInterface $impressionThreshold ) {
22
		$this->campaignCollection = $campaignCollection;
23
		$this->impressionThreshold = $impressionThreshold;
24
	}
25
26
	public function provideBannerRequest( Visitor $visitor ): BannerSelection {
27
		if ( $visitor->hasDonated() ||
28
			$this->getCurrentCampaign() === null ||
29
			$this->impressionThreshold->getIsOverThreshold( $visitor->getTotalImpressionCount() ) ) {
30
			return BannerSelection::createEmptySelection( $visitor );
31
		}
32
33
		$visitorBucket = $this->getCurrentCampaign()->selectBucket(
34
			$visitor->getBucketIdentifier(),
35
			[ self::class, 'selectRandomBucket' ]
36
		);
37
38
		return BannerSelection::createBannerSelection(
39
			$visitorBucket->getBanner( $visitor->getTotalImpressionCount() ),
40
			new Visitor( 1, $visitorBucket->getIdentifier(), false ),
41
			new \DateTime()
42
		);
43
	}
44
45
	private function getCurrentCampaign(): ?Campaign {
46
		if ( $this->currentCampaign === null ) {
47
			$this->currentCampaign = $this->campaignCollection->getCampaign( new \DateTime() );
48
		}
49
		return $this->currentCampaign;
50
	}
51
52
	public static function selectRandomBucket( Bucket ...$buckets ): Bucket {
53
		return $buckets[random_int( 0, count( $buckets ) )];
54
	}
55
}