Merge "Provide command to adjust phpunit.xml for code coverage"
[lhc/web/wiklou.git] / includes / Rest / Validator / ParamValidatorCallbacks.php
1 <?php
2
3 namespace MediaWiki\Rest\Validator;
4
5 use InvalidArgumentException;
6 use MediaWiki\Rest\RequestInterface;
7 use Psr\Http\Message\UploadedFileInterface;
8 use User;
9 use Wikimedia\ParamValidator\Callbacks;
10 use Wikimedia\ParamValidator\ValidationException;
11
12 class ParamValidatorCallbacks implements Callbacks {
13
14 /** @var RequestInterface */
15 private $request;
16
17 /** @var User */
18 private $user;
19
20 public function __construct( RequestInterface $request, User $user ) {
21 $this->request = $request;
22 $this->user = $user;
23 }
24
25 /**
26 * Get the raw parameters from a source in the request
27 * @param string $source 'path', 'query', or 'post'
28 * @return array
29 */
30 private function getParamsFromSource( $source ) {
31 switch ( $source ) {
32 case 'path':
33 return $this->request->getPathParams();
34
35 case 'query':
36 return $this->request->getQueryParams();
37
38 case 'post':
39 return $this->request->getPostParams();
40
41 default:
42 throw new InvalidArgumentException( __METHOD__ . ": Invalid source '$source'" );
43 }
44 }
45
46 public function hasParam( $name, array $options ) {
47 $params = $this->getParamsFromSource( $options['source'] );
48 return isset( $params[$name] );
49 }
50
51 public function getValue( $name, $default, array $options ) {
52 $params = $this->getParamsFromSource( $options['source'] );
53 return $params[$name] ?? $default;
54 // @todo Should normalization to NFC UTF-8 be done here (much like in the
55 // action API and the rest of MW), or should it be left to handlers to
56 // do whatever normalization they need?
57 }
58
59 public function hasUpload( $name, array $options ) {
60 if ( $options['source'] !== 'post' ) {
61 return false;
62 }
63 return $this->getUploadedFile( $name, $options ) !== null;
64 }
65
66 public function getUploadedFile( $name, array $options ) {
67 if ( $options['source'] !== 'post' ) {
68 return null;
69 }
70 $upload = $this->request->getUploadedFiles()[$name] ?? null;
71 return $upload instanceof UploadedFileInterface ? $upload : null;
72 }
73
74 public function recordCondition( ValidationException $condition, array $options ) {
75 // @todo Figure out how to handle warnings
76 }
77
78 public function useHighLimits( array $options ) {
79 return $this->user->isAllowed( 'apihighlimits' );
80 }
81
82 }