Passed
Push — 1.11.x ( 106594...56cdc0 )
by Angel Fernando Quiroz
08:52
created

StatementPostController::postStatement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the xAPI package.
5
 *
6
 * (c) Christian Flothmann <[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 XApi\LrsBundle\Controller;
13
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
17
use Xabbuh\XApi\Common\Exception\NotFoundException;
18
use Xabbuh\XApi\Model\Statement;
19
use XApi\Repository\Api\StatementRepositoryInterface;
20
21
/**
22
 * @author Jérôme Parmentier <[email protected]>
23
 */
24
final class StatementPostController
25
{
26
    /**
27
     * @var StatementRepositoryInterface
28
     */
29
    private $repository;
30
31
    public function __construct(StatementRepositoryInterface $repository)
32
    {
33
        $this->repository = $repository;
34
    }
35
36
    public function postStatements(Request $request, array $statements): JsonResponse
37
    {
38
        $statementsToStore = [];
39
40
        /** @var Statement $statement */
41
        foreach ($statements as $statement) {
42
            if (null === $statementId = $statement->getId()) {
43
                $statementsToStore[] = $statement;
44
45
                continue;
46
            }
47
48
            try {
49
                $existingStatement = $this->repository->findStatementById($statement->getId());
50
51
                if (!$existingStatement->equals($statement)) {
52
                    throw new ConflictHttpException('The new statement is not equal to an existing statement with the same id.');
53
                }
54
            } catch (NotFoundException $e) {
55
                $statementsToStore[] = $statement;
56
            }
57
        }
58
59
        $uuids = [];
60
61
        foreach ($statementsToStore as $statement) {
62
            $uuids[] = $this->repository->storeStatement($statement, true)->getValue();
63
        }
64
65
        return new JsonResponse($uuids);
66
    }
67
}
68