File: RestStatusTrait.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (83 lines) | stat: -rw-r--r-- 2,112 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

namespace MediaWiki\Rest\Handler\Helper;

use MediaWiki\Logger\LoggerFactory;
use MediaWiki\Message\Converter;
use MediaWiki\Rest\LocalizedHttpException;
use StatusValue;
use Wikimedia\Message\MessageValue;

/**
 * Trait for handling Status objects in REST handlers.
 */
trait RestStatusTrait {

	private ?Converter $messageValueConverter = null;

	private function getMessageValueConverter(): Converter {
		if ( !$this->messageValueConverter ) {
			$this->messageValueConverter = new Converter();
		}
		return $this->messageValueConverter;
	}

	/**
	 * Extract the error messages from a Status, as MessageValue objects.
	 * @param StatusValue $status
	 * @return MessageValue[]
	 */
	private function convertStatusToMessageValues( StatusValue $status ): array {
		$conv = $this->getMessageValueConverter();
		return array_map( static function ( $msg ) use ( $conv ) {
			// TODO: It should be possible to do this without going through a Message object,
			// but the internal format of parameters is different in MessageValue (T358779)
			return $conv->convertMessage( $msg );
		}, $status->getMessages() );
	}

	/**
	 * @param StatusValue $status
	 * @param string|MessageValue $msg
	 * @param int $code
	 * @param array $data
	 *
	 * @return never
	 * @throws LocalizedHttpException
	 */
	private function throwExceptionForStatus(
		StatusValue $status,
		$msg,
		int $code,
		array $data = []
	) {
		$data += [ 'error-keys' => $this->getStatusErrorKeys( $status ) ];

		if ( is_string( $msg ) ) {
			$msg = MessageValue::new( $msg )
				->semicolonListParams(
					$this->convertStatusToMessageValues( $status )
				);
		}

		throw new LocalizedHttpException( $msg, $code, $data );
	}

	private function getStatusErrorKeys( StatusValue $status ) {
		$keys = [];

		foreach ( $status->getMessages() as $msg ) {
			$keys[] = $msg->getKey();
		}

		return array_unique( $keys );
	}

	private function logStatusError( StatusValue $status, string $message, string $channel ) {
		LoggerFactory::getInstance( $channel )->error(
			$message,
			[ 'reason' => $this->getStatusErrorKeys( $status ) ]
		);
	}

}