Passed
Pull Request — master (#2)
by nicolas
03:24
created

ContactListConvertor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
namespace Dekalee\MailjetBundle\Convertor;
4
5
use Dekalee\MailjetBundle\Entity\ContactList;
6
use Dekalee\MailjetBundle\Repository\ContactListRepository;
7
use Dekalee\MailjetBundle\Exception\ContactListNotCreated;
8
use Doctrine\Common\Inflector\Inflector;
9
use Doctrine\Common\Persistence\ObjectManager;
10
use Mailjet\Client;
11
use Mailjet\Resources;
12
13
/**
14
 * Class ContactListConvertor
15
 */
16
class ContactListConvertor
17
{
18
    protected $client;
19
    protected $repository;
20
    protected $objectManager;
21
22
    /**
23
     * @param ContactListRepository $repository
24
     * @param ObjectManager         $objectManager
25
     * @param Client                $client
26
     */
27 4
    public function __construct(ContactListRepository $repository, ObjectManager $objectManager, Client $client)
28
    {
29 4
        $this->client = $client;
30 4
        $this->repository = $repository;
31 4
        $this->objectManager = $objectManager;
32 4
    }
33
34
    /**
35
     * @param string $name
36
     *
37
     * @return int
38
     * @throws ContactListNotCreated
39
     */
40 3
    public function convert($name)
41
    {
42 3
        $name = Inflector::classify($name);
43 3
        if (($contactList = $this->repository->findOneByName($name)) instanceof ContactList) {
44 1
            return $contactList->getListId();
45
        }
46
47
        $body = [
48 2
            'Name' => $name,
49 2
        ];
50 2
        $response = $this->client->post(Resources::$Contactslist, ['body' => $body]);
51
52 2
        if (!$response->success()) {
53 1
            throw new ContactListNotCreated();
54
        }
55
56 1
        $contactList = new ContactList();
57 1
        $contactList->setName($name);
58 1
        $contactList->setListId($response->getData()[0]['ID']);
59
60 1
        $this->objectManager->persist($contactList);
61 1
        $this->objectManager->flush($contactList);
62
63 1
        return $contactList->getListId();
64
    }
65
}
66