PushTest::testSendMixedMessage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 3
1
<?php
2
3
/*
4
 * This file is part of the Mremi\Flowdock library.
5
 *
6
 * (c) Rémi Marseille <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Mremi\Flowdock\Tests\Api\Push;
13
14
use GuzzleHttp\Psr7\Response;
15
16
use Mremi\Flowdock\Api\Push\BaseMessageInterface;
17
use Mremi\Flowdock\Api\Push\ChatMessage;
18
use Mremi\Flowdock\Api\Push\Push;
19
use Mremi\Flowdock\Api\Push\TeamInboxMessage;
20
21
/**
22
 * Tests the Push class
23
 *
24
 * @author Rémi Marseille <[email protected]>
25
 */
26
class PushTest extends \PHPUnit_Framework_TestCase
27
{
28
    /**
29
     * Provides arguments for sendMessage test
30
     *
31
     * @return array
32
     */
33
    public function getSendMessageArgs()
34
    {
35
        return array(
36
            array($this->createChatMessage(), Push::BASE_CHAT_URL, array('connect_timeout' => 1, 'timeout' => 1)),
37
            array($this->createTeamInboxMessage(), Push::BASE_TEAM_INBOX_URL, array('connect_timeout' => 1, 'timeout' => 1)),
38
        );
39
    }
40
41
    /**
42
     * Tests the sendChatMessage and sendTeamInboxMessage methods
43
     *
44
     * @param BaseMessageInterface $message A message instance
45
     * @param string               $baseUrl A base URL
46
     * @param array                $options An array of options used by request
47
     *
48
     * @dataProvider getSendMessageArgs
49
     */
50
    public function testSendMixedMessage(BaseMessageInterface $message, $baseUrl, array $options)
51
    {
52
        $push = $this->getMockBuilder('Mremi\Flowdock\Api\Push\Push')
53
            ->disableOriginalConstructor()
54
            ->setMethods(array('sendMessage'))
55
            ->getMock();
56
57
        $push
58
            ->expects($this->exactly(2))
59
            ->method('sendMessage')
60
            ->with($this->equalTo($message), $this->equalTo($baseUrl), $this->equalTo($options))
61
            ->will($this->onConsecutiveCalls(true, false));
62
63
        $method = $message instanceof ChatMessage ? 'sendChatMessage' : 'sendTeamInboxMessage';
64
65
        $this->assertTrue($push->$method($message, $options));
66
        $this->assertFalse($push->$method($message, $options));
67
    }
68
69
    /**
70
     * Tests the sendMessage method succeed and failed
71
     *
72
     * @param BaseMessageInterface $message A message instance
73
     * @param string               $baseUrl A base URL
74
     * @param array                $options An array of options used by request
75
     *
76
     * @dataProvider getSendMessageArgs
77
     */
78
    public function testSendMessage(BaseMessageInterface $message, $baseUrl, array $options)
79
    {
80
        $responseOk = new Response(200, array(
81
            'Content-Type' => 'application/json; charset=utf-8',
82
        ), '{}');
83
84
        $responseKo = new Response(400, array(
85
            'Content-Type' => 'application/json; charset=utf-8',
86
        ), '{"message": "Validation error", "errors": {"content": ["can\'t be blank"]}}');
87
88
        $clientOptions = $options;
89
        $clientOptions['headers'] = array('Content-Type' => 'application/json');
90
        $clientOptions['json'] = $message->getData();
91
        
92
        $client = $this->createMock('GuzzleHttp\Client');
93
        $client
94
            ->expects($this->exactly(2))
95
            ->method('__call')
96
            ->with($this->equalTo('post'), $this->equalTo([null, $clientOptions]))
97
            ->willReturnOnConsecutiveCalls($responseOk, $responseKo);
98
99
        $push = $this->getMockBuilder('Mremi\Flowdock\Api\Push\Push')
100
            ->setConstructorArgs(array('flow_api_token'))
101
            ->setMethods(array('createClient'))
102
            ->getMock();
103
104
        $push
105
            ->expects($this->exactly(2))
106
            ->method('createClient')
107
            ->with($this->equalTo(sprintf('%s/flow_api_token', $baseUrl)))
108
            ->will($this->returnValue($client));
109
110
        $method = new \ReflectionMethod($push, 'sendMessage');
111
        $method->setAccessible(true);
112
113
        $this->assertNull($message->getResponse());
114
        $this->assertFalse($message->hasResponseErrors());
115
116
        $this->assertTrue($method->invoke($push, $message, $baseUrl, $options));
117
        $this->assertSame($responseOk, $message->getResponse());
118
        $this->assertFalse($message->hasResponseErrors());
119
120
        $this->assertFalse($method->invoke($push, $message, $baseUrl, $options));
121
        $this->assertSame($responseKo, $message->getResponse());
122
        $this->assertTrue($message->hasResponseErrors());
123
    }
124
125
    /**
126
     * Creates a chat message
127
     *
128
     * @return ChatMessage
129
     */
130
    private function createChatMessage()
131
    {
132
        return ChatMessage::create()
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Mremi\Flowdock\Api\Push\BaseMessage as the method setExternalUserName() does only exist in the following sub-classes of Mremi\Flowdock\Api\Push\BaseMessage: Mremi\Flowdock\Api\Push\ChatMessage. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
133
            ->setContent('Hello world!')
134
            ->setExternalUserName('mremi');
135
    }
136
137
    /**
138
     * Creates a team inbox message
139
     *
140
     * @return TeamInboxMessage
141
     */
142
    private function createTeamInboxMessage()
143
    {
144
        return TeamInboxMessage::create()
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Mremi\Flowdock\Api\Push\BaseMessage as the method setSource() does only exist in the following sub-classes of Mremi\Flowdock\Api\Push\BaseMessage: Mremi\Flowdock\Api\Push\TeamInboxMessage. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
145
            ->setSource('source')
146
            ->setFromAddress('[email protected]')
147
            ->setSubject('subject')
148
            ->setContent('Hello world!');
149
    }
150
}
151