Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
MenteeOverviewPrefixSearchDataFilter
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
4 / 4
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 prefix
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 limit
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getUsernames
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace GrowthExperiments\MentorDashboard\MenteeOverview;
4
5/**
6 * Helper class to search mentees by username prefix
7 *
8 * Used by search box of the mentor dashboard's mentee overview module
9 * (as part of autocomplete).
10 */
11class MenteeOverviewPrefixSearchDataFilter {
12    /** @var array */
13    private $data;
14
15    /** @var string */
16    private $prefix = '';
17
18    /** @var int */
19    private $limit = 10;
20
21    /**
22     * @param array $data Data to filter (must come from MenteeOverviewDataProvider)
23     */
24    public function __construct(
25        array $data
26    ) {
27        $this->data = $data;
28    }
29
30    /**
31     * Only mentees matching a given prefix
32     *
33     * @param string $prefix
34     * @return static
35     */
36    public function prefix( string $prefix ) {
37        $this->prefix = str_replace( '_', ' ', $prefix );
38        return $this;
39    }
40
41    /**
42     * Limit number of usernames returned
43     *
44     * @param int $limit
45     * @return static
46     */
47    public function limit( int $limit ) {
48        $this->limit = $limit;
49        return $this;
50    }
51
52    /**
53     * Get all usernames matching given prefix
54     *
55     * @return string[]
56     */
57    public function getUsernames(): array {
58        $usernames = array_column( $this->data, 'username' );
59
60        $prefixLen = strlen( $this->prefix );
61        // filtering only makes sense with prefixes longer than 0 characters
62        if ( $prefixLen !== 0 ) {
63            $usernames = array_filter( $usernames, function ( $username ) use ( $prefixLen ) {
64                return substr( $username, 0, $prefixLen ) === $this->prefix;
65            } );
66        }
67
68        // Sort the data
69        sort( $usernames );
70
71        return array_slice( $usernames, 0, $this->limit, true );
72    }
73}