Passed
Pull Request — master (#5629)
by Angel Fernando Quiroz
08:49
created

StatementPostController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A postStatements() 0 30 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the xAPI package.
7
 *
8
 * (c) Christian Flothmann <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace XApi\LrsBundle\Controller;
15
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
19
use Xabbuh\XApi\Common\Exception\NotFoundException;
20
use Xabbuh\XApi\Model\Statement;
21
use XApi\Repository\Api\StatementRepositoryInterface;
22
23
/**
24
 * @author Jérôme Parmentier <[email protected]>
25
 */
26
final class StatementPostController
27
{
28
    /**
29
     * @var StatementRepositoryInterface
30
     */
31
    private $repository;
32
33
    public function __construct(StatementRepositoryInterface $repository)
34
    {
35
        $this->repository = $repository;
36
    }
37
38
    public function postStatements(Request $request, array $statements): JsonResponse
39
    {
40
        $statementsToStore = [];
41
42
        /** @var Statement $statement */
43
        foreach ($statements as $statement) {
44
            if (null === $statementId = $statement->getId()) {
45
                $statementsToStore[] = $statement;
46
47
                continue;
48
            }
49
50
            try {
51
                $existingStatement = $this->repository->findStatementById($statement->getId());
52
53
                if (!$existingStatement->equals($statement)) {
54
                    throw new ConflictHttpException('The new statement is not equal to an existing statement with the same id.');
55
                }
56
            } catch (NotFoundException $e) {
57
                $statementsToStore[] = $statement;
58
            }
59
        }
60
61
        $uuids = [];
62
63
        foreach ($statementsToStore as $statement) {
64
            $uuids[] = $this->repository->storeStatement($statement, true)->getValue();
65
        }
66
67
        return new JsonResponse($uuids);
68
    }
69
}
70