GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( e7fb79...adc388 )
by
unknown
87:37 queued 75:31
created

getRepositoriesInternal()   B

Complexity

Conditions 9
Paths 12

Size

Total Lines 55
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 9

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 55
ccs 37
cts 37
cp 1
rs 7.2446
cc 9
eloc 34
nc 12
nop 1
crap 9

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Dkd\PhpCmis\Bindings\Browser;
3
4
/*
5
 * This file is part of php-cmis-client.
6
 *
7
 * (c) Sascha Egerer <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
use Dkd\PhpCmis\Bindings\BindingSessionInterface;
14
use Dkd\PhpCmis\Bindings\CmisBindingsHelper;
15
use Dkd\PhpCmis\Bindings\LinkAccessInterface;
16
use Dkd\PhpCmis\Constants;
17
use Dkd\PhpCmis\Data\AclInterface;
18
use Dkd\PhpCmis\Data\PropertiesInterface;
19
use Dkd\PhpCmis\DataObjects\RepositoryInfo;
20
use Dkd\PhpCmis\DataObjects\RepositoryInfoBrowserBinding;
21
use Dkd\PhpCmis\Definitions\TypeDefinitionInterface;
22
use Dkd\PhpCmis\Enum\DateTimeFormat;
23
use Dkd\PhpCmis\Exception\CmisBaseException;
24
use Dkd\PhpCmis\Exception\CmisConnectionException;
25
use Dkd\PhpCmis\Exception\CmisConstraintException;
26
use Dkd\PhpCmis\Exception\CmisInvalidArgumentException;
27
use Dkd\PhpCmis\Exception\CmisNotSupportedException;
28
use Dkd\PhpCmis\Exception\CmisObjectNotFoundException;
29
use Dkd\PhpCmis\Exception\CmisPermissionDeniedException;
30
use Dkd\PhpCmis\Exception\CmisProxyAuthenticationException;
31
use Dkd\PhpCmis\Exception\CmisRuntimeException;
32
use Dkd\PhpCmis\Exception\CmisUnauthorizedException;
33
use Dkd\PhpCmis\SessionParameter;
34
use GuzzleHttp\Client;
35
use GuzzleHttp\Psr7\Response;
36
use GuzzleHttp\Stream\StreamInterface;
37
use GuzzleHttp\Exception\RequestException;
38
use function json_decode;
39
use League\Url\Url;
40
use Psr\Http\Message\ResponseInterface;
41
42
/**
43
 * Base class for all Browser Binding client services.
44
 */
45
abstract class AbstractBrowserBindingService implements LinkAccessInterface
46
{
47
    /**
48
     * @var BindingSessionInterface
49
     */
50
    protected $session;
51
52
    /**
53
     * @var boolean
54
     */
55
    protected $succinct;
56
57
    /**
58
     * @var CmisBindingsHelper
59
     */
60
    protected $cmisBindingsHelper;
61
62
    /**
63
     * @var DateTimeFormat
64
     */
65
    protected $dateTimeFormat;
66
67
    /**
68
     * @param BindingSessionInterface $session
69 168
     * @param CmisBindingsHelper|null $cmisBindingsHelper
70
     */
71 168
    public function __construct(BindingSessionInterface $session, $cmisBindingsHelper = null)
72 168
    {
73 168
        $this->setCmisBindingsHelper($cmisBindingsHelper);
74
        $this->setSession($session);
75
    }
76
77
    /**
78
     * Set cmis binding helper property
79
     *
80
     * @param CmisBindingsHelper|null $cmisBindingsHelper The cmis binding helper that should be defined.
81 168
     * If <code>null</code> is given a new instance of CmisBindingsHelper will be created.
82
     */
83 168
    protected function setCmisBindingsHelper($cmisBindingsHelper = null)
84 168
    {
85
        $this->cmisBindingsHelper = ($cmisBindingsHelper === null) ? new CmisBindingsHelper() : $cmisBindingsHelper;
86
    }
87
88
    /**
89
     * Get the url for an object
90
     *
91
     * @param string $repositoryId
92
     * @param string $objectId
93
     * @param string|null $selector
94
     * @throws CmisConnectionException
95
     * @throws CmisObjectNotFoundException
96 2
     * @return Url
97
     */
98 2 View Code Duplication
    protected function getObjectUrl($repositoryId, $objectId, $selector = null)
99
    {
100 2
        $result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $objectId, $selector);
101 1
102 1
        if ($result === null) {
103 1
            $this->getRepositoriesInternal($repositoryId);
104
            $result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $objectId, $selector);
105 2
        }
106 1
107 1
        if ($result === null) {
108 1
            throw new CmisObjectNotFoundException(
109 1
                sprintf(
110 1
                    'Unknown Object! Repository: "%s" | Object: "%s" | Selector: "%s"',
111
                    $repositoryId,
112 1
                    $objectId,
113 1
                    $selector
114
                )
115
            );
116 1
        }
117
118
        return $result;
119
    }
120
121
    /**
122
     * Returns the repository URL cache or creates a new cache if it doesn't
123
     * exist.
124
     *
125 2
     * @return RepositoryUrlCache
126
     */
127 2
    protected function getRepositoryUrlCache()
128 2
    {
129 1
        $repositoryUrlCache = $this->getSession()->get(SessionParameter::REPOSITORY_URL_CACHE);
130 1
        if ($repositoryUrlCache === null) {
131 1
            $repositoryUrlCache = new RepositoryUrlCache();
132
            $this->getSession()->put(SessionParameter::REPOSITORY_URL_CACHE, $repositoryUrlCache);
133 2
        }
134
135
        return $repositoryUrlCache;
136
    }
137
138
    /**
139
     * Get current session
140
     *
141 66
     * @return BindingSessionInterface
142
     */
143 66
    public function getSession()
144
    {
145
        return $this->session;
146
    }
147
148
    /**
149
     * Sets the current session.
150
     *
151 168
     * @param BindingSessionInterface $session
152
     */
153 168
    protected function setSession(BindingSessionInterface $session)
154 168
    {
155 168
        $this->session = $session;
156
        $succinct = $session->get(SessionParameter::BROWSER_SUCCINCT);
157 168
        $this->succinct = $succinct ?? true;
158 168
159
        $this->dateTimeFormat = DateTimeFormat::cast($session->get(SessionParameter::BROWSER_DATETIME_FORMAT));
160
    }
161
162
    /**
163
     * Retrieves the the repository info objects.
164
     *
165
     * @param string|null $repositoryId
166
     * @throws CmisConnectionException
167 8
     * @return RepositoryInfo[] Returns ALL Repository Infos that are available and not just the one requested by id.
168
     */
169 8
    protected function getRepositoriesInternal($repositoryId = null)
170
    {
171 8
        $repositoryUrlCache = $this->getRepositoryUrlCache();
172
173 6
        if ($repositoryId === null) {
174 6
            // no repository id provided -> get all
175
            $url = $repositoryUrlCache->buildUrl($this->getServiceUrl());
176 2
        } else {
177 2
            // use URL of the specified repository
178
            $url = $repositoryUrlCache->getRepositoryUrl($repositoryId, Constants::SELECTOR_REPOSITORY_INFO) ??
179 1
                $repositoryUrlCache->buildUrl($this->getServiceUrl());
180 1
        }
181
182
        $repositoryInfos = [];
183 8
        $result = $this->readJson($url);
184 8
        if (!is_array($result)) {
185 8
            throw new CmisConnectionException(
186
                'Could not fetch repository info! Response is not a valid JSON.',
187 8
                1416343166
188 8
            );
189 1
        }
190 1
        foreach ($result as $item) {
191
            if (is_array($item)) {
192 1
                $repositoryInfo = $this->getJsonConverter()->convertRepositoryInfo($item);
193
194 7
                if ($repositoryInfo instanceof RepositoryInfoBrowserBinding) {
195 7
                    $id = $repositoryInfo->getId();
196 6
                    $repositoryUrl = $repositoryInfo->getRepositoryUrl();
197
                    $rootUrl = $repositoryInfo->getRootUrl();
198 6
199 6
                    if (empty($id) || empty($repositoryUrl) || empty($rootUrl)) {
200 6
                        throw new CmisConnectionException(
201 6
                            sprintf('Found invalid Repository Info! (id: %s)', $id),
202
                            1415187765
203 6
                        );
204 3
                    }
205 3
206
                    $this->getRepositoryUrlCache()->addRepository($id, $repositoryUrl, $rootUrl);
207 3
208
                    $repositoryInfos[] = $repositoryInfo;
209
                }
210 3
            } else {
211
                throw new CmisConnectionException(
212 3
                    sprintf(
213 3
                        'Found invalid repository info! Value of type "array" was expected'
214 3
                        . 'but value of type "%s" was given.',
215 1
                        gettype($item)
216 1
                    ),
217
                    1415187764
218 1
                );
219 1
            }
220 1
        }
221
222 1
        return $repositoryInfos;
223
    }
224 3
225
    /**
226 3
     * Returns the service URL of this session.
227
     *
228
     * @return string|null
229
     */
230
    protected function getServiceUrl()
231
    {
232
        return $this->getSession()->get(SessionParameter::BROWSER_URL);
233
    }
234 2
235
    /**
236 2
     * Wrapper to read URL response as JSON as is the general use case.
237 2
     *
238 1
     * @param Url $url
239
     * @return mixed
240
     */
241 1
    protected function readJson(Url $url)
242
    {
243
        return json_decode($this->read($url)->getBody(), true);
244
    }
245
246
    /**
247
     * Do a get request for the given url
248
     *
249
     * @param Url $url
250
     * @return Response
251
     * @throws CmisBaseException an more specific exception of this type could be thrown. For more details see
252 3
     * @see AbstractBrowserBindingService::convertStatusCode()
253
     */
254
    protected function read(Url $url)
255
    {
256 3
        /** @var Response $response */
257 3
        try {
258 2
            $response = $this->getHttpInvoker()->get((string) $url);
259 2
        } catch (RequestException $exception) {
260 2
            $code = 0;
261 2
            $message = null;
262 2
            if ($exception->getResponse()) {
263 2
                $code = $exception->getResponse()->getStatusCode();
264 2
                $message = $exception->getResponse()->getBody();
265 2
            }
266 2
            throw $this->convertStatusCode(
267
                $code,
268 2
                (string) $message,
269
                $exception
270
            );
271 1
        }
272
273
        return $response;
274
    }
275
276
    /**
277
     * Get a HTTP Invoker instance
278
     *
279 4
     * @return Client
280
     */
281
    protected function getHttpInvoker()
282 4
    {
283
        return $this->cmisBindingsHelper->getHttpInvoker($this->getSession());
284 4
    }
285
286
    /**
287
     * Converts an error message or a HTTP status code into an Exception.
288
     *
289
     * @see http://docs.oasis-open.org/cmis/CMIS/v1.1/os/CMIS-v1.1-os.html#x1-551021r549
290
     *
291
     * @param integer $code
292
     * @param string $message
293
     * @param null|\Exception $exception
294
     * @return CmisBaseException
295
     */
296
    protected function convertStatusCode($code, $message, \Exception $exception = null)
297 26
    {
298
        $messageData = json_decode($message, true);
299 26
300
        if (is_array($messageData) && !empty($messageData[JSONConstants::ERROR_EXCEPTION])) {
301 26
            $jsonError = $messageData[JSONConstants::ERROR_EXCEPTION];
302 13
303
            if (!empty($messageData[JSONConstants::ERROR_MESSAGE])
304 13
                && is_string($messageData[JSONConstants::ERROR_MESSAGE])
305 13
            ) {
306 13
                $message = $messageData[JSONConstants::ERROR_MESSAGE];
307 13
            }
308 13
309
            $exceptionName = '\\Dkd\\PhpCmis\\Exception\\Cmis' . ucfirst($jsonError) . 'Exception';
310 13
311
            if (class_exists($exceptionName)) {
312 13
                return new $exceptionName($message, null, $exception);
313 12
            }
314
        }
315 1
316
        if (empty($message) && $exception !== null) {
317 14
            $message = $exception->getMessage();
318
        }
319
320
        // fall back to status code
321
        switch ($code) {
322
            case 301:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
323 14
            case 302:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
324 14
            case 303:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
325 14
            case 307:
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
326 14
                return new CmisConnectionException(
327 4
                    'Redirects are not supported (HTTP status code ' . $code . '): ' . $message,
328 4
                    null,
329 4
                    $exception
330
                );
331 4
            case 400:
332 10
                return new CmisInvalidArgumentException($message, null, $exception);
333 1
            case 401:
334 9
                return new CmisUnauthorizedException($message, null, $exception);
335 1
            case 403:
336 8
                return new CmisPermissionDeniedException($message, null, $exception);
337 1
            case 404:
338 7
                return new CmisObjectNotFoundException($message, null, $exception);
339 1
            case 405:
340 6
                return new CmisNotSupportedException($message, null, $exception);
341 1
            case 407:
342 5
                return new CmisProxyAuthenticationException($message, null, $exception);
343 1
            case 409:
344 4
                return new CmisConstraintException($message, null, $exception);
345 1
            default:
346 3
                return new CmisRuntimeException($message, null, $exception);
347 3
        }
348 3
    }
349
350
    // ---- helpers ----
351
352
    /**
353
     * Returns JSON Converter instance
354
     *
355
     * @return \Dkd\PhpCmis\Converter\JsonConverter
356
     */
357
    protected function getJsonConverter()
358 65
    {
359
        return $this->cmisBindingsHelper->getJsonConverter($this->getSession());
360 65
    }
361
362
    /**
363
     * Generate url for a given path of a given repository.
364
     *
365
     * @param string $repositoryId
366
     * @param string $path
367
     * @param string|null $selector
368
     * @throws CmisConnectionException
369
     * @throws CmisObjectNotFoundException
370
     * @return Url
371
     */
372 View Code Duplication
    protected function getPathUrl($repositoryId, $path, $selector = null)
373 2
    {
374
        $result = $this->getRepositoryUrlCache()->getPathUrl($repositoryId, $path, $selector);
375 2
376
        if ($result === null) {
377 2
            $this->getRepositoriesInternal($repositoryId);
378 1
            $result = $this->getRepositoryUrlCache()->getPathUrl($repositoryId, $path, $selector);
379 1
        }
380 1
381
        if ($result === null) {
382 2
            throw new CmisObjectNotFoundException(
383 1
                sprintf(
384 1
                    'Unknown path! Repository: "%s" | Path: "%s" | Selector: "%s"',
385 1
                    $repositoryId,
386 1
                    $path,
387 1
                    $selector
388
                )
389 1
            );
390 1
        }
391
392
        return $result;
393 1
    }
394
395
// ---- URL ----
396
397
    /**
398
     * Get if succinct mode is used
399
     *
400
     * @return boolean
401
     */
402
    protected function getSuccinct()
403 46
    {
404
        return $this->succinct;
405 46
    }
406
407
    /**
408
     * Wrapper for calling post() and reading response as JSON, as is the general use case.
409
     *
410
     * @param Url $url
411
     * @param array $content
412
     * @param array $headers
413
     * @return mixed
414
     */
415
    protected function postJson(Url $url, $content = [], array $headers = [])
416
    {
417
        return \json_decode($this->post($url, $content, $headers)->getBody(), true);
418
    }
419 2
420
    /**
421 2
     * Performs a POST on an URL, checks the response code and returns the
422
     * result.
423
     *
424
     * @param Url $url Request url
425 2
     * @param resource|string|StreamInterface|array $content Entity body data or an array for POST fields and files
426 2
     * @param array $headers Additional header options
427 1
     * @return ResponseInterface
428 1
     * @throws CmisBaseException an more specific exception of this type could be thrown. For more details see
429 1
     * @see AbstractBrowserBindingService::convertStatusCode()
430
     */
431 1
    protected function post(Url $url, $content = [], array $headers = [])
432
    {
433
        $headers['form_params'] = $content;
434 1
435
        try {
436
            return $this->getHttpInvoker()->post((string) $url, $headers);
437
        } catch (RequestException $exception) {
438
            throw $this->convertStatusCode(
439
                $exception->getResponse()->getStatusCode(),
440
                (string) $exception->getResponse()->getBody(),
441
                $exception
442
            );
443
        }
444
    }
445 3
446
    /**
447 3
     * Retrieves a type definition.
448 1
     *
449
     * @param string $repositoryId
450
     * @param string $typeId
451 2
     * @return TypeDefinitionInterface|null
452 1
     * @throws CmisInvalidArgumentException if repository id or type id is <code>null</code>
453
     */
454
    protected function getTypeDefinitionInternal($repositoryId, $typeId)
455
    {
456 1
        if (empty($repositoryId)) {
457 1
            throw new CmisInvalidArgumentException('Repository id must not be empty!');
458
        }
459 1
460 1
        if (empty($typeId)) {
461 1
            throw new CmisInvalidArgumentException('Type id must not be empty!');
462
        }
463 1
464 1
        // build URL
465
        $url = $this->getRepositoryUrl($repositoryId, Constants::SELECTOR_TYPE_DEFINITION);
466
        $url->getQuery()->modify([Constants::PARAM_TYPE_ID => $typeId]);
467
468
        return $this->getJsonConverter()->convertTypeDefinition(
469
            (array) $this->readJson($url)
470
        );
471
    }
472
473
    /**
474
     * Get url for a repository
475
     *
476 2
     * @param string $repositoryId
477
     * @param string|null $selector
478 2
     * @throws CmisConnectionException
479
     * @throws CmisObjectNotFoundException
480 2
     * @return Url
481 1
     */
482 1 View Code Duplication
    protected function getRepositoryUrl($repositoryId, $selector = null)
483 1
    {
484
        $result = $this->getRepositoryUrlCache()->getRepositoryUrl($repositoryId, $selector);
485 2
486 1
        if ($result === null) {
487 1
            $this->getRepositoriesInternal($repositoryId);
488 1
            $result = $this->getRepositoryUrlCache()->getRepositoryUrl($repositoryId, $selector);
489 1
        }
490
491 1
        if ($result === null) {
492 1
            throw new CmisObjectNotFoundException(
493
                sprintf(
494
                    'Unknown repository! Repository: "%s" | Selector: "%s"',
495 1
                    $repositoryId,
496
                    $selector
497
                )
498
            );
499
        }
500
501
        return $result;
502
    }
503
504
    /**
505
     * Converts a Properties list into an array that can be used for the CMIS request.
506 13
     *
507
     * @param PropertiesInterface $properties
508 13
     * @return array Example <code>
509
     * array('propertyId' => array(0 => 'myId'), 'propertyValue' => array(0 => 'valueOfMyId'))
510 13
     * </code>
511 13
     */
512 13
    protected function convertPropertiesToQueryArray(PropertiesInterface $properties)
513 13
    {
514 13
        $propertiesArray = [];
515
516 13
        $propertyCounter = 0;
517
        $propertiesArray[Constants::CONTROL_PROP_ID] = [];
518 13
        $propertiesArray[Constants::CONTROL_PROP_VALUE] = [];
519 13
        foreach ($properties->getProperties() as $property) {
520 13
            $propertiesArray[Constants::CONTROL_PROP_ID][$propertyCounter] = $property->getId();
521 13
522 13
            $propertyValues = $property->getValues();
523 13
524 1
            if (count($propertyValues) === 1) {
525 1
                $propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter] =
526 1
                    $this->convertPropertyValueToSimpleType(
527 1
                        $property->getFirstValue()
528 1
                    );
529
            } elseif (count($propertyValues) > 1) {
530 1
                $propertyValueCounter = 0;
531 1
                $propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter] = [];
532 1
                foreach ($propertyValues as $propertyValue) {
533 1
                    $propertiesArray[Constants::CONTROL_PROP_VALUE][$propertyCounter][$propertyValueCounter] =
534
                        $this->convertPropertyValueToSimpleType(
535 13
                            $propertyValue
536 13
                        );
537
                    $propertyValueCounter ++;
538 13
                }
539
            }
540
541
            $propertyCounter ++;
542
        }
543
544
        return $propertiesArray;
545
    }
546
547 13
    /**
548
     * Converts values to a format that can be used for the CMIS Browser binding request.
549 13
     *
550
     * @param mixed $value
551 1
     * @return mixed
552 13
     */
553
    protected function convertPropertyValueToSimpleType($value)
554 1
    {
555 1
        if ($value instanceof \DateTime) {
556
            // CMIS expects a timestamp in milliseconds
557 13
            $value = $value->getTimestamp() * 1000;
558
        } elseif (is_bool($value)) {
559
			// Booleans must be represented in string form since request will fail if cast to integer
560
			$value = $value ? 'true' : 'false';
561
		}
562
563
        return $value;
564
    }
565
566
    /**
567
     * Converts a Access Control list into an array that can be used for the CMIS request
568
     *
569
     * @param AclInterface $acl
570
     * @param string $principalControl one of principal ace constants
571
     * CONTROL_ADD_ACE_PRINCIPAL or CONTROL_REMOVE_ACE_PRINCIPAL
572
     * @param string $permissionControl one of permission ace constants
573 7
     * CONTROL_REMOVE_ACE_PRINCIPAL or CONTROL_REMOVE_ACE_PERMISSION
574
     * @return array Example <code>
575 7
     * array('addACEPrincipal' => array(0 => 'principalId'),
576 7
     *       'addACEPermission' => array(0 => array(0 => 'permissonValue')))
577
     * </code>
578 7
     */
579 7
    protected function convertAclToQueryArray(AclInterface $acl, $principalControl, $permissionControl)
580 7
    {
581 7
        $acesArray = [];
582 7
        $principalCounter = 0;
583 7
584
        foreach ($acl->getAces() as $ace) {
585 7
            $permissions = $ace->getPermissions();
586 7
            if ($ace->getPrincipal() !== null && $ace->getPrincipal()->getId() && !empty($permissions)) {
587 7
                $acesArray[$principalControl][$principalCounter] = $ace->getPrincipal()->getId();
588 7
                $permissionCounter = 0;
589
                $acesArray[$permissionControl][$principalCounter] = [];
590 7
591 7
                foreach ($permissions as $permission) {
592 7
                    $acesArray[$permissionControl][$principalCounter][$permissionCounter] = $permission;
593
                    $permissionCounter ++;
594 7
                }
595
596
                $principalCounter ++;
597
            }
598
        }
599
600
        return $acesArray;
601
    }
602
603 10
    /**
604
     * Converts a policies array into an array that can be used for the CMIS request
605 10
     *
606 10
     * @param string[] $policies A list of policy string representations
607
     * @return array
608 10
     */
609 6
    protected function convertPolicyIdArrayToQueryArray(array $policies)
610 6
    {
611 10
        $policiesArray = [];
612
        $policyCounter = 0;
613 10
614
        foreach ($policies as $policy) {
615
            $policiesArray[Constants::CONTROL_POLICY][$policyCounter] = (string) $policy;
616
            $policyCounter ++;
617
        }
618
619
        return $policiesArray;
620
    }
621 32
622
    /**
623 32
     * Returns the date time format
624
     *
625
     * @return DateTimeFormat
626
     */
627
    public function getDateTimeFormat()
628
    {
629
        return $this->dateTimeFormat;
630
    }
631 1
632
    /**
633 1
     * Sets the date time format
634 1
     *
635
     * @param DateTimeFormat $dateTimeFormat
636
     */
637
    public function setDateTimeFormat(DateTimeFormat $dateTimeFormat)
638
    {
639
        $this->dateTimeFormat = $dateTimeFormat;
640
    }
641
642
    /**
643
     * Appends policies parameters to url
644
     *
645
     * @param Url $url
646
     * @param string[] $policies A list of policy IDs that must be applied to the newly created document object
647
     */
648
    protected function appendPoliciesToUrl(Url $url, array $policies)
649
    {
650
        if (!empty($policies)) {
651
            $url->getQuery()->modify($this->convertPolicyIdArrayToQueryArray($policies));
652
        }
653
    }
654
655
    /**
656
     * Appends addAces parameters to url
657
     *
658
     * @param Url $url
659
     * @param AclInterface|null $addAces A list of ACEs
660
     */
661 View Code Duplication
    protected function appendAddAcesToUrl(Url $url, AclInterface $addAces = null)
662
    {
663
        if ($addAces !== null) {
664
            $url->getQuery()->modify(
665
                $this->convertAclToQueryArray(
666
                    $addAces,
667
                    Constants::CONTROL_ADD_ACE_PRINCIPAL,
668
                    Constants::CONTROL_ADD_ACE_PERMISSION
669
                )
670
            );
671
        }
672
    }
673
674
    /**
675
     * Appends removeAces parameters to url
676
     *
677
     * @param Url $url
678
     * @param AclInterface|null $removeAces A list of ACEs
679
     */
680 View Code Duplication
    protected function appendRemoveAcesToUrl(Url $url, AclInterface $removeAces = null)
681
    {
682
        if ($removeAces !== null) {
683
            $url->getQuery()->modify(
684
                $this->convertAclToQueryArray(
685
                    $removeAces,
686
                    Constants::CONTROL_REMOVE_ACE_PRINCIPAL,
687
                    Constants::CONTROL_REMOVE_ACE_PERMISSION
688
                )
689
            );
690
        }
691
    }
692
693
    /**
694
     * Gets the content link from the cache if it is there or loads it into the
695
     * cache if it is not there.
696
     *
697
     * @param string $repositoryId
698
     * @param string $documentId
699
     * @return string|null
700
     */
701
    public function loadContentLink($repositoryId, $documentId)
702
    {
703
        $result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $documentId, Constants::SELECTOR_CONTENT);
704
        return $result === null ? null : (string) $result;
705
    }
706
707
    /**
708
     * Gets a rendition content link from the cache if it is there or loads it
709
     * into the cache if it is not there.
710
     *
711
     * @param string $repositoryId
712
     * @param string $documentId
713
     * @param string $streamId
714
     * @return string|null
715
     */
716
    public function loadRenditionContentLink($repositoryId, $documentId, $streamId)
717
    {
718
        $result = $this->getRepositoryUrlCache()->getObjectUrl($repositoryId, $documentId, Constants::SELECTOR_CONTENT);
719
        if ($result !== null) {
720
            $result->getQuery()->modify([Constants::PARAM_STREAM_ID => $streamId]);
721
            $result = (string) $result;
722
        }
723
        return $result;
724
    }
725
}
726