Merge "API: Abstract out parameter validation"
[lhc/web/wiklou.git] / includes / libs / ParamValidator / SimpleCallbacks.php
1 <?php
2
3 namespace Wikimedia\ParamValidator;
4
5 use Wikimedia\ParamValidator\Util\UploadedFile;
6
7 /**
8 * Simple Callbacks implementation for $_GET/$_POST/$_FILES data
9 *
10 * Options array keys used by this class:
11 * - 'useHighLimits': (bool) Return value from useHighLimits()
12 *
13 * @since 1.34
14 */
15 class SimpleCallbacks implements Callbacks {
16
17 /** @var (string|string[])[] $_GET/$_POST data */
18 private $params;
19
20 /** @var (array|UploadedFile)[] $_FILES data or UploadedFile instances */
21 private $files;
22
23 /** @var array Any recorded conditions */
24 private $conditions = [];
25
26 /**
27 * @param (string|string[])[] $params Data from $_POST + $_GET
28 * @param array[] $files Data from $_FILES
29 */
30 public function __construct( array $params, array $files = [] ) {
31 $this->params = $params;
32 $this->files = $files;
33 }
34
35 public function hasParam( $name, array $options ) {
36 return isset( $this->params[$name] );
37 }
38
39 public function getValue( $name, $default, array $options ) {
40 return $this->params[$name] ?? $default;
41 }
42
43 public function hasUpload( $name, array $options ) {
44 return isset( $this->files[$name] );
45 }
46
47 public function getUploadedFile( $name, array $options ) {
48 $file = $this->files[$name] ?? null;
49 if ( $file && !$file instanceof UploadedFile ) {
50 $file = new UploadedFile( $file );
51 $this->files[$name] = $file;
52 }
53 return $file;
54 }
55
56 public function recordCondition( ValidationException $condition, array $options ) {
57 $this->conditions[] = $condition;
58 }
59
60 /**
61 * Fetch any recorded conditions
62 * @return array[]
63 */
64 public function getRecordedConditions() {
65 return $this->conditions;
66 }
67
68 /**
69 * Clear any recorded conditions
70 */
71 public function clearRecordedConditions() {
72 $this->conditions = [];
73 }
74
75 public function useHighLimits( array $options ) {
76 return !empty( $options['useHighLimits'] );
77 }
78
79 }