Fix typos in MessageCache
[lhc/web/wiklou.git] / includes / preferences / MultiUsernameFilter.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Preferences;
22
23 use CentralIdLookup;
24
25 class MultiUsernameFilter implements Filter {
26 /**
27 * @var CentralIdLookup|null
28 */
29 private $lookup;
30 /** @var CentralIdLookup|int User querying central usernames or one of the audience constants */
31 private $userOrAudience;
32
33 /**
34 * @param CentralIdLookup|null $lookup
35 * @param int $userOrAudience
36 */
37 public function __construct( CentralIdLookup $lookup = null,
38 $userOrAudience = CentralIdLookup::AUDIENCE_PUBLIC
39 ) {
40 $this->lookup = $lookup;
41 $this->userOrAudience = $userOrAudience;
42 }
43
44 /**
45 * @inheritDoc
46 */
47 public function filterFromForm( $names ) {
48 $names = trim( $names );
49 if ( $names !== '' ) {
50 $names = preg_split( '/\n/', $names, -1, PREG_SPLIT_NO_EMPTY );
51 $ids = $this->getLookup()->centralIdsFromNames( $names, $this->userOrAudience );
52 if ( $ids ) {
53 return implode( "\n", $ids );
54 }
55 }
56 // If the user list is empty, it should be null (don't save) rather than an empty string
57 return null;
58 }
59
60 /**
61 * @inheritDoc
62 */
63 public function filterForForm( $value ) {
64 $ids = self::splitIds( $value );
65 $names = $ids ? $this->getLookup()->namesFromCentralIds( $ids, $this->userOrAudience ) : [];
66 return implode( "\n", $names );
67 }
68
69 /**
70 * Splits a newline separated list of user ids into a
71 *
72 * @param string $str
73 * @return int[]
74 */
75 public static function splitIds( $str ) {
76 return array_map( 'intval', preg_split( '/\n/', $str, -1, PREG_SPLIT_NO_EMPTY ) );
77 }
78
79 /**
80 * @return CentralIdLookup
81 */
82 private function getLookup() {
83 $this->lookup = $this->lookup ?? CentralIdLookup::factory();
84 return $this->lookup;
85 }
86 }