Completed
Push — master ( c3efa2...a812ec )
by Guilherme
13s
created

MonologDBHandler::write()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
nc 6
nop 1
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\LogBundle\Handler;
12
13
use Doctrine\Common\Cache\CacheProvider;
14
use Doctrine\ORM\EntityManagerInterface;
15
use LoginCidadao\LogBundle\Entity\Log;
16
use Monolog\Handler\AbstractProcessingHandler;
17
18
class MonologDBHandler extends AbstractProcessingHandler
19
{
20
    const DISABLE_LOGGING_FLAG_KEY = 'db_logging_disabled';
21
    const LIFETIME = 1800;
22
23
    /** @var EntityManagerInterface */
24
    private $em;
25
26
    /** @var CacheProvider */
27
    private $cache;
28
29
    /**
30
     * MonologDBHandler constructor.
31
     * @param EntityManagerInterface $em
32
     */
33
    public function __construct(EntityManagerInterface $em)
34
    {
35
        parent::__construct();
36
        $this->em = $em;
37
    }
38
39
    /**
40
     * @param CacheProvider $cache
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cache not be null|CacheProvider?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
41
     */
42
    public function setCacheProvider(CacheProvider $cache = null)
43
    {
44
        $this->cache = $cache;
45
    }
46
47
    protected function write(array $record)
48
    {
49
        if ($this->cache !== null && $this->cache->contains(self::DISABLE_LOGGING_FLAG_KEY)) {
50
            return;
51
        }
52
53
        $logEntry = (new Log())
54
            ->setMessage($record['message'])
55
            ->setLevel($record['level'])
56
            ->setLevelName($record['level_name'])
57
            ->setExtra($record['extra'])
58
            ->setContext($record['context']);
59
60
        try {
61
            $this->em->persist($logEntry);
62
            $this->em->flush();
63
        } catch (\Exception $e) {
64
            if ($this->cache) {
65
                $this->cache->save(self::DISABLE_LOGGING_FLAG_KEY, true, self::LIFETIME);
66
            }
67
        }
68
    }
69
}
70