Translate extension for MediaWiki
Loading...
Searching...
No Matches
MediaWikiGenderValidator.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\Validation\Validators;
5
6use MediaWiki\Extension\Translate\MessageLoading\Message;
7use MediaWiki\Extension\Translate\Validation\MessageValidator;
8use MediaWiki\Extension\Translate\Validation\ValidationIssue;
9use MediaWiki\Extension\Translate\Validation\ValidationIssues;
10use MediaWiki\Language\LanguageFactory;
11use MediaWiki\Parser\Parser;
12use MediaWiki\Parser\ParserFactory;
13use MediaWiki\Parser\ParserOptions;
14use MediaWiki\Parser\PPFrame;
15use MediaWiki\User\UserFactory;
16
28readonly class MediaWikiGenderValidator implements MessageValidator {
29
30 public function __construct(
31 private LanguageFactory $languageFactory,
32 private ParserFactory $parserFactory,
33 private UserFactory $userFactory,
34 ) {
35 }
36
37 public function getIssues( Message $message, string $targetLanguage ): ValidationIssues {
38 $issues = new ValidationIssues();
39
40 $translation = $message->translation();
41 if ( stripos( $translation, '{{gender:' ) === false ) {
42 return $issues;
43 }
44
45 foreach ( $this->getGenderForms( $translation ) as $forms ) {
46 $count = count( $forms );
47 if ( $count === 2 && $forms[0] === $forms[1] ) {
48 $issues->add( new ValidationIssue( 'gender', 'dupe', 'translate-checks-gender-dupe' ) );
49 } elseif ( $count === 3 && $forms[0] === $forms[2] ) {
50 $issues->add( new ValidationIssue( 'gender', 'dupe', 'translate-checks-gender-dupe' ) );
51 }
52 }
53
54 return $issues;
55 }
56
63 public function getGenderForms( string $translation ): array {
64 $genders = [];
65
66 $cb = static function ( $parser, $frame, $args ) use ( &$genders ) {
67 $forms = [];
68 foreach ( $args as $index => $form ) {
69 // The first arg is the username, skip it
70 if ( $index !== 0 ) {
71 $forms[] = $frame->expand( $form, PPFrame::RECOVER_ORIG );
72 }
73 }
74 $genders[] = $forms;
75
76 return '';
77 };
78
79 $parser = $this->parserFactory->create();
80 $parser->setFunctionHook( 'gender', $cb, Parser::SFH_NO_HASH | Parser::SFH_OBJECT_ARGS );
81
82 $options = ParserOptions::newFromUserAndLang(
83 $this->userFactory->newAnonymous(),
84 $this->languageFactory->getLanguage( 'en' )
85 );
86
87 $parser->preprocess( $translation, null, $options );
88
89 return $genders;
90 }
91}
Interface for message objects used by MessageCollection.
Definition Message.php:13
getGenderForms(string $translation)
Parses {{GENDER:}} instances from a translation and returns an array of invocations,...