Passed
Push — develop ( 77747e...4f7d52 )
by Mathieu
01:41
created

DBObjectTest::testRelations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 24
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 38
rs 9.536
1
<?php
2
require_once 'stubs/Category.php';
3
4
class DBObjectTest extends \PHPUnit\Framework\TestCase
5
{
6
    protected $tableName = 'users';
7
    public function testContructor()
8
    {
9
        $classname = '\Suricate\DBObject';
10
11
        // Get mock, without the constructor being called
12
        $mock = $this->getMockBuilder($classname)
13
            ->disableOriginalConstructor()
14
            ->setMethods(array('setRelations'))
15
            ->getMockForAbstractClass();
16
17
        // set expectations for constructor calls
18
        $mock->expects($this->once())
19
            ->method('setRelations');
20
21
        // now call the constructor
22
        $reflectedClass = new ReflectionClass($classname);
23
        $constructor = $reflectedClass->getConstructor();
24
        $constructor->invoke($mock);
25
    }
26
27
    public function testGetTableName()
28
    {
29
        $testName = 'my_sql_table';
30
31
        $testDBO = new \Suricate\DBObject();
32
        self::mockProperty($testDBO, 'tableName', $testName);
33
        $this->assertEquals($testName, $testDBO->getTableName());
34
    }
35
36
    public function testGetTableIndex()
37
    {
38
        $testIndex = 'id';
39
40
        $testDBO = new \Suricate\DBObject();
41
        self::mockProperty($testDBO, 'tableIndex', $testIndex);
42
        $this->assertEquals($testIndex, $testDBO->getTableIndex());
43
    }
44
45
    public function testGetDBConfig()
46
    {
47
        $testConfigName = 'my_config';
48
49
        $testDBO = new \Suricate\DBObject();
50
        self::mockProperty($testDBO, 'DBConfig', $testConfigName);
51
        $this->assertEquals($testConfigName, $testDBO->getDBConfig());
52
    }
53
54
    public function testUndefinedGet()
55
    {
56
        $testDBO = new \Suricate\DBObject();
57
        self::mockProperty($testDBO, 'dbVariables', ['id', 'name', 'last_update']);
58
        $this->expectException(\InvalidArgumentException::class);
59
        
60
        $testDBO->undefinedVar;
0 ignored issues
show
Bug Best Practice introduced by
The property undefinedVar does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
61
    }
62
63
    public function testDBProperty()
64
    {
65
        $testDBO = new \Suricate\DBObject();
66
        $testDBO->regularProperty = 42;
0 ignored issues
show
Bug Best Practice introduced by
The property regularProperty does not exist on Suricate\DBObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
67
        self::mockProperty($testDBO, 'dbVariables', ['id', 'name', 'not_loaded_var']);
68
        self::mockProperty($testDBO, 'dbValues', ['id' => 1, 'name' => 'test name']);
69
        $this->assertEquals($testDBO->id, 1);
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
70
        $this->assertNotEquals($testDBO->name, 'test name edited');
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
71
        $this->assertNull($testDBO->not_loaded_var);
0 ignored issues
show
Bug Best Practice introduced by
The property not_loaded_var does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
72
73
        $this->assertTrue($testDBO->isDBVariable('id'));
74
        $this->assertFalse($testDBO->isDBVariable('regularProperty'));
75
76
        $this->assertTrue($testDBO->propertyExists('regularProperty'));
77
        $this->assertTrue($testDBO->propertyExists('id'));
78
        $this->assertFalse($testDBO->propertyExists('unknownProperty'));
79
    }
80
81
    public function testIsset()
82
    {
83
        $testDBO = new \Suricate\DBObject();
84
        self::mockProperty($testDBO, 'dbVariables', ['id', 'name', 'not_loaded_var']);
85
        self::mockProperty($testDBO, 'dbValues', ['id' => 1, 'name' => 'test name']);
86
87
        $this->assertTrue(isset($testDBO->id));
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
88
        $this->assertFalse(isset($testDBO->undefVar));
0 ignored issues
show
Bug Best Practice introduced by
The property undefVar does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
89
    }
90
91
    public function testIsLoaded()
92
    {
93
        $testIndex = 'id';
94
95
        $testDBO = new \Suricate\DBObject();
96
        self::mockProperty($testDBO, 'tableIndex', $testIndex);
97
        self::mockProperty($testDBO, 'dbVariables', [$testIndex, 'name', 'not_loaded_var']);
98
        $this->assertFalse($testDBO->isLoaded());
99
100
        self::mockProperty($testDBO, 'dbValues', [$testIndex => 1, 'name' => 'test name']);
101
        $this->assertTrue($testDBO->isLoaded());
102
    }
103
104
    public function testHydrate()
105
    {
106
        $testDBO = new \Suricate\DBObject();
107
        $testDBO->realProperty = '';
0 ignored issues
show
Bug Best Practice introduced by
The property realProperty does not exist on Suricate\DBObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
108
109
        self::mockProperty($testDBO, 'dbVariables', ['id', 'name']);
110
        $testDBO->hydrate([
111
            'id' => 1,
112
            'name' => 'test record',
113
            'add_column' => 'test value',
114
            'realProperty' => 'my string',
115
        ]);
116
117
        $this->assertEquals($testDBO->realProperty, 'my string');
0 ignored issues
show
Bug Best Practice introduced by
The property realProperty does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
118
119
        $reflector = new ReflectionClass(get_class($testDBO));
120
        $property = $reflector->getProperty('dbValues');
121
        $property->setAccessible(true);
122
        $this->assertEquals([
123
            'id' => 1,
124
            'name' => 'test record',
125
        ], $property->getValue($testDBO));
126
    }
127
128
    public function testWakeup()
129
    {
130
        $mock = $this->getMockBuilder(\Suricate\DBObject::class)
131
            ->setMethods(['setRelations'])
132
            ->getMock();
133
134
        $mock
135
            ->expects($this->once())
136
            ->method('setRelations');
137
        
138
        $mock->__wakeup();
0 ignored issues
show
Bug introduced by
The method __wakeup() does not exist on PHPUnit\Framework\MockObject\MockObject. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

138
        $mock->/** @scrutinizer ignore-call */ 
139
               __wakeup();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
139
    }
140
141
    public function testRelations()
142
    {
143
        $relations = [
144
            'category' => [
145
                'type' => \Suricate\DBObject::RELATION_ONE_ONE,
146
                'source' => 'category_id',
147
                'target' => 'Category'
148
            ]
149
        ];
150
        // Prepare database
151
        $this->setupData();
152
        $mock = $this->getMockBuilder(\Suricate\DBObject::class)
153
            ->setMethods(['setRelations', 'getRelation'])
154
            ->getMock();
155
156
        // Prepare setup DBObject
157
        $testDBO = $this->getDBOject();
158
        $reflector = new ReflectionClass($mock);
159
        $property = $reflector->getProperty('relations');
160
        $property->setAccessible(true);
161
        $property->setValue($testDBO, $relations);
162
163
        // get relation values
164
        $property = $reflector->getProperty('relationValues');
165
        $property->setAccessible(true);
166
167
        // Load
168
        $testDBO->load(1);
169
        $relationsValues = $property->getValue($testDBO);
170
171
        // No relation values at first
172
        $this->assertSame([], $relationsValues);
173
        $this->assertEquals('Admin', $testDBO->category->name);
0 ignored issues
show
Bug Best Practice introduced by
The property category does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
174
        $this->assertInstanceOf('\Suricate\DBObject', $testDBO->category);
175
176
        $relationsValues = $property->getValue($testDBO);
177
        $this->assertArrayHasKey('category', $relationsValues);
178
        $this->assertInstanceOf('\Suricate\DBObject', $relationsValues['category']);
179
180
    }
181
182
    public function testLoad()
183
    {
184
        // Prepare database
185
        $this->setupData();
186
187
        // Inject database handler
188
        $testDBO = $this->getDBOject();
189
190
        $this->assertFalse($testDBO->isLoaded());
191
        $retVal = $testDBO->load(1);
192
        $this->assertTrue($testDBO->isLoaded());
193
        $this->assertEquals(1, $testDBO->id);
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
194
195
        $this->assertEquals('John', $testDBO->name);
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Suricate\DBObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
196
        
197
        $this->assertInstanceOf('\Suricate\DBObject', $retVal);
198
    }
199
    
200
201
    public static function mockProperty($object, string $propertyName, $value)
202
    {
203
        $reflectionClass = new \ReflectionClass($object);
204
205
        $property = $reflectionClass->getProperty($propertyName);
206
        $property->setAccessible(true);
207
        $property->setValue($object, $value);
208
        $property->setAccessible(false);
209
    }
210
211
    protected function setupData()
212
    {
213
        $pdo = new PDO('sqlite:/tmp/test.db');
214
        $pdo->exec("DROP TABLE IF EXISTS `users`");
215
        $pdo->exec("DROP TABLE IF EXISTS `categories`");
216
        $pdo->exec("CREATE TABLE `users` (`id` INTEGER PRIMARY KEY,`category_id` INTEGER, `name` varchar(50) DEFAULT NULL,`date_added` datetime NOT NULL)");
217
        $pdo->exec("CREATE TABLE `categories` (`id` INTEGER PRIMARY KEY, `name` varchar(50) DEFAULT NULL)");
218
        
219
        $stmt = $pdo->prepare("INSERT INTO `users` (name, category_id, date_added) VALUES (:name, :categoryid, :date)");
220
        $values = [
221
            ['John', 100, '2019-01-10 00:00:00'],
222
            ['Paul', 100, '2019-01-11 00:00:00'],
223
            ['Robert', 101, '2019-01-12 00:00:00']
224
        ];
225
        foreach ($values as $value) {
226
            $stmt->execute(['name' => $value[0], 'categoryid' => $value[1], 'date' => $value[2]]);
227
        }
228
229
        $stmt = $pdo->prepare("INSERT INTO `categories` (id, name) VALUES (:id, :name)");
230
        $values = [
231
            [100, 'Admin'],
232
            [101, 'Employee']
233
        ];
234
        foreach ($values as $value) {
235
            $stmt->execute(['id' => $value[0], 'name' => $value[1]]);
236
        }
237
    }
238
239
    protected function getDatabase()
240
    {
241
        $database = new \Suricate\Database();
242
        $database->configure([
243
            'type' => 'sqlite',
244
            'file' => '/tmp/test.db',
245
        ]);
246
247
        return $database;
248
    }
249
250
    protected function getDBOject()
251
    {
252
        $dbLink = $this->getDatabase();
253
        // Inject database handler
254
        $testDBO = new \Suricate\DBObject();
255
256
257
        $reflector = new ReflectionClass(get_class($testDBO));
258
        $property = $reflector->getProperty('dbLink');
259
        $property->setAccessible(true);
260
        $property->setValue($testDBO, $dbLink);
261
262
        self::mockProperty($testDBO, 'tableName', $this->tableName);
263
        self::mockProperty($testDBO, 'tableIndex', 'id');
264
        self::mockProperty($testDBO, 'dbVariables', ['id', 'category_id', 'name', 'date_added']);
265
266
        return $testDBO;
267
    }
268
}
269