Passed
Pull Request — master (#5629)
by Angel Fernando Quiroz
10:06 queued 01:32
created

XApiActivityHookObserver   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 50
c 1
b 0
f 0
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serializeStatement() 0 6 1
A saveSharedStatement() 0 13 1
A __construct() 0 8 1
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\XApiSharedStatement;
6
use Xabbuh\XApi\Model\Statement;
7
use Xabbuh\XApi\Serializer\Symfony\Serializer;
8
use Xabbuh\XApi\Serializer\Symfony\StatementSerializer;
9
10
/**
11
 * Class XApiActivityHookObserver.
12
 */
13
abstract class XApiActivityHookObserver extends HookObserver
14
{
15
    /**
16
     * @var \XApiPlugin
17
     */
18
    protected $plugin;
19
20
    /**
21
     * XApiActivityHookObserver constructor.
22
     */
23
    protected function __construct()
24
    {
25
        parent::__construct(
26
            'plugin/xapi/src/XApiPlugin.php',
27
            'xapi'
28
        );
29
30
        $this->plugin = XApiPlugin::create();
31
    }
32
33
    /**
34
     * @throws \Doctrine\ORM\ORMException
35
     * @throws \Doctrine\ORM\OptimisticLockException
36
     */
37
    protected function saveSharedStatement(Statement $statement): XApiSharedStatement
38
    {
39
        $statementSerialized = $this->serializeStatement($statement);
40
41
        $sharedStmt = new XApiSharedStatement(
42
            json_decode($statementSerialized, true)
43
        );
44
45
        $em = Database::getManager();
46
        $em->persist($sharedStmt);
47
        $em->flush();
48
49
        return $sharedStmt;
50
    }
51
52
    /**
53
     * Serialize a statement to JSON.
54
     *
55
     * @return string
56
     */
57
    private function serializeStatement(Statement $statement)
58
    {
59
        $serializer = Serializer::createSerializer();
60
        $statementSerializer = new StatementSerializer($serializer);
61
62
        return $statementSerializer->serializeStatement($statement);
63
    }
64
}
65