Completed
Push — master ( 8184b0...a4b4a5 )
by Douglas
02:13
created

InMemoryRobotStore::log()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2.032
1
<?php
2
3
/**
4
 * (c) 2018 Douglas Reith.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
declare(strict_types=1);
10
11
namespace Reith\ToyRobot\Infrastructure\Persistence;
12
13
use Psr\Log\LoggerInterface;
14
use Reith\ToyRobot\Domain\Robot\Robot;
15
16
/**
17
 * Class: InMemoryRobotStore
18
 *
19
 * This store is used in testing scenarios. Though if we implement an
20
 * interactive mode, then we could use this instead of FileRobotStore.
21
 *
22
 * @see RobotStoreInterface
23
 */
24
class InMemoryRobotStore implements RobotStoreInterface
25
{
26
    private static $store;
27
28
    private $logger;
29
30
    private $robot;
31
32
    /**
33
     * __construct.
34
     *
35
     * @param LoggerInterface|null $logger
36
     */
37 1
    private function __construct(?LoggerInterface $logger = null)
38
    {
39 1
        $this->logger = $logger;
40 1
    }
41
42
    /**
43
     * @param LoggerInterface|null $logger
44
     *
45
     * @return RobotStoreInterface
46
     */
47 4
    public static function getStore(?LoggerInterface $logger = null): RobotStoreInterface
48
    {
49
        // Ensure the same store is used everywhere
50 4
        if (!self::$store) {
51 1
            self::$store = self::createStore($logger);
52
        }
53
54 4
        return self::$store;
55
    }
56
57
    /**
58
     * @param LoggerInterface|null $logger
59
     *
60
     * @return RobotStoreInterface
61
     */
62 1
    private static function createStore(?LoggerInterface $logger): RobotStoreInterface
63
    {
64 1
        return new static($logger);
65
    }
66
67
    /**
68
     * @return Robot|null
69
     */
70 2
    public function getRobot(): ?Robot
71
    {
72 2
        return $this->robot;
73
    }
74
75
    /**
76
     * @param Robot $robot
77
     */
78 2
    public function saveRobot(Robot $robot): void
79
    {
80 2
        $this->robot = $robot;
81 2
        $this->log('Saved robot');
82 2
    }
83
84
    /**
85
     * @param string $msg
86
     */
87 2
    private function log(string $msg): void
88
    {
89 2
        if (!$this->logger) {
90
            return;
91
        }
92
93 2
        $this->logger->info($msg);
94 2
    }
95
}
96