Completed
Branch develop (876d53)
by Nate
01:53
created

AccessorByString::find()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember
7
 */
8
9
namespace flipbox\ember\services\traits\records;
10
11
use flipbox\ember\exceptions\RecordNotFoundException;
12
use yii\db\ActiveRecord as Record;
13
14
/**
15
 * @author Flipbox Factory <[email protected]>
16
 * @since 1.0.0
17
 *
18
 * @method Record parentFind($identifier)
19
 */
20
trait AccessorByString
21
{
22
    use Accessor {
23
        find as parentFind;
24
    }
25
26
    /**
27
     * @return string
28
     */
29
    abstract protected static function stringProperty(): string;
30
31
    /*******************************************
32
     * OVERRIDE
33
     *******************************************/
34
35
    /**
36
     * @param $identifier
37
     * @return Record|null
38
     */
39
    public function find($identifier)
40
    {
41
        if (!is_numeric($identifier) && is_string($identifier)) {
42
            return $this->findByString($identifier);
43
        }
44
45
        return $this->parentFind($identifier);
46
    }
47
48
    /*******************************************
49
     * FIND STRING
50
     *******************************************/
51
52
    /**
53
     * @param string $string
54
     * @return Record|null
55
     */
56
    public function findByString(string $string)
57
    {
58
        return $this->findByCondition(
59
            [self::stringProperty() => $string]
60
        );
61
    }
62
63
    /**
64
     * @param string $string
65
     * @throws RecordNotFoundException
66
     * @return Record|null
67
     */
68
    public function getByString(string $string)
69
    {
70
        if (null === ($record = $this->findByString($string))) {
71
            $this->notFoundByStringException($string);
72
        }
73
74
        return $record;
75
    }
76
77
    /**
78
     * @param string|null $string
79
     * @throws RecordNotFoundException
80
     */
81
    protected function notFoundByStringException(string $string = null)
82
    {
83
        throw new RecordNotFoundException(
84
            sprintf(
85
                'Record does not exist with the string "%s".',
86
                (string)$string
87
            )
88
        );
89
    }
90
}
91