Completed
Push — develop ( 56f424...dccc18 )
by Mathieu
01:46
created

DBObjectTest::testToJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 12
rs 10
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
        $reflector = new ReflectionClass($testDBO);
165
        $relationValuesRef = $reflector->getProperty('relationValues');
166
        $relationValuesRef->setAccessible(true);
167
168
        $loadedRelationsRef = $reflector->getProperty('loadedRelations');
169
        $loadedRelationsRef->setAccessible(true);
170
171
        // Load
172
        $testDBO->load(1);
173
        $relationsValues = $relationValuesRef->getValue($testDBO);
174
        $loadedRelations = $loadedRelationsRef->getValue($testDBO);
175
176
        // No relation values at first
177
        $this->assertSame([], $relationsValues);
178
        $this->assertSame([], $loadedRelations);
179
        $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...
180
        $this->assertInstanceOf('\Suricate\DBObject', $testDBO->category);
181
182
        $relationsValues = $relationValuesRef->getValue($testDBO);
183
        $loadedRelations = $loadedRelationsRef->getValue($testDBO);
184
185
        // Check relation cache has been set
186
        $this->assertArrayHasKey('category', $relationsValues);
187
188
        // Check relation loaded flag has been set
189
        $this->assertArrayHasKey('category', $loadedRelations);
190
191
        // Check return type of relation
192
        $this->assertInstanceOf('\Suricate\DBObject', $relationsValues['category']);
193
194
    }
195
196
    public function testLoad()
197
    {
198
        // Prepare database
199
        $this->setupData();
200
201
        // Inject database handler
202
        $testDBO = $this->getDBOject();
203
204
        $this->assertFalse($testDBO->isLoaded());
205
        $retVal = $testDBO->load(1);
206
        $this->assertTrue($testDBO->isLoaded());
207
        $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...
208
209
        $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...
210
        
211
        $this->assertInstanceOf('\Suricate\DBObject', $retVal);
212
    }
213
214
    public function testToArray()
215
    {
216
        // Prepare database
217
        $this->setupData();
218
219
        // Inject database handler
220
        $testDBO = $this->getDBOject();
221
        $testDBO->load(2);
222
        
223
        $this->assertSame([
224
            'id' => '2',
225
            'category_id' => '100',
226
            'name' => 'Paul',
227
            'date_added' => '2019-01-11 00:00:00',
228
            ],
229
            $testDBO->toArray()
230
        );
231
232
        $testDBO = $this->getDBOject();
233
        $testDBO->load(2);
234
        self::mockProperty($testDBO, 'exportedVariables', [
235
            'id' => 'id', 
236
            'category_id' => 'category_id,type:integer',
237
            'name' => 'name',
238
            'date_added' => '-']
239
        );
240
241
        $this->assertSame([
242
            'id' => '2',
243
            'category_id' => 100,
244
            'name' => 'Paul',
245
            ],
246
            $testDBO->toArray()
247
        );
248
    }
249
250
    public function testToJson()
251
    {
252
        // Prepare database
253
        $this->setupData();
254
255
        // Inject database handler
256
        $testDBO = $this->getDBOject();
257
        $testDBO->load(2);
258
259
        $this->assertSame(
260
            '{"id":"2","category_id":"100","name":"Paul","date_added":"2019-01-11 00:00:00"}',
261
            $testDBO->toJson()
262
        );
263
    }
264
265
    public static function mockProperty($object, string $propertyName, $value)
266
    {
267
        $reflectionClass = new \ReflectionClass($object);
268
269
        $property = $reflectionClass->getProperty($propertyName);
270
        $property->setAccessible(true);
271
        $property->setValue($object, $value);
272
        $property->setAccessible(false);
273
    }
274
275
    protected function setupData()
276
    {
277
        $pdo = new PDO('sqlite:/tmp/test.db');
278
        $pdo->exec("DROP TABLE IF EXISTS `users`");
279
        $pdo->exec("DROP TABLE IF EXISTS `categories`");
280
        $pdo->exec("CREATE TABLE `users` (`id` INTEGER PRIMARY KEY,`category_id` INTEGER, `name` varchar(50) DEFAULT NULL,`date_added` datetime NOT NULL)");
281
        $pdo->exec("CREATE TABLE `categories` (`id` INTEGER PRIMARY KEY, `name` varchar(50) DEFAULT NULL)");
282
        
283
        $stmt = $pdo->prepare("INSERT INTO `users` (name, category_id, date_added) VALUES (:name, :categoryid, :date)");
284
        $values = [
285
            ['John', 100, '2019-01-10 00:00:00'],
286
            ['Paul', 100, '2019-01-11 00:00:00'],
287
            ['Robert', 101, '2019-01-12 00:00:00']
288
        ];
289
        foreach ($values as $value) {
290
            $stmt->execute(['name' => $value[0], 'categoryid' => $value[1], 'date' => $value[2]]);
291
        }
292
293
        $stmt = $pdo->prepare("INSERT INTO `categories` (id, name) VALUES (:id, :name)");
294
        $values = [
295
            [100, 'Admin'],
296
            [101, 'Employee']
297
        ];
298
        foreach ($values as $value) {
299
            $stmt->execute(['id' => $value[0], 'name' => $value[1]]);
300
        }
301
    }
302
303
    protected function getDatabase()
304
    {
305
        $database = new \Suricate\Database();
306
        $database->configure([
307
            'type' => 'sqlite',
308
            'file' => '/tmp/test.db',
309
        ]);
310
311
        return $database;
312
    }
313
314
    protected function getDBOject()
315
    {
316
        $dbLink = $this->getDatabase();
317
        // Inject database handler
318
        $testDBO = new \Suricate\DBObject();
319
320
321
        $reflector = new ReflectionClass(get_class($testDBO));
322
        $property = $reflector->getProperty('dbLink');
323
        $property->setAccessible(true);
324
        $property->setValue($testDBO, $dbLink);
325
326
        self::mockProperty($testDBO, 'tableName', $this->tableName);
327
        self::mockProperty($testDBO, 'tableIndex', 'id');
328
        self::mockProperty($testDBO, 'dbVariables', ['id', 'category_id', 'name', 'date_added']);
329
330
        return $testDBO;
331
    }
332
}
333