Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
SurveyContextFilter | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
11 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
isAnySurveyAvailable | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
7 | |||
isKnownPageId | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | |
3 | namespace QuickSurveys; |
4 | |
5 | use MediaWiki\Title\Title; |
6 | |
7 | /** |
8 | * Determine whether any surveys will be shown on the current pageview. |
9 | */ |
10 | class SurveyContextFilter { |
11 | /** |
12 | * The internal name of the view action (see \ViewAction) as returned by ActionFactory::getActionName. |
13 | */ |
14 | private const VIEW_ACTION_NAME = 'view'; |
15 | |
16 | /** |
17 | * @var Survey[] |
18 | */ |
19 | private $surveys; |
20 | |
21 | /** |
22 | * @param Survey[] $surveys |
23 | */ |
24 | public function __construct( array $surveys ) { |
25 | $this->surveys = $surveys; |
26 | } |
27 | |
28 | /** |
29 | * @param Title|null $title |
30 | * @param string $action |
31 | * |
32 | * @return bool |
33 | */ |
34 | public function isAnySurveyAvailable( ?Title $title, string $action ): bool { |
35 | if ( !$this->surveys ) { |
36 | return false; |
37 | } |
38 | |
39 | if ( $title === null || $action !== static::VIEW_ACTION_NAME ) { |
40 | return false; |
41 | } |
42 | |
43 | // Typically disabled outside of the main namespace, as well as on the main page |
44 | if ( !$title->inNamespace( NS_MAIN ) || $title->isMainPage() ) { |
45 | // Allow surveys to target specific pages regardless of namespace. |
46 | if ( !$this->isKnownPageId( $title->getArticleID() ) ) { |
47 | return false; |
48 | } |
49 | } |
50 | |
51 | return $title->exists(); |
52 | } |
53 | |
54 | /** |
55 | * @param int $pageId |
56 | * |
57 | * @return bool |
58 | */ |
59 | private function isKnownPageId( int $pageId ): bool { |
60 | foreach ( $this->surveys as $survey ) { |
61 | $audience = $survey->getAudience()->toArray(); |
62 | if ( in_array( $pageId, $audience['pageIds'] ?? [] ) ) { |
63 | return true; |
64 | } |
65 | } |
66 | return false; |
67 | } |
68 | } |