Debian Codegraph @

includes/Rest/Handler/Helper/RestStatusTrait.php

raw symbols SCIP
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 * Trait for handling Status objects in REST handlers.
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 * Extract the error messages from a Status, as MessageValue objects.
27 * @param StatusValue $status
28 * @return MessageValue[]
29 */
30 private function convertStatusToMessageValues( StatusValue $status ): array {
31 $conv = $this->getMessageValueConverter();
32 return array_map( static function ( $msg ) use ( $conv ) {
33 // TODO: It should be possible to do this without going through a Message object,
34 // but the internal format of parameters is different in MessageValue (T358779)
35 return $conv->convertMessage( $msg );
36 }, $status->getMessages() );
37 }
38
39 /**
40 * @param StatusValue $status
41 * @param string|MessageValue $msg
42 * @param int $code
43 * @param array $data
44 *
45 * @return never
46 * @throws LocalizedHttpException
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 }