Completed
Pull Request — master (#16)
by Joshua
02:23
created

PersisterTest::testGenerateIdObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace As3\Modlr\Persister\MongoDb\Tests;
4
5
use PHPUnit_Framework_TestCase;
6
use Doctrine\MongoDB\Configuration;
7
use Doctrine\MongoDB\Connection;
8
use As3\Modlr;
9
10
class PersisterTest extends PHPUnit_Framework_TestCase
11
{
12
    protected static $dbName = 'modlr_mongodb';
13
14
    protected $connection;
15
    protected $smf;
16
    protected $persister;
17
18
    public function setUp()
19
    {
20
        // Initialize the doctrine connection
21
        $config = new Configuration();
22
        $config->setLoggerCallable(function($msg) {});
23
        $this->connection = new Connection(null, array(), $config);
24
25
        // Initialize the metadata factory
26
        $typeFactory = new Modlr\DataTypes\TypeFactory;
27
        $validator = new Modlr\Util\Validator;
28
29
        $config = new Modlr\Rest\RestConfiguration($validator);
30
        $config->setRootEndpoint('/modlr/api/');
31
32
        $entityUtil = new Modlr\Util\EntityUtility($config, $typeFactory);
33
        $this->smf = new Modlr\Persister\MongoDb\StorageMetadataFactory($entityUtil);
34
35
        $formatter = new Modlr\Persister\MongoDb\Formatter();
36
        $query = new Modlr\Persister\MongoDb\Query($this->connection, $formatter);
37
38
        $hydrator = new Modlr\Persister\MongoDb\Hydrator();
39
        $schemaManager = new Modlr\Persister\MongoDb\SchemaManager();
40
41
        $this->persister = new Modlr\Persister\MongoDb\Persister($query, $this->smf, $hydrator, $schemaManager);
42
    }
43
44
    public function tearDown()
45
    {
46
        $collections = $this->connection->selectDatabase(self::$dbName)->listCollections();
47
        foreach ($collections as $collection) {
48
            $collection->drop();
49
        }
50
51
        $this->connection->close();
52
        unset($this->connection);
53
    }
54
55
    public function testPersisterValues()
56
    {
57
        $this->assertEquals('mongodb', $this->persister->getPersisterKey());
58
        $this->assertEquals('_type', $this->persister->getPolymorphicKey());
59
        $this->assertEquals('_id', $this->persister->getIdentifierKey());
60
    }
61
62
    public function testMDFInstance()
63
    {
64
        $this->assertInstanceOf(
65
            'As3\Modlr\Metadata\Interfaces\StorageMetadataFactoryInterface',
66
            $this->persister->getPersistenceMetadataFactory()
67
        );
68
    }
69
70
    /**
71
     * @expectedException           As3\Modlr\Persister\PersisterException
72
     * @expectedExceptionMessage    ID conversion currently only supports an object strategy, or none at all.
73
     */
74
    public function testConvertIdInvalidStrategy()
75
    {
76
        $this->assertInstanceOf('MongoId', $this->persister->convertId('test', 'blag'));
77
    }
78
79
    /**
80
     * @expectedException           As3\Modlr\Persister\PersisterException
81
     * @expectedExceptionMessage    ID generation currently only supports an object strategy, or none at all.
82
     */
83
    public function testGenerateIdInvalidStrategy()
84
    {
85
        $this->assertInstanceOf('MongoId', $this->persister->generateId('blag'));
86
    }
87
88
    public function testConvertIdObject()
89
    {
90
        $test = '49a7011a05c677b9a916612a';
91
        $id = new \MongoId($test);
92
93
        $this->assertEquals($id, $this->persister->convertId($id));
94
        $this->assertEquals($id, $this->persister->convertId($id, 'object'));
95
    }
96
97
    public function testGenerateIdObject()
98
    {
99
        $this->assertInstanceOf('MongoId', $this->persister->generateId());
100
        $this->assertInstanceOf('MongoId', $this->persister->generateId('object'));
101
    }
102
103
    /**
104
     * @expectedException           As3\Modlr\Persister\PersisterException
105
     * @expectedExceptionMessage    ID conversion currently only supports an object strategy, or none at all.
106
     */
107
    public function testConvertIdIncrementId()
108
    {
109
        $test = 12345;
110
        $this->assertEquals($test, $this->persister->convertId($test, 'incrementId'));
111
    }
112
113
    /**
114
     * @expectedException           As3\Modlr\Persister\PersisterException
115
     * @expectedExceptionMessage    ID generation currently only supports an object strategy, or none at all.
116
     */
117
    public function testGenerateIdIncrementId()
118
    {
119
        $val = $this->persister->generateId('incrementId');
120
        $this->assertGreaterThan($val, $this->persister->generateId('incrementId'));
121
    }
122
123
    public function testNameIsAppendedToSchemata()
124
    {
125
        $metadata = $this->getMetadata()->persistence;
126
127
        foreach ($metadata->schemata as $schema) {
0 ignored issues
show
Bug introduced by
Accessing schemata on the interface As3\Modlr\Metadata\Inter...s\StorageLayerInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
128
            $this->assertTrue(array_key_exists('name', $schema['options']), 'index name was not applied to schema');
129
            $this->assertTrue(!empty($schema['options']['name']), 'index name was not properly generated for schema');
130
            $this->assertSame(stripos($schema['options']['name'], 'modlr_'), 0, '`modlr_` prefix missing from schema name');
131
        }
132
    }
133
134
    /**
135
     * @expectedException           As3\Modlr\Exception\MetadataException
136
     * @expectedExceptionMessage    At least one key must be specified to define an index.
137
     */
138
    public function testSchemaRequiresAtLeastOneKey()
139
    {
140
        $schemata = [['options' => ['unique' => true]]];
141
        $metadata = $this->getMetadata($schemata);
0 ignored issues
show
Unused Code introduced by
$metadata is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
142
    }
143
144
    public function testSchemaCreation()
145
    {
146
        $metadata = $this->getMetadata();
147
        $this->persister->createSchemata($metadata);
148
149
        $collection = $this->connection->selectCollection(self::$dbName, 'test-model');
150
        $indices = $collection->getIndexInfo();
151
152
        foreach ($metadata->persistence->schemata as $schema) {
0 ignored issues
show
Bug introduced by
Accessing schemata on the interface As3\Modlr\Metadata\Inter...s\StorageLayerInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
153
            $found = false;
154
            foreach ($indices as $index) {
155
                if ($index['name'] === $schema['options']['name']) {
156
                    $found = true;
157
                }
158
            }
159
            $this->assertTrue($found, sprintf('Index for "%s" was not created!', $schema['options']['name']));
160
        }
161
    }
162
163
    private function getMetadata(array $schemata = [])
164
    {
165
        $mapping = [
166
            'type'          => 'test-model',
167
            'attributes'    => [
168
                'name'          => ['data_type' => 'string'],
169
                'active'        => ['data_type' => 'boolean']
170
            ],
171
            'persistence'   => [
172
                'db'            => self::$dbName,
173
                'collection'    => 'test-model',
174
                'schemata'      => [
175
                    ['keys' => ['name' => 1]],
176
                    ['keys' => ['active' => 1], ['options' => ['unique' => true]]]
177
                ]
178
            ]
179
        ];
180
        if (!empty($schemata)) {
181
            $mapping['persistence']['schemata'] = $schemata;
182
        }
183
        $metadata = new Modlr\Metadata\EntityMetadata($mapping['type']);
184
        $pmd = $this->smf->createInstance($mapping['persistence']);
185
        $metadata->setPersistence($pmd);
186
        $this->smf->handleValidate($metadata);
187
        return $metadata;
188
    }
189
}
190