FileSessionStorage::save()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 12
1
<?php
2
3
namespace mb24dev\AmoCRM\SessionStorage;
4
5
use mb24dev\AmoCRM\Session\Session;
6
use mb24dev\AmoCRM\Session\SessionDoesNotExistException;
7
use mb24dev\AmoCRM\Session\SessionDoNotSavedException;
8
use mb24dev\AmoCRM\User\UserInterface;
9
10
/**
11
 * Class FileSessionStorage
12
 *
13
 * @package mb24dev\AmoCRM\Session
14
 */
15
class FileSessionStorage implements SessionStorageInterface
16
{
17
    /**
18
     * @var string
19
     */
20
    private $sessionPath;
21
22
    /**
23
     * FileSessionStorage constructor.
24
     *
25
     * @param $sessionPath
26
     */
27
    public function __construct($sessionPath)
28
    {
29
        $this->sessionPath = $sessionPath;
30
    }
31
32
    /**
33
     * @param Session       $session
34
     * @param UserInterface $user
35
     * @throws SessionDoNotSavedException
36
     */
37
    public function save(Session $session, UserInterface $user)
38
    {
39
        $filename = $this->sessionPath . $user->getAmoCRMLogin();
40
        if (is_dir($this->sessionPath)) {
41
            if (file_put_contents($filename, $session->getId())) {
42
                return;
43
            }
44
        }
45
46
        throw new SessionDoNotSavedException();
47
    }
48
49
    /**
50
     * @param UserInterface $user
51
     * @return Session
52
     * @throws SessionDoesNotExistException
53
     */
54
    public function getActive(UserInterface $user)
55
    {
56
        $filename = $this->sessionPath . $user->getAmoCRMLogin();
57
        if (file_exists($filename)) {
58
            $fileUpdatedDate = new \DateTime(date("F d Y H:i:s.", filemtime($filename)));
59
            $currentDate = new \DateTime();
60
            $diff = $currentDate->diff($fileUpdatedDate);
61
            $diffMinutes = $diff->d * 24 * 60;
62
            $diffMinutes += $diff->h * 60;
63
64
            if ($diffMinutes < 15 && $data = file_get_contents($filename)) {
65
                return new Session($data);
66
            }
67
        }
68
69
        throw new SessionDoesNotExistException($user);
70
    }
71
}
72