Passed
Push — master ( cf75f9...66ca98 )
by Julito
09:35
created

CDocumentRepository::getDocumentPath()   A

Complexity

Conditions 2
Paths 7

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 7
nop 1
dl 0
loc 22
rs 9.7998
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CourseBundle\Repository;
5
6
use Chamilo\CourseBundle\Entity\CDocument;
7
use Doctrine\ORM\EntityManager;
8
use Doctrine\ORM\EntityRepository;
9
use Gaufrette\Exception\FileNotFound;
10
use Sonata\MediaBundle\Provider\MediaProviderInterface;
11
use Sonata\MediaBundle\Provider\Pool;
12
use Symfony\Component\Translation\Exception\NotFoundResourceException;
13
14
/**
15
 * Class CDocumentRepository.
16
 *
17
 */
18
class CDocumentRepository
19
{
20
    /**
21
     * @var EntityRepository
22
     */
23
    private $repository;
24
25
    private $mediaPool;
26
27
    /**
28
     * CDocumentRepository constructor.
29
     *
30
     * @param EntityManager $entityManager
31
     */
32
    public function __construct(EntityManager $entityManager, Pool $mediaPool)
33
    {
34
        $this->repository = $entityManager->getRepository(CDocument::class);
35
        $this->mediaPool = $mediaPool;
36
    }
37
38
    /**
39
     * @param int $id
40
     *
41
     * @return CDocument|null
42
     */
43
    public function find(int $id): ?CDocument
44
    {
45
        return $this->repository->find($id);
46
    }
47
48
    /**
49
     * @param array      $criteria
50
     * @param array|null $orderBy
51
     *
52
     * @return CDocument|null
53
     */
54
    public function findOneBy(array $criteria, array $orderBy = null): ?CDocument
55
    {
56
        return $this->repository->findOneBy($criteria, $orderBy);
57
    }
58
59
    /**
60
     * @param int $id
61
     *
62
     * @return string
63
     */
64
    public function getDocumentPath($id) :string
65
    {
66
        try {
67
            $document = $this->find($id);
68
69
            $resourceNode = $document->getResourceNode();
70
71
            $resourceFile = $resourceNode->getResourceFile();
72
            $media = $resourceFile->getMedia();
73
            $provider = $this->mediaPool->getProvider($media->getProviderName());
74
75
            $format = MediaProviderInterface::FORMAT_REFERENCE;
76
            $filename = sprintf(
77
                '%s/%s',
78
                $provider->getFilesystem()->getAdapter()->getDirectory(),
79
                $provider->generatePrivateUrl($media, $format)
80
            );
81
82
83
            return $filename;
84
        } catch (\Throwable $exception) {
85
            throw new FileNotFound($id);
86
        }
87
    }
88
}
89