Completed
Push — master ( a36a2e...782846 )
by Sergii
05:45
created

RawNodeContext::getIdByArguments()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 20
rs 9.2
cc 4
eloc 11
nc 3
nop 2
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Context\Node;
6
7
// Contexts.
8
use Drupal\TqExtension\Context\RawTqContext;
9
10
// Utils.
11
use Drupal\TqExtension\Utils\Database\FetchField;
12
use Drupal\TqExtension\Utils\BaseEntity;
13
14
class RawNodeContext extends RawTqContext
15
{
16
    use BaseEntity;
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    protected function entityType()
22
    {
23
        return 'node';
24
    }
25
26
    /**
27
     * @param string $title
28
     *   Inaccurate title of a node.
29
     * @param string $contentType
30
     *   Content type. Could be a title of content type.
31
     *
32
     * @return int
33
     *
34
     * @throws \InvalidArgumentException
35
     */
36
    protected function getIdByArguments($title, $contentType = '')
37
    {
38
        $nid = new FetchField('node', 'nid');
39
        $nid->condition('title', "%$title", 'like');
40
41
        // Try to recognize node type by its title if content type specified and does not exist.
42
        if ('' !== $contentType && !isset(node_type_get_types()[$contentType])) {
43
            $contentType = (new FetchField('node_type', 'type'))
44
                ->condition('name', $contentType)
45
                ->execute();
46
47
            if ('' === $contentType) {
48
                throw new \InvalidArgumentException('Content type with such name does not exist!');
49
            }
50
51
            $nid->condition('type', $contentType);
52
        }
53
54
        return $nid->execute();
55
    }
56
}
57