MandrillPayloadDecoder::decode()   C
last analyzed

Complexity

Conditions 9
Paths 8

Size

Total Lines 85
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 85
rs 5.3909
cc 9
eloc 52
nc 8
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace AramisAuto\EmailController\PayloadDecoder;
4
5
use AramisAuto\EmailController\Exception\InvalidPayloadException;
6
use AramisAuto\EmailController\Exception\MandrillWebhookTestException;
7
use AramisAuto\EmailController\Message;
8
9
class MandrillPayloadDecoder implements PayloadDecoderInterface
10
{
11
    public function decode($payload)
12
    {
13
        // Parse request raw body
14
        $vars = array();
15
        parse_str($payload, $vars);
16
17
        if (!isset($vars['mandrill_events'])) {
18
            throw new InvalidPayloadException(
19
                sprintf(
20
                    'Missing "mandrill_events" body parameter - %s',
21
                    json_encode(array('payload' => $payload), JSON_UNESCAPED_SLASHES)
22
                )
23
            );
24
        }
25
26
        // Decode JSON
27
        $messagesMandrill = json_decode($vars['mandrill_events'], true);
28
29
        if (is_array($messagesMandrill) && count($messagesMandrill) === 0) {
30
            throw new MandrillWebhookTestException(
31
                sprintf(
32
                    'Received Mandrill test payload - %s',
33
                    json_encode(array('payload' => $payload), JSON_UNESCAPED_SLASHES)
34
                )
35
            );
36
        }
37
38
        if (!$messagesMandrill) {
39
            throw new InvalidPayloadException(
40
                sprintf(
41
                    'Could not decode payload JSON - %s',
42
                    json_encode($vars['mandrill_events'], JSON_UNESCAPED_SLASHES)
43
                )
44
            );
45
        }
46
47
        $messages = array();
48
        foreach ($messagesMandrill as $messageMandrill) {
0 ignored issues
show
Bug introduced by
The expression $messagesMandrill of type object|integer|double|string|boolean|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
49
            // Defaults
50
            $messageDefaults = array(
51
                'cc' => array(),
52
                'from_email' => null,
53
                'from_name' => null,
54
                'headers' => array(),
55
                'html' => null,
56
                'id' => null,
57
                'metadata' => array(),
58
                'raw_msg' => null,
59
                'subject' => null,
60
                'text' => null,
61
                'email' => array(),
62
            );
63
            $messageFields = array_merge($messageDefaults, $messageMandrill);
64
65
            // Create EmailController message
66
            $message = new Message();
67
            $message->setRaw($messageFields['raw_msg']);
68
            $message->setHeaders($messageFields['headers']);
0 ignored issues
show
Bug introduced by
It seems like $messageFields['headers'] can also be of type null; however, AramisAuto\EmailController\Message::setHeaders() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
69
            $message->setText($messageFields['text']);
70
            $message->setHtml($messageFields['html']);
71
            $message->setSubject($messageFields['subject']);
72
            $message->setFrom($messageFields['msg']['sender']);
73
            $message->setTo(array(array($messageMandrill['msg']['email'], null)));
74
75
            // Message unique identifier
76
            $message->setId($messageFields['_id']);
77
78
            // Message metadata
79
            $message->metadata = array();
80
            if (isset($messageFields['msg'])) {
81
                $message->metadata = array_merge($message->metadata, $messageFields['msg']);
82
            }
83
            if (isset($messageFields['msg']) && isset($messageFields['msg']['metadata'])) {
84
                $message->metadata = array_merge($message->metadata, $messageFields['msg']['metadata']);
85
            }
86
87
            // Keep original message
88
            $message->source = $messageMandrill;
89
90
            $messages[] = $message;
91
            unset($messageFields);
92
        }
93
94
        return $messages;
95
    }
96
}
97