AssociationWriter::write()   C
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 44
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 44
rs 6.7272
cc 7
eloc 26
nc 7
nop 1
1
<?php
2
3
namespace Actualys\Bundle\DrupalCommerceConnectorBundle\Writer;
4
5
use Actualys\Bundle\DrupalCommerceConnectorBundle\Item\DrupalItemStep;
6
use Akeneo\Bundle\BatchBundle\Item\ItemWriterInterface;
7
use Akeneo\Bundle\BatchBundle\Event\InvalidItemEvent;
8
use Symfony\Component\EventDispatcher\EventDispatcher;
9
use Akeneo\Bundle\BatchBundle\Event\EventInterface;
10
use Guzzle\Http\Exception\ClientErrorResponseException;
11
use Akeneo\Bundle\BatchBundle\Job\ExitStatus;
12
13
class AssociationWriter extends DrupalItemStep implements ItemWriterInterface
14
{
15
16
    protected $eventDispatcher;
17
18
    public function __construct(EventDispatcher $eventDispatcher)
19
    {
20
        $this->eventDispatcher = $eventDispatcher;
21
    }
22
23
    /**
24
     * @param array $items
25
     */
26
    public function write(array $items)
27
    {
28
        //file_put_contents('product_association.json', json_encode($items));
29
        foreach ($items as $item) {
30
            try {
31
                // Send only when association exist
32
                if (count($item[key($item)]) > 0) {
33
                    $this->webservice->sendAssociation($item);
34
                }
35
            } catch (\Exception $e) {
36
                $event = new InvalidItemEvent(
37
                  __CLASS__,
38
                  $e->getMessage(),
39
                  array(),
40
                  ['sku' => array_key_exists('sku', $item) ? $item['sku'] : 'NULL']
41
                );
42
                // Logging file
43
                $this->eventDispatcher->dispatch(
44
                  EventInterface::INVALID_ITEM,
45
                  $event
46
                );
47
48
49
                // Loggin Interface
50
                $this->stepExecution->addWarning(
51
                  __CLASS__,
52
                  $e->getMessage(),
53
                  array(),
54
                  ['sku' => array_key_exists('sku', $item) ? $item['sku'] : 'NULL']
55
                );
56
57
                /** @var ClientErrorResponseException  $e */
58
                if ($e->getResponse()->getStatusCode() <= 404) {
59
                    $e = new \Exception($e->getResponse()->getReasonPhrase());
60
                    $this->stepExecution->addFailureException($e);
61
                    $exitStatus = new ExitStatus(ExitStatus::FAILED);
62
                    $this->stepExecution->setExitStatus($exitStatus);
63
                }
64
                // Handle next element.
65
            }
66
            $this->stepExecution->incrementSummaryInfo('write');
67
            $this->stepExecution->incrementWriteCount();
68
        }
69
    }
70
}
71