ActiveRecordTest.php 34.8 KB
Newer Older
1 2
<?php

3
namespace yiiunit\extensions\elasticsearch;
4

5 6
use yii\base\Event;
use yii\db\BaseActiveRecord;
7
use yii\elasticsearch\Connection;
8
use yiiunit\framework\ar\ActiveRecordTestTrait;
9 10 11 12 13
use yiiunit\data\ar\elasticsearch\ActiveRecord;
use yiiunit\data\ar\elasticsearch\Customer;
use yiiunit\data\ar\elasticsearch\OrderItem;
use yiiunit\data\ar\elasticsearch\Order;
use yiiunit\data\ar\elasticsearch\Item;
14 15
use yiiunit\data\ar\elasticsearch\OrderWithNullFK;
use yiiunit\data\ar\elasticsearch\OrderItemWithNullFK;
16
use yiiunit\TestCase;
17

18 19 20
/**
 * @group elasticsearch
 */
21 22
class ActiveRecordTest extends ElasticSearchTestCase
{
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    use ActiveRecordTestTrait;

    public function getCustomerClass()
    {
        return Customer::className();
    }

    public function getItemClass()
    {
        return Item::className();
    }

    public function getOrderClass()
    {
        return Order::className();
    }

    public function getOrderItemClass()
    {
        return OrderItem::className();
    }

45 46 47 48 49 50 51 52 53
    public function getOrderWithNullFKClass()
    {
        return OrderWithNullFK::className();
    }
    public function getOrderItemWithNullFKmClass()
    {
        return OrderItemWithNullFK::className();
    }

54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * can be overridden to do things after save()
     */
    public function afterSave()
    {
        $this->getConnection()->createCommand()->flushIndex('yiitest');
    }

    public function setUp()
    {
        parent::setUp();

66
        /* @var $db Connection */
67 68 69 70 71 72 73 74 75 76 77 78 79
        $db = ActiveRecord::$db = $this->getConnection();

        // delete index
        if ($db->createCommand()->indexExists('yiitest')) {
            $db->createCommand()->deleteIndex('yiitest');
        }
        $db->createCommand()->createIndex('yiitest');

        $command = $db->createCommand();
        Customer::setUpMapping($command);
        Item::setUpMapping($command);
        Order::setUpMapping($command);
        OrderItem::setUpMapping($command);
80 81
        OrderWithNullFK::setUpMapping($command);
        OrderItemWithNullFK::setUpMapping($command);
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

        $db->createCommand()->flushIndex('yiitest');

        $customer = new Customer();
        $customer->id = 1;
        $customer->setAttributes(['email' => 'user1@example.com', 'name' => 'user1', 'address' => 'address1', 'status' => 1], false);
        $customer->save(false);
        $customer = new Customer();
        $customer->id = 2;
        $customer->setAttributes(['email' => 'user2@example.com', 'name' => 'user2', 'address' => 'address2', 'status' => 1], false);
        $customer->save(false);
        $customer = new Customer();
        $customer->id = 3;
        $customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2], false);
        $customer->save(false);
97

98 99
//		INSERT INTO category (name) VALUES ('Books');
//		INSERT INTO category (name) VALUES ('Movies');
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        $item = new Item();
        $item->id = 1;
        $item->setAttributes(['name' => 'Agile Web Application Development with Yii1.1 and PHP5', 'category_id' => 1], false);
        $item->save(false);
        $item = new Item();
        $item->id = 2;
        $item->setAttributes(['name' => 'Yii 1.1 Application Development Cookbook', 'category_id' => 1], false);
        $item->save(false);
        $item = new Item();
        $item->id = 3;
        $item->setAttributes(['name' => 'Ice Age', 'category_id' => 2], false);
        $item->save(false);
        $item = new Item();
        $item->id = 4;
        $item->setAttributes(['name' => 'Toy Story', 'category_id' => 2], false);
        $item->save(false);
        $item = new Item();
        $item->id = 5;
        $item->setAttributes(['name' => 'Cars', 'category_id' => 2], false);
        $item->save(false);

        $order = new Order();
        $order->id = 1;
124
        $order->setAttributes(['customer_id' => 1, 'created_at' => 1325282384, 'total' => 110.0, 'itemsArray' => [1, 2]], false);
125 126 127
        $order->save(false);
        $order = new Order();
        $order->id = 2;
128
        $order->setAttributes(['customer_id' => 2, 'created_at' => 1325334482, 'total' => 33.0, 'itemsArray' => [4, 5, 3]], false);
129 130 131
        $order->save(false);
        $order = new Order();
        $order->id = 3;
132
        $order->setAttributes(['customer_id' => 2, 'created_at' => 1325502201, 'total' => 40.0, 'itemsArray' => [2]], false);
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        $order->save(false);

        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 1, 'item_id' => 1, 'quantity' => 1, 'subtotal' => 30.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 1, 'item_id' => 2, 'quantity' => 2, 'subtotal' => 40.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 4, 'quantity' => 1, 'subtotal' => 10.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 5, 'quantity' => 1, 'subtotal' => 15.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 3, 'quantity' => 1, 'subtotal' => 8.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItem();
        $orderItem->setAttributes(['order_id' => 3, 'item_id' => 2, 'quantity' => 1, 'subtotal' => 40.0], false);
        $orderItem->save(false);

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        $order = new OrderWithNullFK();
        $order->id = 1;
        $order->setAttributes(['customer_id' => 1, 'created_at' => 1325282384, 'total' => 110.0], false);
        $order->save(false);
        $order = new OrderWithNullFK();
        $order->id = 2;
        $order->setAttributes(['customer_id' => 2, 'created_at' => 1325334482, 'total' => 33.0], false);
        $order->save(false);
        $order = new OrderWithNullFK();
        $order->id = 3;
        $order->setAttributes(['customer_id' => 2, 'created_at' => 1325502201, 'total' => 40.0], false);
        $order->save(false);

        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 1, 'item_id' => 1, 'quantity' => 1, 'subtotal' => 30.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 1, 'item_id' => 2, 'quantity' => 2, 'subtotal' => 40.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 4, 'quantity' => 1, 'subtotal' => 10.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 5, 'quantity' => 1, 'subtotal' => 15.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 2, 'item_id' => 3, 'quantity' => 1, 'subtotal' => 8.0], false);
        $orderItem->save(false);
        $orderItem = new OrderItemWithNullFK();
        $orderItem->setAttributes(['order_id' => 3, 'item_id' => 2, 'quantity' => 1, 'subtotal' => 40.0], false);
        $orderItem->save(false);

186 187 188
        $db->createCommand()->flushIndex('yiitest');
    }

189 190 191 192 193 194 195 196 197 198
    public function testSaveNoChanges()
    {
        // this should not fail with exception
        $customer = new Customer();
        // insert
        $customer->save(false);
        // update
        $customer->save(false);
    }

199 200 201
    public function testFindAsArray()
    {
        // asArray
Qiang Xue committed
202
        $customer = Customer::find()->where(['id' => 2])->asArray()->one();
203 204 205 206 207 208
        $this->assertEquals([
            'id' => 2,
            'email' => 'user2@example.com',
            'name' => 'user2',
            'address' => 'address2',
            'status' => 1,
209 210
//            '_score' => 1.0
        ], $customer['_source']);
211 212 213 214
    }

    public function testSearch()
    {
Qiang Xue committed
215
        $customers = Customer::find()->search()['hits'];
216 217 218 219 220 221 222
        $this->assertEquals(3, $customers['total']);
        $this->assertEquals(3, count($customers['hits']));
        $this->assertTrue($customers['hits'][0] instanceof Customer);
        $this->assertTrue($customers['hits'][1] instanceof Customer);
        $this->assertTrue($customers['hits'][2] instanceof Customer);

        // limit vs. totalcount
Qiang Xue committed
223
        $customers = Customer::find()->limit(2)->search()['hits'];
224 225 226 227
        $this->assertEquals(3, $customers['total']);
        $this->assertEquals(2, count($customers['hits']));

        // asArray
Qiang Xue committed
228
        $result = Customer::find()->asArray()->search()['hits'];
229 230 231
        $this->assertEquals(3, $result['total']);
        $customers = $result['hits'];
        $this->assertEquals(3, count($customers));
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        $this->assertArrayHasKey('id', $customers[0]['_source']);
        $this->assertArrayHasKey('name', $customers[0]['_source']);
        $this->assertArrayHasKey('email', $customers[0]['_source']);
        $this->assertArrayHasKey('address', $customers[0]['_source']);
        $this->assertArrayHasKey('status', $customers[0]['_source']);
        $this->assertArrayHasKey('id', $customers[1]['_source']);
        $this->assertArrayHasKey('name', $customers[1]['_source']);
        $this->assertArrayHasKey('email', $customers[1]['_source']);
        $this->assertArrayHasKey('address', $customers[1]['_source']);
        $this->assertArrayHasKey('status', $customers[1]['_source']);
        $this->assertArrayHasKey('id', $customers[2]['_source']);
        $this->assertArrayHasKey('name', $customers[2]['_source']);
        $this->assertArrayHasKey('email', $customers[2]['_source']);
        $this->assertArrayHasKey('address', $customers[2]['_source']);
        $this->assertArrayHasKey('status', $customers[2]['_source']);
247 248 249 250

        // TODO test asArray() + fields() + indexBy()

        // find by attributes
Qiang Xue committed
251
        $result = Customer::find()->where(['name' => 'user2'])->search()['hits'];
252 253 254 255 256 257 258 259 260
        $customer = reset($result['hits']);
        $this->assertTrue($customer instanceof Customer);
        $this->assertEquals(2, $customer->id);

        // TODO test query() and filter()
    }

    public function testSearchFacets()
    {
Qiang Xue committed
261
        $result = Customer::find()->addStatisticalFacet('status_stats', ['field' => 'status'])->search();
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        $this->assertArrayHasKey('facets', $result);
        $this->assertEquals(3, $result['facets']['status_stats']['count']);
        $this->assertEquals(4, $result['facets']['status_stats']['total']); // sum of values
        $this->assertEquals(1, $result['facets']['status_stats']['min']);
        $this->assertEquals(2, $result['facets']['status_stats']['max']);
    }

    public function testGetDb()
    {
        $this->mockApplication(['components' => ['elasticsearch' => Connection::className()]]);
        $this->assertInstanceOf(Connection::className(), ActiveRecord::getDb());
    }

    public function testGet()
    {
        $this->assertInstanceOf(Customer::className(), Customer::get(1));
        $this->assertNull(Customer::get(5));
    }

    public function testMget()
    {
        $this->assertEquals([], Customer::mget([]));

        $records = Customer::mget([1]);
        $this->assertEquals(1, count($records));
        $this->assertInstanceOf(Customer::className(), reset($records));

        $records = Customer::mget([5]);
        $this->assertEquals(0, count($records));

        $records = Customer::mget([1, 3, 5]);
        $this->assertEquals(2, count($records));
        $this->assertInstanceOf(Customer::className(), $records[0]);
        $this->assertInstanceOf(Customer::className(), $records[1]);
    }

    public function testFindLazy()
    {
300
        /* @var $customer Customer */
Alexander Makarov committed
301
        $customer = Customer::findOne(2);
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        $orders = $customer->orders;
        $this->assertEquals(2, count($orders));

        $orders = $customer->getOrders()->where(['between', 'created_at', 1325334000, 1325400000])->all();
        $this->assertEquals(1, count($orders));
        $this->assertEquals(2, $orders[0]->id);
    }

    public function testFindEagerViaRelation()
    {
        $orders = Order::find()->with('items')->orderBy('created_at')->all();
        $this->assertEquals(3, count($orders));
        $order = $orders[0];
        $this->assertEquals(1, $order->id);
        $this->assertTrue($order->isRelationPopulated('items'));
        $this->assertEquals(2, count($order->items));
        $this->assertEquals(1, $order->items[0]->id);
        $this->assertEquals(2, $order->items[1]->id);
    }

    public function testInsertNoPk()
    {
        $this->assertEquals(['id'], Customer::primaryKey());
        $pkName = 'id';

        $customer = new Customer;
        $customer->email = 'user4@example.com';
        $customer->name = 'user4';
        $customer->address = 'address4';

        $this->assertNull($customer->primaryKey);
        $this->assertNull($customer->oldPrimaryKey);
        $this->assertNull($customer->$pkName);
        $this->assertTrue($customer->isNewRecord);

        $customer->save();
        $this->afterSave();

        $this->assertNotNull($customer->primaryKey);
        $this->assertNotNull($customer->oldPrimaryKey);
        $this->assertNotNull($customer->$pkName);
        $this->assertEquals($customer->primaryKey, $customer->oldPrimaryKey);
        $this->assertEquals($customer->primaryKey, $customer->$pkName);
        $this->assertFalse($customer->isNewRecord);
    }

    public function testInsertPk()
    {
        $pkName = 'id';

        $customer = new Customer;
        $customer->$pkName = 5;
        $customer->email = 'user5@example.com';
        $customer->name = 'user5';
        $customer->address = 'address5';

        $this->assertTrue($customer->isNewRecord);

        $customer->save();

        $this->assertEquals(5, $customer->primaryKey);
        $this->assertEquals(5, $customer->oldPrimaryKey);
        $this->assertEquals(5, $customer->$pkName);
        $this->assertFalse($customer->isNewRecord);
    }

    public function testUpdatePk()
    {
        $pkName = 'id';

Alexander Makarov committed
372
        $orderItem = Order::findOne([$pkName => 2]);
373 374 375
        $this->assertEquals(2, $orderItem->primaryKey);
        $this->assertEquals(2, $orderItem->oldPrimaryKey);
        $this->assertEquals(2, $orderItem->$pkName);
376

377
//		$this->setExpectedException('yii\base\InvalidCallException');
378 379 380 381 382 383 384 385 386 387
        $orderItem->$pkName = 13;
        $this->assertEquals(13, $orderItem->primaryKey);
        $this->assertEquals(2, $orderItem->oldPrimaryKey);
        $this->assertEquals(13, $orderItem->$pkName);
        $orderItem->save();
        $this->afterSave();
        $this->assertEquals(13, $orderItem->primaryKey);
        $this->assertEquals(13, $orderItem->oldPrimaryKey);
        $this->assertEquals(13, $orderItem->$pkName);

Alexander Makarov committed
388 389
        $this->assertNull(Order::findOne([$pkName => 2]));
        $this->assertNotNull(Order::findOne([$pkName => 13]));
390 391 392 393
    }

    public function testFindLazyVia2()
    {
394 395
        /* @var $this TestCase|ActiveRecordTestTrait */
        /* @var $order Order */
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        $orderClass = $this->getOrderClass();
        $pkName = 'id';

        $order = new $orderClass();
        $order->$pkName = 100;
        $this->assertEquals([], $order->items);
    }

    /**
     * Some PDO implementations(e.g. cubrid) do not support boolean values.
     * Make sure this does not affect AR layer.
     */
    public function testBooleanAttribute()
    {
        $db = $this->getConnection();
        Customer::deleteAll();
        Customer::setUpMapping($db->createCommand(), true);

        $customerClass = $this->getCustomerClass();
        $customer = new $customerClass();
        $customer->name = 'boolean customer';
        $customer->email = 'mail@example.com';
        $customer->status = true;
        $customer->save(false);

        $customer->refresh();
        $this->assertEquals(true, $customer->status);

        $customer->status = false;
        $customer->save(false);

        $customer->refresh();
        $this->assertEquals(false, $customer->status);

        $customer = new Customer();
        $customer->setAttributes(['email' => 'user2b@example.com', 'name' => 'user2b', 'status' => true], false);
        $customer->save(false);
        $customer = new Customer();
        $customer->setAttributes(['email' => 'user3b@example.com', 'name' => 'user3b', 'status' => false], false);
        $customer->save(false);
        $this->afterSave();

Qiang Xue committed
438
        $customers = Customer::find()->where(['status' => true])->all();
439 440
        $this->assertEquals(1, count($customers));

Qiang Xue committed
441
        $customers = Customer::find()->where(['status' => false])->all();
442 443 444
        $this->assertEquals(2, count($customers));
    }

445 446 447 448 449 450 451 452
    public function testScriptFields()
    {
        $orderItems = OrderItem::find()->fields(['quantity', 'subtotal', 'total' => ['script' => "doc['quantity'].value * doc['subtotal'].value"]])->all();
        foreach($orderItems as $item) {
            $this->assertEquals($item->subtotal * $item->quantity, $item->total);
        }
    }

453 454
    public function testFindAsArrayFields()
    {
455
        /* @var $this TestCase|ActiveRecordTestTrait */
456
        // indexBy + asArray
Qiang Xue committed
457
        $customers = Customer::find()->asArray()->fields(['id', 'name'])->all();
458
        $this->assertEquals(3, count($customers));
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        $this->assertArrayHasKey('id', $customers[0]['fields']);
        $this->assertArrayHasKey('name', $customers[0]['fields']);
        $this->assertArrayNotHasKey('email', $customers[0]['fields']);
        $this->assertArrayNotHasKey('address', $customers[0]['fields']);
        $this->assertArrayNotHasKey('status', $customers[0]['fields']);
        $this->assertArrayHasKey('id', $customers[1]['fields']);
        $this->assertArrayHasKey('name', $customers[1]['fields']);
        $this->assertArrayNotHasKey('email', $customers[1]['fields']);
        $this->assertArrayNotHasKey('address', $customers[1]['fields']);
        $this->assertArrayNotHasKey('status', $customers[1]['fields']);
        $this->assertArrayHasKey('id', $customers[2]['fields']);
        $this->assertArrayHasKey('name', $customers[2]['fields']);
        $this->assertArrayNotHasKey('email', $customers[2]['fields']);
        $this->assertArrayNotHasKey('address', $customers[2]['fields']);
        $this->assertArrayNotHasKey('status', $customers[2]['fields']);
474 475
    }

476 477
    public function testFindAsArraySourceFilter()
    {
478
        /* @var $this TestCase|ActiveRecordTestTrait */
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        // indexBy + asArray
        $customers = Customer::find()->asArray()->source(['id', 'name'])->all();
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers[0]['_source']);
        $this->assertArrayHasKey('name', $customers[0]['_source']);
        $this->assertArrayNotHasKey('email', $customers[0]['_source']);
        $this->assertArrayNotHasKey('address', $customers[0]['_source']);
        $this->assertArrayNotHasKey('status', $customers[0]['_source']);
        $this->assertArrayHasKey('id', $customers[1]['_source']);
        $this->assertArrayHasKey('name', $customers[1]['_source']);
        $this->assertArrayNotHasKey('email', $customers[1]['_source']);
        $this->assertArrayNotHasKey('address', $customers[1]['_source']);
        $this->assertArrayNotHasKey('status', $customers[1]['_source']);
        $this->assertArrayHasKey('id', $customers[2]['_source']);
        $this->assertArrayHasKey('name', $customers[2]['_source']);
        $this->assertArrayNotHasKey('email', $customers[2]['_source']);
        $this->assertArrayNotHasKey('address', $customers[2]['_source']);
        $this->assertArrayNotHasKey('status', $customers[2]['_source']);
    }


    public function testFindIndexBySource()
501 502
    {
        $customerClass = $this->getCustomerClass();
503
        /* @var $this TestCase|ActiveRecordTestTrait */
504
        // indexBy + asArray
505
        $customers = Customer::find()->indexBy('name')->source('id', 'name')->all();
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers['user1'] instanceof $customerClass);
        $this->assertTrue($customers['user2'] instanceof $customerClass);
        $this->assertTrue($customers['user3'] instanceof $customerClass);
        $this->assertNotNull($customers['user1']->id);
        $this->assertNotNull($customers['user1']->name);
        $this->assertNull($customers['user1']->email);
        $this->assertNull($customers['user1']->address);
        $this->assertNull($customers['user1']->status);
        $this->assertNotNull($customers['user2']->id);
        $this->assertNotNull($customers['user2']->name);
        $this->assertNull($customers['user2']->email);
        $this->assertNull($customers['user2']->address);
        $this->assertNull($customers['user2']->status);
        $this->assertNotNull($customers['user3']->id);
        $this->assertNotNull($customers['user3']->name);
        $this->assertNull($customers['user3']->email);
        $this->assertNull($customers['user3']->address);
        $this->assertNull($customers['user3']->status);

        // indexBy callable + asArray
Qiang Xue committed
527
        $customers = Customer::find()->indexBy(function ($customer) {
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
            return $customer->id . '-' . $customer->name;
        })->fields('id', 'name')->all();
        $this->assertEquals(3, count($customers));
        $this->assertTrue($customers['1-user1'] instanceof $customerClass);
        $this->assertTrue($customers['2-user2'] instanceof $customerClass);
        $this->assertTrue($customers['3-user3'] instanceof $customerClass);
        $this->assertNotNull($customers['1-user1']->id);
        $this->assertNotNull($customers['1-user1']->name);
        $this->assertNull($customers['1-user1']->email);
        $this->assertNull($customers['1-user1']->address);
        $this->assertNull($customers['1-user1']->status);
        $this->assertNotNull($customers['2-user2']->id);
        $this->assertNotNull($customers['2-user2']->name);
        $this->assertNull($customers['2-user2']->email);
        $this->assertNull($customers['2-user2']->address);
        $this->assertNull($customers['2-user2']->status);
        $this->assertNotNull($customers['3-user3']->id);
        $this->assertNotNull($customers['3-user3']->name);
        $this->assertNull($customers['3-user3']->email);
        $this->assertNull($customers['3-user3']->address);
        $this->assertNull($customers['3-user3']->status);
    }

    public function testFindIndexByAsArrayFields()
    {
553
        /* @var $this TestCase|ActiveRecordTestTrait */
554
        // indexBy + asArray
Qiang Xue committed
555
        $customers = Customer::find()->indexBy('name')->asArray()->fields('id', 'name')->all();
556
        $this->assertEquals(3, count($customers));
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        $this->assertArrayHasKey('id', $customers['user1']['fields']);
        $this->assertArrayHasKey('name', $customers['user1']['fields']);
        $this->assertArrayNotHasKey('email', $customers['user1']['fields']);
        $this->assertArrayNotHasKey('address', $customers['user1']['fields']);
        $this->assertArrayNotHasKey('status', $customers['user1']['fields']);
        $this->assertArrayHasKey('id', $customers['user2']['fields']);
        $this->assertArrayHasKey('name', $customers['user2']['fields']);
        $this->assertArrayNotHasKey('email', $customers['user2']['fields']);
        $this->assertArrayNotHasKey('address', $customers['user2']['fields']);
        $this->assertArrayNotHasKey('status', $customers['user2']['fields']);
        $this->assertArrayHasKey('id', $customers['user3']['fields']);
        $this->assertArrayHasKey('name', $customers['user3']['fields']);
        $this->assertArrayNotHasKey('email', $customers['user3']['fields']);
        $this->assertArrayNotHasKey('address', $customers['user3']['fields']);
        $this->assertArrayNotHasKey('status', $customers['user3']['fields']);
572 573

        // indexBy callable + asArray
Qiang Xue committed
574
        $customers = Customer::find()->indexBy(function ($customer) {
575
            return reset($customer['fields']['id']) . '-' . reset($customer['fields']['name']);
576 577
        })->asArray()->fields('id', 'name')->all();
        $this->assertEquals(3, count($customers));
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
        $this->assertArrayHasKey('id', $customers['1-user1']['fields']);
        $this->assertArrayHasKey('name', $customers['1-user1']['fields']);
        $this->assertArrayNotHasKey('email', $customers['1-user1']['fields']);
        $this->assertArrayNotHasKey('address', $customers['1-user1']['fields']);
        $this->assertArrayNotHasKey('status', $customers['1-user1']['fields']);
        $this->assertArrayHasKey('id', $customers['2-user2']['fields']);
        $this->assertArrayHasKey('name', $customers['2-user2']['fields']);
        $this->assertArrayNotHasKey('email', $customers['2-user2']['fields']);
        $this->assertArrayNotHasKey('address', $customers['2-user2']['fields']);
        $this->assertArrayNotHasKey('status', $customers['2-user2']['fields']);
        $this->assertArrayHasKey('id', $customers['3-user3']['fields']);
        $this->assertArrayHasKey('name', $customers['3-user3']['fields']);
        $this->assertArrayNotHasKey('email', $customers['3-user3']['fields']);
        $this->assertArrayNotHasKey('address', $customers['3-user3']['fields']);
        $this->assertArrayNotHasKey('status', $customers['3-user3']['fields']);
    }

    public function testFindIndexByAsArray()
    {
597
        /* @var $customerClass \yii\db\ActiveRecordInterface */
598 599
        $customerClass = $this->getCustomerClass();

600
        /* @var $this TestCase|ActiveRecordTestTrait */
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        // indexBy + asArray
        $customers = $customerClass::find()->asArray()->indexBy('name')->all();
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers['user1']['_source']);
        $this->assertArrayHasKey('name', $customers['user1']['_source']);
        $this->assertArrayHasKey('email', $customers['user1']['_source']);
        $this->assertArrayHasKey('address', $customers['user1']['_source']);
        $this->assertArrayHasKey('status', $customers['user1']['_source']);
        $this->assertArrayHasKey('id', $customers['user2']['_source']);
        $this->assertArrayHasKey('name', $customers['user2']['_source']);
        $this->assertArrayHasKey('email', $customers['user2']['_source']);
        $this->assertArrayHasKey('address', $customers['user2']['_source']);
        $this->assertArrayHasKey('status', $customers['user2']['_source']);
        $this->assertArrayHasKey('id', $customers['user3']['_source']);
        $this->assertArrayHasKey('name', $customers['user3']['_source']);
        $this->assertArrayHasKey('email', $customers['user3']['_source']);
        $this->assertArrayHasKey('address', $customers['user3']['_source']);
        $this->assertArrayHasKey('status', $customers['user3']['_source']);

        // indexBy callable + asArray
        $customers = $customerClass::find()->indexBy(function ($customer) {
            return $customer['_source']['id'] . '-' . $customer['_source']['name'];
        })->asArray()->all();
        $this->assertEquals(3, count($customers));
        $this->assertArrayHasKey('id', $customers['1-user1']['_source']);
        $this->assertArrayHasKey('name', $customers['1-user1']['_source']);
        $this->assertArrayHasKey('email', $customers['1-user1']['_source']);
        $this->assertArrayHasKey('address', $customers['1-user1']['_source']);
        $this->assertArrayHasKey('status', $customers['1-user1']['_source']);
        $this->assertArrayHasKey('id', $customers['2-user2']['_source']);
        $this->assertArrayHasKey('name', $customers['2-user2']['_source']);
        $this->assertArrayHasKey('email', $customers['2-user2']['_source']);
        $this->assertArrayHasKey('address', $customers['2-user2']['_source']);
        $this->assertArrayHasKey('status', $customers['2-user2']['_source']);
        $this->assertArrayHasKey('id', $customers['3-user3']['_source']);
        $this->assertArrayHasKey('name', $customers['3-user3']['_source']);
        $this->assertArrayHasKey('email', $customers['3-user3']['_source']);
        $this->assertArrayHasKey('address', $customers['3-user3']['_source']);
        $this->assertArrayHasKey('status', $customers['3-user3']['_source']);
640 641 642 643
    }

    public function testAfterFindGet()
    {
644
        /* @var $customerClass BaseActiveRecord */
645 646 647 648
        $customerClass = $this->getCustomerClass();

        $afterFindCalls = [];
        Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND, function ($event) use (&$afterFindCalls) {
649
            /* @var $ar BaseActiveRecord */
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
            $ar = $event->sender;
            $afterFindCalls[] = [get_class($ar), $ar->getIsNewRecord(), $ar->getPrimaryKey(), $ar->isRelationPopulated('orders')];
        });

        $customer = Customer::get(1);
        $this->assertNotNull($customer);
        $this->assertEquals([[$customerClass, false, 1, false]], $afterFindCalls);
        $afterFindCalls = [];

        $customer = Customer::mget([1, 2]);
        $this->assertNotNull($customer);
        $this->assertEquals([
            [$customerClass, false, 1, false],
            [$customerClass, false, 2, false],
        ], $afterFindCalls);
        $afterFindCalls = [];

        Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_FIND);
    }

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    public function testFindEmptyPkCondition()
    {
        /* @var $this TestCase|ActiveRecordTestTrait */
        /* @var $orderItemClass \yii\db\ActiveRecordInterface */
        $orderItemClass = $this->getOrderItemClass();
        $orderItem = new $orderItemClass();
        $orderItem->setAttributes(['order_id' => 1, 'item_id' => 1, 'quantity' => 1, 'subtotal' => 30.0], false);
        $orderItem->save(false);
        $this->afterSave();

        $orderItems = $orderItemClass::find()->where(['_id' => [$orderItem->getPrimaryKey()]])->all();
        $this->assertEquals(1, count($orderItems));

        $orderItems = $orderItemClass::find()->where(['_id' => []])->all();
        $this->assertEquals(0, count($orderItems));

        $orderItems = $orderItemClass::find()->where(['_id' => null])->all();
        $this->assertEquals(0, count($orderItems));

        $orderItems = $orderItemClass::find()->where(['IN', '_id', [$orderItem->getPrimaryKey()]])->all();
        $this->assertEquals(1, count($orderItems));

        $orderItems = $orderItemClass::find()->where(['IN', '_id', []])->all();
        $this->assertEquals(0, count($orderItems));

        $orderItems = $orderItemClass::find()->where(['IN', '_id', [null]])->all();
        $this->assertEquals(0, count($orderItems));
    }

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
    public function testArrayAttributes()
    {
        $this->assertTrue(is_array(Order::findOne(1)->itemsArray));
        $this->assertTrue(is_array(Order::findOne(2)->itemsArray));
        $this->assertTrue(is_array(Order::findOne(3)->itemsArray));
    }

    public function testArrayAttributeRelationLazy()
    {
        $order = Order::findOne(1);
        $items = $order->itemsByArrayValue;
        $this->assertEquals(2, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));
        $this->assertTrue($items[1] instanceof Item);
        $this->assertTrue($items[2] instanceof Item);

        $order = Order::findOne(2);
        $items = $order->itemsByArrayValue;
        $this->assertEquals(3, count($items));
        $this->assertTrue(isset($items[3]));
        $this->assertTrue(isset($items[4]));
        $this->assertTrue(isset($items[5]));
        $this->assertTrue($items[3] instanceof Item);
        $this->assertTrue($items[4] instanceof Item);
        $this->assertTrue($items[5] instanceof Item);
    }

    public function testArrayAttributeRelationEager()
    {
        /* @var $order Order */
        $order = Order::find()->with('itemsByArrayValue')->where(['id' => 1])->one();
        $this->assertTrue($order->isRelationPopulated('itemsByArrayValue'));
        $items = $order->itemsByArrayValue;
        $this->assertEquals(2, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));
        $this->assertTrue($items[1] instanceof Item);
        $this->assertTrue($items[2] instanceof Item);

        /* @var $order Order */
        $order = Order::find()->with('itemsByArrayValue')->where(['id' => 2])->one();
741
        $this->assertTrue($order->isRelationPopulated('itemsByArrayValue'));
742 743 744 745 746 747 748 749 750
        $items = $order->itemsByArrayValue;
        $this->assertEquals(3, count($items));
        $this->assertTrue(isset($items[3]));
        $this->assertTrue(isset($items[4]));
        $this->assertTrue(isset($items[5]));
        $this->assertTrue($items[3] instanceof Item);
        $this->assertTrue($items[4] instanceof Item);
        $this->assertTrue($items[5] instanceof Item);
    }
751

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    public function testArrayAttributeRelationLink()
    {
        /* @var $order Order */
        $order = Order::find()->where(['id' => 1])->one();
        $items = $order->itemsByArrayValue;
        $this->assertEquals(2, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));

        $item = Item::get(5);
        $order->link('itemsByArrayValue', $item);
        $this->afterSave();

        $items = $order->itemsByArrayValue;
        $this->assertEquals(3, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));
        $this->assertTrue(isset($items[5]));

        // check also after refresh
        $this->assertTrue($order->refresh());
        $items = $order->itemsByArrayValue;
        $this->assertEquals(3, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));
        $this->assertTrue(isset($items[5]));
    }

    public function testArrayAttributeRelationUnLink()
    {
        /* @var $order Order */
        $order = Order::find()->where(['id' => 1])->one();
        $items = $order->itemsByArrayValue;
        $this->assertEquals(2, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));

        $item = Item::get(2);
        $order->unlink('itemsByArrayValue', $item);
        $this->afterSave();

        $items = $order->itemsByArrayValue;
        $this->assertEquals(1, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertFalse(isset($items[2]));

        // check also after refresh
        $this->assertTrue($order->refresh());
        $items = $order->itemsByArrayValue;
        $this->assertEquals(1, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertFalse(isset($items[2]));
    }

    public function testArrayAttributeRelationUnLinkAll()
    {
        /* @var $order Order */
        $order = Order::find()->where(['id' => 1])->one();
        $items = $order->itemsByArrayValue;
        $this->assertEquals(2, count($items));
        $this->assertTrue(isset($items[1]));
        $this->assertTrue(isset($items[2]));

        $order->unlinkAll('itemsByArrayValue');
        $this->afterSave();

        $items = $order->itemsByArrayValue;
        $this->assertEquals(0, count($items));

        // check also after refresh
        $this->assertTrue($order->refresh());
        $items = $order->itemsByArrayValue;
        $this->assertEquals(0, count($items));
    }


828
    // TODO test AR with not mapped PK
Alexander Kochetov committed
829
}