Passed
Pull Request — master (#2)
by nicolas
07:19
created

ContactListConvertor::convert()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 25
rs 8.8571
cc 3
eloc 15
nc 3
nop 1
1
<?php
2
3
namespace Dekalee\MailjetBundle\Convertor;
4
5
use Dekalee\MailjetBundle\Entity\ContactList;
6
use Dekalee\MailjetBundle\Entity\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
    public function __construct(ContactListRepository $repository, ObjectManager $objectManager, Client $client)
28
    {
29
        $this->client = $client;
30
        $this->repository = $repository;
31
        $this->objectManager = $objectManager;
32
    }
33
34
    /**
35
     * @param $name
36
     *
37
     * @return int
38
     * @throws ContactListNotCreated
39
     */
40
    public function convert($name)
41
    {
42
        $name = Inflector::classify($name);
43
        if (($contactList = $this->repository->findOneByName($name)) instanceof ContactList) {
44
            return $contactList->getListId();
45
        }
46
47
        $body = [
48
            'Name' => $name,
49
        ];
50
        $response = $this->client->post(Resources::$Contactslist, ['body' => $body]);
51
52
        if (!$response->success()) {
53
            throw new ContactListNotCreated();
54
        }
55
56
        $contactList = new ContactList();
57
        $contactList->setName($name);
58
        $contactList->setListId($response[0]['ID']);
59
60
        $this->objectManager->persist($contactList);
61
        $this->objectManager->flush($contactList);
62
63
        return $contactList->getListId();
64
    }
65
}
66