Completed
Pull Request — master (#16)
by Sergii
03:45
created

BaseEntity::entityUrl()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 23
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 7
cts 8
cp 0.875
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 9
nc 12
nop 3
crap 5.0488
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Utils;
6
7
/**
8
 * Trait BaseEntity.
9
 *
10
 * @package Drupal\TqExtension\Utils
11
 */
12
trait BaseEntity
13
{
14
    /**
15
     * @return string
16
     *   An entity type.
17
     */
18
    abstract protected function entityType();
19
20
    /**
21
     * @param string $argument1
22
     *   An argument to clarify the results.
23
     * @param string $argument2
24
     *   An argument to clarify the results.
25
     *
26
     * @return int
27
     *   An ID of the entity.
28
     */
29
    abstract public function getIdByArguments($argument1, $argument2);
30
31
    /**
32
     * Get identifier of current entity.
33
     *
34
     * @return int
35
     */
36
    public function getCurrentId()
37
    {
38
        // We have programmatically bootstrapped Drupal core, so able to use such functionality.
39
        $args = \DrupalKernelPlaceholder::arg();
40
41
        return count($args) > 1 && $this->entityType() === $args[0] && $args[1] > 0 ? (int) $args[1] : 0;
42
    }
43
44
    /**
45
     * @param string $operation
46
     *   Allowable values: "edit", "view", "visit".
47
     * @param string $argument1
48
     *   An argument to clarify the result.
49
     * @param string $argument2
50
     *   An argument to clarify the result.
51
     *
52
     * @return string
53
     *   Entity URL.
54
     */
55 4
    public function entityUrl($operation, $argument1 = '', $argument2 = '')
56
    {
57 4
        // Drupal 8 don't have the "entity/{id}/view" local action instead of Drupal 7. So,
58 4
        // to support both of versions, assume that "entity/{id}" is correct for "view" operation
59 4
        // in each case.
60
        // @todo Maybe we should use "DRUPAL_CORE > 7 ? '' : 'view'"?
61
        if (in_array($operation, ['visit', 'view'])) {
62 4
            $operation = '';
63
        }
64 4
65
        // An empty string could be passed when currently viewing entity expected.
66
        $id = '' === $argument1 ? $this->getCurrentId() : $this->getIdByArguments($argument1, $argument2);
67
68 4
        if (0 === $id) {
69
            throw new \RuntimeException('An ID cannot be zero.');
70
        }
71
72
        if ('' !== $operation) {
73
            $operation = "/$operation";
74
        }
75
76
        return $this->entityType() . "/$id$operation";
77
    }
78
}
79