Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
73.68% covered (warning)
73.68%
14 / 19
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SurveyContextFilter
73.68% covered (warning)
73.68%
14 / 19
75.00% covered (warning)
75.00%
3 / 4
17.57
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isAnySurveyAvailable
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
7
 isAudienceKeySet
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 isKnownPageId
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace QuickSurveys;
4
5use MediaWiki\Title\Title;
6
7/**
8 * Determine whether any surveys will be shown on the current pageview.
9 */
10class 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     * Checks if a specific audience key is set for any surveys.
56     *
57     * @param string $key
58     * @return bool
59     */
60    public function isAudienceKeySet( string $key ): bool {
61        foreach ( $this->surveys as $survey ) {
62            $audience = $survey->getAudience()->toArray();
63            if ( isset( $audience[$key] ) ) {
64                return true;
65            }
66        }
67        return false;
68    }
69
70    /**
71     * @param int $pageId
72     *
73     * @return bool
74     */
75    private function isKnownPageId( int $pageId ): bool {
76        foreach ( $this->surveys as $survey ) {
77            $audience = $survey->getAudience()->toArray();
78            if ( in_array( $pageId, $audience['pageIds'] ?? [] ) ) {
79                return true;
80            }
81        }
82        return false;
83    }
84}