Completed
Push — master ( 73401c...7dc428 )
by Gabriel
05:35
created

RecordsTest::testGetUrlHelper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 6
rs 9.4285
c 1
b 1
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace Nip\Records\Tests;
4
5
use Mockery as m;
6
use Nip\Database\Connections\Connection;
7
use Nip\Helpers\View\Url;
8
use Nip\Records\Collections\Collection;
9
use Nip\Records\RecordManager as Records;
10
use Nip\Request;
11
use Nip\Records\Tests\AbstractTest;
12
use Nip_Helper_Url;
13
14
/**
15
 * Class RecordsTest
16
 * @package Nip\Records\Tests
17
 */
18
class RecordsTest extends AbstractTest
19
{
20
21
    /**
22
     * @var Records
23
     */
24
    protected $_object;
25
26
    public function testSetModel()
27
    {
28
        $this->_object->setModel('Row');
29
        self::assertEquals($this->_object->getModel(), 'Row');
30
31
        $this->_object->setModel('Row2');
32
        self::assertEquals($this->_object->getModel(), 'Row2');
33
    }
34
35
    public function testGetFullNameTable()
36
    {
37
        self::assertEquals('pages', $this->_object->getFullNameTable());
38
39
        $this->_object->getDB()->setDatabase('database_name');
40
        self::assertEquals('database_name.pages', $this->_object->getFullNameTable());
41
    }
42
43
    // tests
44
45
    public function testGenerateModelClass()
46
    {
47
        self::assertEquals($this->_object->generateModelClass('Notifications\Table'), 'Notifications\Row');
48
        self::assertEquals($this->_object->generateModelClass('Notifications_Tables'), 'Notifications_Table');
49
        self::assertEquals($this->_object->generateModelClass('Notifications'), 'Notification');
50
        self::assertEquals($this->_object->generateModelClass('Persons'), 'Person');
51
    }
52
53
    /**
54
     * @return array
55
     */
56
    public function providerGetController()
57
    {
58
        return [
59
            ["notifications-tables", "Notifications_Tables"],
60
            ["notifications-tables", "Notifications\\Tables\\Tables"],
61
            ["notifications-tables", "App\\Models\\Notifications\\Tables\\Tables"],
62
        ];
63
    }
64
65
    /**
66
     * @dataProvider providerGetController
67
     * @param $controller
68
     * @param $class
69
     */
70
    public function testGetController($controller, $class)
71
    {
72
        /** @var Records $records */
73
        $records = new Records();
74
        $records->setClassName($class);
75
76
        self::assertEquals($controller, $records->getController());
77
    }
78
79
//    public function testInitRelationsFromArrayBelongsToSimple()
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
80
//    {
81
    /** @var Records $users */
82
//        $users = m::namedMock('Users', Records::class)->shouldDeferMissing()
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
83
//            ->shouldReceive('instance')->andReturnSelf()
84
//            ->getMock();
85
86
//        $users->setPrimaryFK('id_user');
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
87
//
88
//        m::namedMock('User', Records::class);
89
//        m::namedMock('Articles', Records::class);
90
91
//        $this->_object->setPrimaryFK('id_object');
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
92
//
93
//        $this->_object->initRelationsFromArray('belongsTo', ['User']);
94
//        $this->_testInitRelationsFromArrayBelongsToUser('User');
95
//
96
//        $this->_object->initRelationsFromArray('belongsTo', [
97
//            'UserName' => ['with' => $users],
98
//        ]);
99
//        $this->_testInitRelationsFromArrayBelongsToUser('UserName');
100
//
101
//        self::assertSame($users, $this->_object->getRelation('User')->getWith());
102
//    }
103
104
    public function testNewCollection()
105
    {
106
        $collection = $this->_object->newCollection();
107
        self::assertInstanceOf('Nip\Records\Collections\Collection', $collection);
108
        self::assertSame($this->_object, $collection->getManager());
109
    }
110
111
    public function testRequestFilters()
112
    {
113
        $request = new Request();
114
        $params = [
115
            'title' => 'Test title',
116
            'name' => 'Test name',
117
        ];
118
        $request->query->add($params);
119
120
        $this->_object->getFilterManager()->addFilter(
121
            $this->_object->getFilterManager()->newFilter('Column\BasicFilter')
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Nip\Records\Filters\AbstractFilter as the method setField() does only exist in the following sub-classes of Nip\Records\Filters\AbstractFilter: Nip\Records\Filters\Column\AbstractFilter, Nip\Records\Filters\Column\BasicFilter, Nip\Records\Filters\Column\WildcardFilter. 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...
122
                ->setField('title')
123
        );
124
125
        $this->_object->getFilterManager()->addFilter(
126
            $this->_object->getFilterManager()->newFilter('Column\BasicFilter')
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Nip\Records\Filters\AbstractFilter as the method setField() does only exist in the following sub-classes of Nip\Records\Filters\AbstractFilter: Nip\Records\Filters\Column\AbstractFilter, Nip\Records\Filters\Column\BasicFilter, Nip\Records\Filters\Column\WildcardFilter. 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...
127
                ->setField('name')
128
        );
129
130
        $filtersArray = $this->_object->requestFilters($request);
131
        self::assertSame($filtersArray, $params);
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    public function providerGetPrimaryFK()
138
    {
139
        return [
140
            ["id_user", "Users"],
141
            ["id_race_entry", "RaceEntries"],
142
            ["id_notifications_table", "Notifications_Tables"],
143
            ["id_notifications_table", "Notifications\\Tables\\Tables"],
144
            ["id_notifications_table", "App\\Models\\Notifications\\Tables\\Tables"],
145
        ];
146
    }
147
148
    /**
149
     * @dataProvider providerGetPrimaryFK
150
     * @param $primaryFK
151
     * @param $class
152
     */
153
    public function testGetPrimaryFK($primaryFK, $class)
154
    {
155
        /** @var Records $records */
156
//        $records = m::namedMock($class, 'Records')->shouldDeferMissing()
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
157
//            ->shouldReceive('instance')->andReturnSelf()
158
//            ->shouldReceive('getPrimaryKey')->andReturn('id')
159
//            ->getMock();
160
        $records = new Records();
161
        $records->setClassName($class);
162
        $records->setPrimaryKey('id');
163
164
        self::assertEquals($primaryFK, $records->getPrimaryFK());
165
    }
166
167
    public function testGetPrimaryKey()
168
    {
169
        $records = new Records();
170
        $tableStructure = unserialize(file_get_contents(TEST_FIXTURE_PATH . '/database_structure/users.serialize'));
171
        $records->setTableStructure($tableStructure);
172
        $records->setPrimaryKey('id');
173
174
        self::assertEquals('id', $records->getPrimaryKey());
175
    }
176
177
    public function testGetCollectionClass()
178
    {
179
        self::assertEquals(Collection::class, $this->_object->getCollectionClass());
180
    }
181
182
    public function testGetUrlHelper()
183
    {
184
        $records = new Records();
185
        $urlHelper = $records->Url();
186
        self::assertInstanceOf(Nip_Helper_Url::class,$urlHelper);
187
    }
188
189 View Code Duplication
    protected function setUp()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
    {
191
        parent::setUp();
192
193
        $wrapper = new Connection(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<PDO>|object<Closure>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
194
195
        $this->_object = m::mock(Records::class)->shouldDeferMissing()
196
            ->shouldReceive('getRequest')->andReturn(Request::create('/'))
197
            ->getMock();
198
199
        $this->_object->setDB($wrapper);
200
        $this->_object->setTable('pages');
201
    }
202
}
203