Campaign::selectBucket()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\BannerServer\Entity\BannerSelection;
6
7
/**
8
 * @license GPL-2.0-or-later
9
 */
10
class Campaign {
11
12
	private string $identifier;
13
	private \DateTime $start;
14
	private \DateTime $end;
15
	private string $category;
16
	private RandomIntegerGenerator $rng;
17
	private int $displayPercentage;
18
	private ?int $minDisplayWidth;
19
	private ?int $maxDisplayWidth;
20
21
	/**
22
	 * @var Bucket[]
23
	 */
24
	private $buckets;
25
26 9
	public function __construct(
27
		string $identifier,
28
		\DateTime $start,
29
		\DateTime $end,
30
		int $displayPercentage,
31
		string $category,
32
		RandomIntegerGenerator $rng,
33
		?int $minDisplayWidth,
34
		?int $maxDisplayWidth,
35
		Bucket $firstBucket,
36
		Bucket ...$additionalBuckets ) {
37 9
		$this->identifier = $identifier;
38 9
		$this->start = $start;
39 9
		$this->end = $end;
40 9
		$this->category = $category;
41 9
		$this->displayPercentage = $displayPercentage;
42 9
		$this->rng = $rng;
43 9
		$this->minDisplayWidth = $minDisplayWidth;
44 9
		$this->maxDisplayWidth = $maxDisplayWidth;
45 9
		$this->buckets = array_merge( [ $firstBucket ], $additionalBuckets );
46
	}
47
48 1
	public function getIdentifier(): string {
49 1
		return $this->identifier;
50
	}
51
52 1
	public function getEnd(): \DateTime {
53 1
		return $this->end;
54
	}
55
56
	public function getCategory(): string {
57
		return $this->category;
58
	}
59
60 2
	public function isInActiveDateRange( \DateTime $time ): bool {
61 2
		return $time->getTimestamp() >= $this->start->getTimestamp() &&
62 2
			$time->getTimestamp() <= $this->end->getTimestamp();
63
	}
64
65 3
	public function selectBucket( ?string $bucketId ): Bucket {
66 3
		foreach ( $this->buckets as $bucket ) {
67 3
			if ( $bucket->getIdentifier() === $bucketId ) {
68 1
				return $bucket;
69
			}
70
		}
71 2
		return $this->buckets[$this->rng->getRandomInteger( 0, count( $this->buckets ) - 1 )];
72
	}
73
74 1
	public function getDisplayPercentage(): int {
75 1
		return $this->displayPercentage;
76
	}
77
78 3
	public function isInDisplayRange( int $width ): bool {
79 3
		if ( $this->minDisplayWidth !== null && $width < $this->minDisplayWidth ) {
80 1
			return false;
81
		}
82 3
		if ( $this->maxDisplayWidth !== null && $width >= $this->maxDisplayWidth ) {
83 1
			return false;
84
		}
85 3
		return true;
86
	}
87
}
88