Completed
Pull Request — master (#38)
by Sam
02:50
created

MultipartRequest::setMultipartParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Mediawiki\Api;
4
5
use Exception;
6
7
/**
8
 * A MultipartRequest is the same as a FluentRequest with additional support for setting request
9
 * parameters (both normal parameters and headers) on multipart requests.
10
 *
11
 * @link http://docs.guzzlephp.org/en/stable/request-options.html#multipart
12
 */
13
class MultipartRequest extends FluentRequest {
14
15
	/** @var mixed[] */
16
	protected $multipartParams = [];
17
18
	/**
19
	 * Check the structure of a multipart parameter array.
20
	 *
21
	 * @param mixed[] $params The multipart parameters to check.
22
	 *
23
	 * @throws Exception
24
	 */
25 2
	protected function checkMultipartParams( $params ) {
26 2
		foreach ( $params as $key => $val ) {
27 2
			if ( !is_array( $val ) ) {
28
				throw new Exception( "Parameter '$key' must be an array." );
29
			}
30 2
			if ( !in_array( $key, array_keys( $this->getParams() ) ) ) {
31 1
				throw new Exception( "Parameter '$key' is not already set on this request." );
32
			}
33 1
		}
34 1
	}
35
36
	/**
37
	 * Set all multipart parameters, replacing all existing ones.
38
	 *
39
	 * Each key of the array passed in here must be the name of a parameter already set on this
40
	 * request object.
41
	 *
42
	 * @param $params
43
	 * @return $this
44
	 */
45
	public function setMultipartParams( $params ) {
46
		$this->checkMultipartParams( $params );
47
		$this->multipartParams = $params;
48
		return $this;
49
	}
50
51
	/**
52
	 * Add extra multipart parameters.
53
	 *
54
	 * Each key of the array passed in here must be the name of a parameter already set on this
55
	 * request object.
56
	 *
57
	 * @param mixed[] $params
58
	 *
59
	 * @return $this
60
	 */
61 2
	public function addMultipartParams( $params ) {
62 2
		$this->checkMultipartParams( $params );
63 1
		$this->multipartParams = array_merge( $this->multipartParams, $params );
64 1
		return $this;
65
	}
66
67
	/**
68
	 * Get all multipart request parameters.
69
	 *
70
	 * @return mixed[]
71
	 */
72 1
	public function getMultipartParams() {
73 1
		return $this->multipartParams;
74
	}
75
}
76