Completed
Push — master ( ca3a05...58f804 )
by André
66:34 queued 43:18
created

TestCase::createFolder()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 32
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 32
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the Functional\TestCase class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 *
9
 * @version //autogentag//
10
 */
11
namespace eZ\Bundle\EzPublishRestBundle\Tests\Functional;
12
13
use Buzz\Message\Request as HttpRequest;
14
use Buzz\Message\Response as HttpResponse;
15
use PHPUnit_Framework_TestCase;
16
17
class TestCase extends PHPUnit_Framework_TestCase
18
{
19
    /**
20
     * @var \Buzz\Client\ClientInterface
21
     */
22
    private $httpClient;
23
24
    /**
25
     * @var string
26
     */
27
    private $httpHost;
28
29
    /**
30
     * @var string
31
     * Basic auth login:password
32
     */
33
    private $httpAuth;
34
35
    protected static $testSuffix;
36
37
    protected function setUp()
38
    {
39
        parent::setUp();
40
41
        $this->httpHost = getenv('EZP_TEST_REST_HOST') ?: 'localhost';
42
        $this->httpAuth = getenv('EZP_TEST_REST_AUTH') ?: 'admin:publish';
43
44
        $this->httpClient = new \Buzz\Client\Curl();
45
        $this->httpClient->setVerifyPeer(false);
46
        $this->httpClient->setTimeout(90);
47
        $this->httpClient->setOption(CURLOPT_FOLLOWLOCATION, false);
48
    }
49
50
    /**
51
     * @return HttpResponse
52
     */
53
    public function sendHttpRequest(HttpRequest $request)
54
    {
55
        $response = new HttpResponse();
56
        $this->httpClient->send($request, $response);
57
58
        return $response;
59
    }
60
61
    /**
62
     * @return HttpRequest
63
     */
64
    public function createHttpRequest($method, $uri, $contentType = '', $acceptType = '')
65
    {
66
        $request = new HttpRequest($method, $uri, $this->httpHost);
67
        $request->addHeader('Authorization: Basic ' . base64_encode($this->httpAuth));
68
        $request->addHeader('Content-Type: ' . $this->generateMediaTypeString($contentType));
69
        $request->addHeader('Accept: ' . $this->generateMediaTypeString($acceptType));
70
71
        return $request;
72
    }
73
74
    protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
75
    {
76
        $responseCode = $response->getStatusCode();
77
        if ($responseCode != $expected) {
78
            $errorMessageString = '';
79
            if (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+xml') !== false) {
80
                $body = \simplexml_load_string($response->getContent());
81
                $errorMessageString = $this->getHttpResponseCodeErrorMessage($body);
82
            } elseif (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+json') !== false) {
83
                $body = json_decode($response->getContent());
84
                $errorMessageString = $this->getHttpResponseCodeErrorMessage($body->ErrorMessage);
85
            }
86
87
            self::assertEquals($expected, $responseCode, $errorMessageString);
88
        }
89
    }
90
91
    private function getHttpResponseCodeErrorMessage($errorMessage)
92
    {
93
        $errorMessageString = <<< EOF
94
Server error message ({$errorMessage->errorCode}): {$errorMessage->errorMessage}
95
96
{$errorMessage->errorDescription}
97
98
EOF;
99
100
        // If server is in debug mode it will return file, line and trace.
101
        if (!empty($errorMessage->file)) {
102
            $errorMessageString .= "\nIn {$errorMessage->file}:{$errorMessage->line}\n\n{$errorMessage->trace}";
103
        } else {
104
            $errorMessageString .= "\nIn \<no trace, debug disabled\>";
105
        }
106
107
        return $errorMessageString;
108
    }
109
110
    protected function assertHttpResponseHasHeader(HttpResponse $response, $header, $expectedValue = null)
111
    {
112
        $headerValue = $response->getHeader($header);
113
        self::assertNotNull($headerValue, "Failed asserting that response has a $header header");
114
        if ($expectedValue !== null) {
115
            self::assertEquals($expectedValue, $headerValue);
116
        }
117
    }
118
119
    protected function generateMediaTypeString($typeString)
120
    {
121
        return "application/vnd.ez.api.$typeString";
122
    }
123
124
    protected function addCreatedElement($href)
125
    {
126
        $testCase = $this;
127
        self::$createdContent[$href] = function () use ($href, $testCase) {
128
            $testCase->sendHttpRequest(
129
                $testCase->createHttpRequest('DELETE', $href)
130
            );
131
        };
132
    }
133
134
    public static function tearDownAfterClass()
135
    {
136
        self::clearCreatedElement(self::$createdContent);
137
    }
138
139
    private static function clearCreatedElement(array $contentArray)
140
    {
141
        foreach (array_reverse($contentArray) as $href => $callback) {
142
            $callback();
143
        }
144
    }
145
146
    /**
147
     * @param string $parentLocationId The REST id of the parent location
148
     *
149
     * @return array created Content, as an array
150
     */
151
    protected function createFolder($string, $parentLocationId)
152
    {
153
        $string = $this->addTestSuffix($string);
154
        $xml = <<< XML
155
<?xml version="1.0" encoding="UTF-8"?>
156
<ContentCreate>
157
  <ContentType href="/api/ezp/v2/content/types/1" />
158
  <mainLanguageCode>eng-GB</mainLanguageCode>
159
  <LocationCreate>
160
    <ParentLocation href="{$parentLocationId}" />
161
    <priority>0</priority>
162
    <hidden>false</hidden>
163
    <sortField>PATH</sortField>
164
    <sortOrder>ASC</sortOrder>
165
  </LocationCreate>
166
  <Section href="/api/ezp/v2/content/sections/1" />
167
  <alwaysAvailable>true</alwaysAvailable>
168
  <remoteId>{$string}</remoteId>
169
  <User href="/api/ezp/v2/user/users/14" />
170
  <modificationDate>2012-09-30T12:30:00</modificationDate>
171
  <fields>
172
    <field>
173
      <fieldDefinitionIdentifier>name</fieldDefinitionIdentifier>
174
      <languageCode>eng-GB</languageCode>
175
      <fieldValue>{$string}</fieldValue>
176
    </field>
177
  </fields>
178
</ContentCreate>
179
XML;
180
181
        return $this->createContent($xml);
182
    }
183
184
    /**
185
     * @param $xml
186
     *
187
     * @return array Content key of the Content struct array
188
     */
189
    protected function createContent($xml)
190
    {
191
        $request = $this->createHttpRequest('POST', '/api/ezp/v2/content/objects', 'ContentCreate+xml', 'Content+json');
192
        $request->setContent($xml);
193
194
        $response = $this->sendHttpRequest($request);
195
196
        self::assertHttpResponseCodeEquals($response, 201);
197
198
        $content = json_decode($response->getContent(), true);
199
200
        if (!isset($content['Content']['CurrentVersion']['Version'])) {
201
            self::fail("Incomplete response (no version):\n" . $response->getContent() . "\n");
202
        }
203
204
        $response = $this->sendHttpRequest(
205
            $request = $this->createHttpRequest('PUBLISH', $content['Content']['CurrentVersion']['Version']['_href'])
206
        );
207
208
        self::assertHttpResponseCodeEquals($response, 204);
209
210
        $this->addCreatedElement($content['Content']['_href'], true);
211
212
        return $content['Content'];
213
    }
214
215
    /**
216
     * @param string $contentHref
217
     *
218
     * @return array
219
     */
220 View Code Duplication
    protected function getContentLocations($contentHref)
221
    {
222
        $response = $this->sendHttpRequest(
223
            $this->createHttpRequest('GET', "$contentHref/locations", '', 'LocationList+json')
224
        );
225
        self::assertHttpResponseCodeEquals($response, 200);
226
        $folderLocations = json_decode($response->getContent(), true);
227
228
        return $folderLocations;
229
    }
230
231
    protected function addTestSuffix($string)
232
    {
233
        if (!isset(self::$testSuffix)) {
234
            self::$testSuffix = uniqid();
235
        }
236
237
        return $string . '_' . self::$testSuffix;
238
    }
239
240
    /**
241
     * List of REST contentId (/content/objects/12345) created by tests.
242
     *
243
     * @var array
244
     */
245
    private static $createdContent = array();
246
}
247