Passed
Branch main (b6a268)
by Iain
04:11
created

DoctrineRepository   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A findById() 0 15 4
A save() 0 8 2
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright Humbly Arrogant Ltd 2020-2022.
7
 *
8
 * Use of this software is governed by the Business Source License included in the LICENSE file and at https://getparthenon.com/docs/next/license.
9
 *
10
 * Change Date: TBD ( 3 years after 2.0.0 release )
11
 *
12
 * On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file.
13
 */
14
15
namespace Parthenon\Common\Repository;
16
17
use Doctrine\DBAL\Exception;
18
use Doctrine\DBAL\Types\ConversionException;
19
use Parthenon\Common\Exception\GeneralException;
20
use Parthenon\Common\Exception\NoEntityFoundException;
21
22
class DoctrineRepository implements RepositoryInterface
23
{
24
    protected CustomServiceRepository $entityRepository;
25
26
    public function __construct(CustomServiceRepository $entityRepository)
27
    {
28
        $this->entityRepository = $entityRepository;
29
    }
30
31
    public function save($entity)
32
    {
33
        try {
34
            $em = $this->entityRepository->getEntityManager();
35
            $em->persist($entity);
36
            $em->flush();
37
        } catch (\Exception $e) {
38
            throw new GeneralException($e->getMessage(), $e->getCode(), $e);
39
        }
40
    }
41
42
    public function findById($id)
43
    {
44
        try {
45
            $entity = $this->entityRepository->find($id);
46
        } catch (ConversionException $exception) {
47
            throw new NoEntityFoundException('Invalid id', previous: $exception);
48
        } catch (Exception $exception) {
49
            throw new GeneralException('Issue with Doctrine', previous: $exception);
50
        }
51
52
        if (!$entity) {
53
            throw new NoEntityFoundException('No entity found for id '.$id);
54
        }
55
56
        return $entity;
57
    }
58
}
59