IdFactoryDecoratorTrait::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\id\Helper;
6
7
use byrokrat\id\IdFactoryInterface;
8
use byrokrat\id\FailingIdFactory;
9
use byrokrat\id\IdInterface;
10
use byrokrat\id\Exception;
11
12
/**
13
 * Implements a factory decorator that pass on object creation to decorated factory on failure
14
 */
15
trait IdFactoryDecoratorTrait
16
{
17
    /**
18
     * @var IdFactoryInterface
19
     */
20
    private $decoratedFactory;
21
22
    public function __construct(IdFactoryInterface $decoratedFactory = null)
23
    {
24
        $this->decoratedFactory = $decoratedFactory ?: new FailingIdFactory();
25
    }
26
27
    public function createId(string $raw, \DateTimeInterface $atDate = null): IdInterface
28
    {
29
        try {
30
            return $this->createNewInstance($raw, $atDate);
31
        } catch (Exception $e) {
32
            return $this->decoratedFactory->createId($raw, $atDate);
33
        }
34
    }
35
36
    abstract protected function createNewInstance(string $raw, \DateTimeInterface $atDate = null): IdInterface;
37
}
38