Completed
Push — stable8.2 ( 3eaa45...4ae337 )
by Thomas
13:54
created

BasicStructure::sendingAToWithoutRequesttoken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 17
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
nc 2
dl 17
loc 17
cc 2
eloc 11
nop 2
rs 9.4285
1
<?php
2
3
use GuzzleHttp\Client;
4
use GuzzleHttp\Message\ResponseInterface;
5
6
require __DIR__ . '/../../vendor/autoload.php';
7
8
trait BasicStructure {
9
10
	/** @var string */
11
	private $currentUser = '';
12
13
	/** @var string */
14
	private $currentServer = '';
15
16
	/** @var string */
17
	private $baseUrl = '';
18
19
	/** @var int */
20
	private $apiVersion = 1;
21
22
	/** @var ResponseInterface */
23
	private $response = null;
24
25
	/** @var \GuzzleHttp\Cookie\CookieJar */
26
	private $cookieJar;
27
28
	/** @var string */
29
	private $requestToken;
30
31
	public function __construct($baseUrl, $admin, $regular_user_password) {
32
33
		// Initialize your context here
34
		$this->baseUrl = $baseUrl;
35
		$this->adminUser = $admin;
0 ignored issues
show
Bug introduced by
The property adminUser does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
		$this->regularUser = $regular_user_password;
0 ignored issues
show
Bug introduced by
The property regularUser does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
37
		$this->localBaseUrl = $this->baseUrl;
0 ignored issues
show
Bug introduced by
The property localBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
38
		$this->remoteBaseUrl = $this->baseUrl;
0 ignored issues
show
Bug introduced by
The property remoteBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
39
		$this->currentServer = 'LOCAL';
40
		$this->cookieJar = new \GuzzleHttp\Cookie\CookieJar();
41
42
		// in case of ci deployment we take the server url from the environment
43
		$testServerUrl = getenv('TEST_SERVER_URL');
44
		if ($testServerUrl !== false) {
45
			$this->baseUrl = $testServerUrl;
46
			$this->localBaseUrl = $testServerUrl;
0 ignored issues
show
Bug introduced by
The property localBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
47
		}
48
49
		// federated server url from the environment
50
		$testRemoteServerUrl = getenv('TEST_SERVER_FED_URL');
51
		if ($testRemoteServerUrl !== false) {
52
			$this->remoteBaseUrl = $testRemoteServerUrl;
0 ignored issues
show
Bug introduced by
The property remoteBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
53
		}
54
	}
55
56
	/**
57
	 * @Given /^using api version "([^"]*)"$/
58
	 * @param string $version
59
	 */
60
	public function usingApiVersion($version) {
61
		$this->apiVersion = $version;
0 ignored issues
show
Documentation Bug introduced by
The property $apiVersion was declared of type integer, but $version is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
62
	}
63
64
	/**
65
	 * @Given /^As an "([^"]*)"$/
66
	 * @param string $user
67
	 */
68
	public function asAn($user) {
69
		$this->currentUser = $user;
70
	}
71
72
	/**
73
	 * @Given /^Using server "(LOCAL|REMOTE)"$/
74
	 * @param string $server
75
	 * @return string Previous used server
76
	 */
77
	public function usingServer($server) {
78
		$previousServer = $this->currentServer;
79
		if ($server === 'LOCAL'){
80
			$this->baseUrl = $this->localBaseUrl;
0 ignored issues
show
Bug introduced by
The property localBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
81
			$this->currentServer = 'LOCAL';
82
			return $previousServer;
83
		} else {
84
			$this->baseUrl = $this->remoteBaseUrl;
0 ignored issues
show
Bug introduced by
The property remoteBaseUrl does not seem to exist. Did you mean baseUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
85
			$this->currentServer = 'REMOTE';
86
			return $previousServer;
87
		}
88
	}
89
90
	/**
91
	 * @When /^sending "([^"]*)" to "([^"]*)"$/
92
	 * @param string $verb
93
	 * @param string $url
94
	 */
95
	public function sendingTo($verb, $url) {
96
		$this->sendingToWith($verb, $url, null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<Behat\Gherkin\Node\TableNode>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
97
	}
98
99
	/**
100
	 * Parses the xml answer to get ocs response which doesn't match with
101
	 * http one in v1 of the api.
102
	 * @param ResponseInterface $response
103
	 * @return string
104
	 */
105
	public function getOCSResponse($response) {
106
		return $response->xml()->meta[0]->statuscode;
107
	}
108
109
	/**
110
	 * This function is needed to use a vertical fashion in the gherkin tables.
111
	 * @param array $arrayOfArrays
112
	 * @return array
113
	 */
114
	public function simplifyArray($arrayOfArrays){
115
		$a = array_map(function($subArray) { return $subArray[0]; }, $arrayOfArrays);
116
		return $a;
117
	}
118
119
	/**
120
	 * @When /^sending "([^"]*)" to "([^"]*)" with$/
121
	 * @param string $verb
122
	 * @param string $url
123
	 * @param \Behat\Gherkin\Node\TableNode $body
124
	 */
125
	public function sendingToWith($verb, $url, $body) {
126
		$fullUrl = $this->baseUrl . "v{$this->apiVersion}.php" . $url;
127
		$client = new Client();
128
		$options = [];
129 View Code Duplication
		if ($this->currentUser === 'admin') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
			$options['auth'] = $this->adminUser;
131
		} else {
132
			$options['auth'] = [$this->currentUser, $this->regularUser];
133
		}
134
		if ($body instanceof \Behat\Gherkin\Node\TableNode) {
0 ignored issues
show
Bug introduced by
The class Behat\Gherkin\Node\TableNode does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
135
			$fd = $body->getRowsHash();
136
			$options['body'] = $fd;
137
		}
138
139
		try {
140
			$this->response = $client->send($client->createRequest($verb, $fullUrl, $options));
141
		} catch (\GuzzleHttp\Exception\ClientException $ex) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
142
			$this->response = $ex->getResponse();
143
		}
144
	}
145
146
	public function isExpectedUrl($possibleUrl, $finalPart){
147
		$baseUrlChopped = substr($this->baseUrl, 0, -4);
148
		$endCharacter = strlen($baseUrlChopped) + strlen($finalPart);
149
		return (substr($possibleUrl,0,$endCharacter) == "$baseUrlChopped" . "$finalPart");
150
	}
151
152
	/**
153
	 * @Then /^the OCS status code should be "([^"]*)"$/
154
	 * @param int $statusCode
155
	 */
156
	public function theOCSStatusCodeShouldBe($statusCode) {
157
		PHPUnit_Framework_Assert::assertEquals($statusCode, $this->getOCSResponse($this->response));
158
	}
159
160
	/**
161
	 * @Then /^the HTTP status code should be "([^"]*)"$/
162
	 * @param int $statusCode
163
	 */
164
	public function theHTTPStatusCodeShouldBe($statusCode) {
165
		PHPUnit_Framework_Assert::assertEquals($statusCode, $this->response->getStatusCode());
166
	}
167
168
	/**
169
	 * @param ResponseInterface $response
170
	 */
171
	private function extracRequestTokenFromResponse(ResponseInterface $response) {
172
		$this->requestToken = substr(preg_replace('/(.*)data-requesttoken="(.*)">(.*)/sm', '\2', $response->getBody()->getContents()), 0, 89);
173
	}
174
175
	/**
176
	 * @Given Logging in using web as :user
177
	 * @param string $user
178
	 */
179
	public function loggingInUsingWebAs($user) {
180
		$loginUrl = substr($this->baseUrl, 0, -5) . '/login';
181
		// Request a new session and extract CSRF token
182
		$client = new Client();
183
		$response = $client->get(
184
			$loginUrl,
185
			[
186
				'cookies' => $this->cookieJar,
187
			]
188
		);
189
		$this->extracRequestTokenFromResponse($response);
190
191
		// Login and extract new token
192
		$password = ($user === 'admin') ? 'admin' : '123456';
193
		$client = new Client();
194
		$response = $client->post(
195
			$loginUrl,
196
			[
197
				'body' => [
198
					'user' => $user,
199
					'password' => $password,
200
					'requesttoken' => $this->requestToken,
201
				],
202
				'cookies' => $this->cookieJar,
203
			]
204
		);
205
		$this->extracRequestTokenFromResponse($response);
206
	}
207
208
	/**
209
	 * @When Sending a :method to :url with requesttoken
210
	 * @param string $method
211
	 * @param string $url
212
	 */
213 View Code Duplication
	public function sendingAToWithRequesttoken($method, $url) {
214
		$baseUrl = substr($this->baseUrl, 0, -5);
215
216
		$client = new Client();
217
		$request = $client->createRequest(
218
			$method,
219
			$baseUrl . $url,
220
			[
221
				'cookies' => $this->cookieJar,
222
			]
223
		);
224
		$request->addHeader('requesttoken', $this->requestToken);
225
		try {
226
			$this->response = $client->send($request);
227
		} catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
228
			$this->response = $e->getResponse();
229
		}
230
	}
231
232
	/**
233
	 * @When Sending a :method to :url without requesttoken
234
	 * @param string $method
235
	 * @param string $url
236
	 */
237 View Code Duplication
	public function sendingAToWithoutRequesttoken($method, $url) {
238
		$baseUrl = substr($this->baseUrl, 0, -5);
239
240
		$client = new Client();
241
		$request = $client->createRequest(
242
			$method,
243
			$baseUrl . $url,
244
			[
245
				'cookies' => $this->cookieJar,
246
			]
247
		);
248
		try {
249
			$this->response = $client->send($request);
250
		} catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
251
			$this->response = $e->getResponse();
252
		}
253
	}
254
255
	public static function removeFile($path, $filename){
256
		if (file_exists("$path" . "$filename")) {
257
			unlink("$path" . "$filename");
258
		}
259
	}
260
261
	/**
262
	 * @Given User :user modifies text of :filename with text :text
263
	 * @param string $user
264
	 * @param string $filename
265
	 * @param string $text
266
	 */
267
	public function modifyTextOfFile($user, $filename, $text) {
268
		self::removeFile("../../data/$user/files", "$filename");
269
		file_put_contents("../../data/$user/files" . "$filename", "$text");
270
	}
271
272
	/**
273
	 * @BeforeSuite
274
	 */
275
	public static function addFilesToSkeleton(){
276
		for ($i=0; $i<5; $i++){
277
			file_put_contents("../../core/skeleton/" . "textfile" . "$i" . ".txt", "ownCloud test text file\n");
278
		}
279
		if (!file_exists("../../core/skeleton/FOLDER")) {
280
			mkdir("../../core/skeleton/FOLDER", 0777, true);
281
		}
282
		if (!file_exists("../../core/skeleton/PARENT")) {
283
			mkdir("../../core/skeleton/PARENT", 0777, true);
284
		}
285
		file_put_contents("../../core/skeleton/PARENT/" . "parent.txt", "ownCloud test text file\n");
286
		if (!file_exists("../../core/skeleton/PARENT/CHILD")) {
287
			mkdir("../../core/skeleton/PARENT/CHILD", 0777, true);
288
		}
289
		file_put_contents("../../core/skeleton/PARENT/CHILD/" . "child.txt", "ownCloud test text file\n");
290
	}
291
292
	/**
293
	 * @AfterSuite
294
	 */
295
	public static function removeFilesFromSkeleton(){
296
		for ($i=0; $i<5; $i++){
297
			self::removeFile("../../core/skeleton/", "textfile" . "$i" . ".txt");
298
		}
299
		if (is_dir("../../core/skeleton/FOLDER")) {
300
			rmdir("../../core/skeleton/FOLDER");
301
		}
302
		self::removeFile("../../core/skeleton/PARENT/CHILD/", "child.txt");
303
		if (is_dir("../../core/skeleton/PARENT/CHILD")) {
304
			rmdir("../../core/skeleton/PARENT/CHILD");
305
		}
306
		self::removeFile("../../core/skeleton/PARENT/", "parent.txt");
307
		if (is_dir("../../core/skeleton/PARENT")) {
308
			rmdir("../../core/skeleton/PARENT");
309
		}
310
	}
311
}
312
313