Passed
Push — master ( b0e1d7...34bc8c )
by
unknown
02:32
created

HookHandleService   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 19
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 136
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A processRequest() 0 23 1
A processNewWebhooks() 0 14 3
A processWebhook() 0 12 2
A getIdentityCheckReportByOnfidoReportId() 0 6 1
A getAllNewWebhooks() 0 8 1
A getHookRepo() 0 4 1
C isValidOnfidoRequest() 0 26 7
A sendMessage() 0 4 1
A sendErrorMessage() 0 4 1
1
<?php
2
/**
3
 * Created by Graham Owens ([email protected])
4
 * Company: PartFire Ltd (www.partfire.co.uk)
5
 * Console: Discovery
6
 *
7
 * User:    gra
8
 * Date:    20/01/17
9
 * Time:    09:52
10
 * Project: fruitful-property-investments
11
 * File:    HookHandleService.php
12
 *
13
 **/
14
15
namespace PartFire\MangoPayBundle\Services;
16
17
use Composer\EventDispatcher\Event;
18
use PartFire\CommonBundle\Services\Output\CommonOutputInterface;
19
use PartFire\MangoPayBundle\Entity\Hook;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, PartFire\MangoPayBundle\Services\Hook.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
20
use PartFire\MangoPayBundle\Entity\Repository\HookRepository;
21
use PartFire\MangoPayBundle\Entity\Repository\MangoPayRepositoryFactory;
22
use PartFire\MangoPayBundle\Event\MangoPayWebhookEvent;
23
use PartFire\MangoPayBundle\MangoPayConstants;
24
use PartFire\SlackBundle\Services\SlackService;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
27
class HookHandleService
28
{
29
    /**
30
     * @var IdentityCheckFactoryRepository
31
     */
32
    protected $mangoPayRepositoryFactory;
33
    protected $slackService;
34
35
    const       CHECK_COMPLETE          = "check.completed";
36
    const       REPORT_COMPLETE         = "report.completed";
37
38
39
    public function __construct(
40
        MangoPayRepositoryFactory $mangoPayRepositoryFactory,
41
        SlackService $slackService,
42
        EventDispatcherInterface $event
43
    )
44
    {
45
        $this->mangoPayRepositoryFactory = $mangoPayRepositoryFactory;
46
        $this->slackService = $slackService;
47
        $this->event = $event;
0 ignored issues
show
Bug introduced by
The property event does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
48
    }
49
50
    public function processRequest($bodyJson)
51
    {
52
        $formattedJson = json_encode($bodyJson);
53
        $this->sendMessage(
54
            "New Webhook received from MangoPay \n ```" . $formattedJson . "```",
55
            ':leftwards_arrow_with_hook:'
56
        );
57
58
        $hookQueueEntity = new Hook();
59
        $hookQueueEntity->setHookId($bodyJson->Id);
60
        $hookQueueEntity->setHookCreationDate($bodyJson->CreationDate);
61
        $hookQueueEntity->setHookTag($bodyJson->Tag);
62
        $hookQueueEntity->setHookUrl($bodyJson->Url);
63
        $hookQueueEntity->setHookStatus($bodyJson->Status);
64
        $hookQueueEntity->setHookValidity($bodyJson->Validity);
65
        $hookQueueEntity->setHookEventType($bodyJson->EventType);
66
67
        $hookQueueEntity->setRawHookData($formattedJson);
68
69
        $this->mangoPayRepositoryFactory->saveAndGetEntity($hookQueueEntity);
70
71
        return true;
72
    }
73
74
    public function processNewWebhooks(CommonOutputInterface $output)
75
    {
76
        $output->info(count($this->getAllNewWebhooks()) . " new hooks to check");
77
78
        foreach($this->getAllNewWebhooks() as $webHook) {
79
            $output->infoid(" Processing hook ID " . $webHook->getId() . " - Action Type = " . $webHook->getHookEventType());
80
            try {
81
                $this->processWebhook($webHook, $output);
82
            } catch (\Exception $e) {
83
                $output->error($e->getMessage());
84
            }
85
86
        }
87
    }
88
89
    private function processWebhook(Hook $hook, CommonOutputInterface $commonOutput)
90
    {
91
        if (MangoPayConstants::isEventTypeOk($hook->getHookEventType())) {
92
            $webhookEvent = new MangoPayWebhookEvent();
93
            $webhookEvent->setOutput($commonOutput);
94
        } else {
95
            $this->sendErrorMessage(
96
                "Received webhook from MangoPay *" . $hook->getHookEventType() ."* and unsure what to do with it \n ```" . json_encode($hook->getRawHookData()) . "```",
97
                ':anguished:'
98
            );
99
        }
100
    }
101
102
    private function getIdentityCheckReportByOnfidoReportId(OnfidoHookQueue $onfidoHookQueue) : ?IdentityCheckReport
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
103
    {
104
        return $this->mangoPayRepositoryFactory->getIdentityCheckReport()->findOneByOnfidoReportId(
105
            $onfidoHookQueue->getResourceId()
106
        );
107
    }
108
109
    private function getAllNewWebhooks()
110
    {
111
        return $this->getHookRepo()->findBy(
112
            [
113
                'status'      => MangoPayConstants::HOOK_NEW
114
            ]
115
        );
116
    }
117
118
    private function getHookRepo() : HookRepository
119
    {
120
        return $this->mangoPayRepositoryFactory->getHook();
121
    }
122
123
    // Made public so tests pass
124
125
    public function isValidOnfidoRequest($bodyJson)
126
    {
127
        if ($bodyJson instanceof \stdClass) {
128
129
            if (!isset($bodyJson->payload->resource_type)) {
130
                return false;
131
            }
132
133
            if (!isset($bodyJson->payload->action)) {
134
                return false;
135
            }
136
137
            if (!isset($bodyJson->payload->object->id)) {
138
                return false;
139
            }
140
141
            if (!isset($bodyJson->payload->object->href) ||
142
                !strstr($bodyJson->payload->object->href, 'api.onfido.com/v') === true
143
            ) {
144
                return false;
145
            }
146
147
            return true;
148
        }
149
        return false;
150
    }
151
152
    private function sendMessage(string $message, string $emoji)
153
    {
154
        $this->slackService->sendMessage($message, 'ff-mangopay-webhooks', $emoji);
155
    }
156
157
    private function sendErrorMessage(string $message, string $emoji)
158
    {
159
        $this->slackService->sendMessage($message, FFConstants::SLACK_CHANNEL_ERROR, $emoji);
160
    }
161
162
}
163