| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Rest\Handler\Helper; |
| 4 |
|
| 5 |
use MediaWiki\Logger\LoggerFactory; |
| 6 |
use MediaWiki\Message\Converter; |
| 7 |
use MediaWiki\Rest\LocalizedHttpException; |
| 8 |
use StatusValue; |
| 9 |
use Wikimedia\Message\MessageValue; |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
trait RestStatusTrait { |
| 15 |
|
| 16 |
private ?Converter $messageValueConverter = null; |
| 17 |
|
| 18 |
private function getMessageValueConverter(): Converter { |
| 19 |
if ( !$this->messageValueConverter ) { |
| 20 |
$this->messageValueConverter = new Converter(); |
| 21 |
} |
| 22 |
return $this->messageValueConverter; |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
private function convertStatusToMessageValues( StatusValue $status ): array { |
| 31 |
$conv = $this->getMessageValueConverter(); |
| 32 |
return array_map( static function ( $msg ) use ( $conv ) { |
| 33 |
|
| 34 |
|
| 35 |
return $conv->convertMessage( $msg ); |
| 36 |
}, $status->getMessages() ); |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
private function throwExceptionForStatus( |
| 49 |
StatusValue $status, |
| 50 |
$msg, |
| 51 |
int $code, |
| 52 |
array $data = [] |
| 53 |
) { |
| 54 |
$data += [ 'error-keys' => $this->getStatusErrorKeys( $status ) ]; |
| 55 |
|
| 56 |
if ( is_string( $msg ) ) { |
| 57 |
$msg = MessageValue::new( $msg ) |
| 58 |
->semicolonListParams( |
| 59 |
$this->convertStatusToMessageValues( $status ) |
| 60 |
); |
| 61 |
} |
| 62 |
|
| 63 |
throw new LocalizedHttpException( $msg, $code, $data ); |
| 64 |
} |
| 65 |
|
| 66 |
private function getStatusErrorKeys( StatusValue $status ) { |
| 67 |
$keys = []; |
| 68 |
|
| 69 |
foreach ( $status->getMessages() as $msg ) { |
| 70 |
$keys[] = $msg->getKey(); |
| 71 |
} |
| 72 |
|
| 73 |
return array_unique( $keys ); |
| 74 |
} |
| 75 |
|
| 76 |
private function logStatusError( StatusValue $status, string $message, string $channel ) { |
| 77 |
LoggerFactory::getInstance( $channel )->error( |
| 78 |
$message, |
| 79 |
[ 'reason' => $this->getStatusErrorKeys( $status ) ] |
| 80 |
); |
| 81 |
} |
| 82 |
|
| 83 |
} |