Completed
Pull Request — master (#1352)
by Jordi Sala
02:42
created

ServiceProviderDataTransformer::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\MediaBundle\Form\DataTransformer;
13
14
use Psr\Log\LoggerAwareInterface;
15
use Psr\Log\LoggerAwareTrait;
16
use Psr\Log\NullLogger;
17
use Sonata\MediaBundle\Model\MediaInterface;
18
use Sonata\MediaBundle\Provider\MediaProviderInterface;
19
use Symfony\Component\Form\DataTransformerInterface;
20
21
class ServiceProviderDataTransformer implements DataTransformerInterface, LoggerAwareInterface
22
{
23
    use LoggerAwareTrait;
24
25
    /**
26
     * @var MediaProviderInterface
27
     */
28
    protected $provider;
29
30
    /**
31
     * @param MediaProviderInterface $provider
32
     */
33
    public function __construct(MediaProviderInterface $provider)
34
    {
35
        $this->provider = $provider;
36
37
        $this->logger = new NullLogger();
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function transform($value)
44
    {
45
        return $value;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function reverseTransform($media)
52
    {
53
        if (!$media instanceof MediaInterface) {
54
            return $media;
55
        }
56
57
        try {
58
            $this->provider->transform($media);
59
        } catch (\Exception $e) { // NEXT_MAJOR: When switching to PHP 7+, change this to \Throwable
60
            // #1107 We must never throw an exception here.
61
            // An exception here would prevent us to provide meaningful errors through the Form
62
            // Error message taken from Monolog\ErrorHandler
63
            $this->logger->error(
64
                sprintf('Caught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
65
                ['exception' => $e]
66
            );
67
        }
68
69
        return $media;
70
    }
71
}
72