zend-blog-3-backend
113 строк · 2.4 Кб
1<?php
2/**
3* Created by PhpStorm.
4* User: morontt
5* Date: 07.10.17
6* Time: 11:04
7*/
8
9namespace App\Service;
10
11use App\Entity\SystemParameters;
12use App\Repository\SystemParametersRepository;
13use Doctrine\ORM\EntityManager;
14use Doctrine\ORM\EntityManagerInterface;
15use Doctrine\ORM\ORMException;
16
17class SystemParametersStorage
18{
19const CIPHER = 'DES-EDE3-OFB';
20
21/**
22* @var SystemParametersRepository
23*/
24protected $parametersRepo;
25
26/**
27* @var string
28*/
29protected $secret;
30
31/**
32* @var EntityManager
33*/
34protected $em;
35
36/**
37* @param EntityManagerInterface $em
38* @param string $secret
39*/
40public function __construct(EntityManagerInterface $em, string $secret)
41{
42$this->parametersRepo = $em->getRepository(SystemParameters::class);
43$this->em = $em;
44
45$this->secret = $secret;
46}
47
48/**
49* @param string $key
50* @param string $value
51* @param bool $encrypted
52*
53* @throws ORMException
54*/
55public function saveParameter(string $key, string $value, bool $encrypted = false)
56{
57$sp = $this->parametersRepo->findOneByOptionKey($key);
58
59if (!$sp) {
60$sp = new SystemParameters();
61$sp->setOptionKey($key);
62$this->em->persist($sp);
63}
64
65$sp->setValue($encrypted ? $this->encrypt($value) : $value)
66->setEncrypted($encrypted);
67$this->em->flush();
68}
69
70/**
71* @param string $key
72*
73* @return string|null
74*/
75public function getParameter(string $key): ?string
76{
77$sp = $this->parametersRepo->findOneByOptionKey($key);
78
79if (!$sp) {
80return null;
81}
82
83return $sp->isEncrypted() ? $this->decrypt($sp->getValue()) : $sp->getValue();
84}
85
86/**
87* @param string $value
88*
89* @return string
90*/
91public function encrypt(string $value): string
92{
93return base64_encode(openssl_encrypt($value, self::CIPHER, $this->secret, 0, $this->getVector()));
94}
95
96/**
97* @param string $value
98*
99* @return string
100*/
101public function decrypt(string $value): string
102{
103return openssl_decrypt(base64_decode($value), self::CIPHER, $this->secret, 0, $this->getVector());
104}
105
106/**
107* @return string
108*/
109protected function getVector(): string
110{
111return substr(sha1($this->secret), 0, openssl_cipher_iv_length(self::CIPHER));
112}
113}
114