diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..fcdf61edc --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..bd031bc1e --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: jenssegers +open_collective: laravel-mongodb diff --git a/.gitignore b/.gitignore index 1fe4e30f6..c7e087c4c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ composer.lock *.sublime-workspace *.project .idea/ +.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml index a6358266b..736c4c86e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,20 +1,27 @@ -sudo: required -dist: trusty -language: php -php: - - "7.2" - - "7.1" +language: minimal + +matrix: + include: + - name: "7.1" + env: PHP_VERSION=7.1 + - name: "7.2" + env: PHP_VERSION=7.2 + - name: "7.3" + env: PHP_VERSION=7.3 services: - docker +cache: + directories: + - $HOME/.composer/cache + install: - docker version - sudo pip install docker-compose - docker-compose version - - sed -i -e "s/php:cli/php:${TRAVIS_PHP_VERSION}-cli/g" Dockerfile - - cat Dockerfile - - docker-compose build + - docker-compose build --build-arg PHP_VERSION=${PHP_VERSION} + - docker-compose run --rm tests composer install --no-interaction script: - - docker-compose up --exit-code-from php + - docker-compose run --rm tests ./vendor/bin/phpunit --coverage-clover ./clover.xml diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 03c2ba7e2..000000000 --- a/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM php:cli - -RUN pecl install xdebug - -RUN apt-get update && \ - apt-get install -y autoconf pkg-config libssl-dev git && \ - pecl install mongodb git zlib1g-dev && docker-php-ext-enable mongodb && \ - docker-php-ext-install -j$(nproc) pdo pdo_mysql zip && docker-php-ext-enable xdebug - -RUN curl -sS https://getcomposer.org/installer | php \ - && mv composer.phar /usr/local/bin/ \ - && ln -s /usr/local/bin/composer.phar /usr/local/bin/composer - -ENV PATH="~/.composer/vendor/bin:./vendor/bin:${PATH}" diff --git a/README.md b/README.md index 4073209df..3eb0030b4 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ composer require jenssegers/mongodb 5.4.x | 3.2.x 5.5.x | 3.3.x 5.6.x | 3.4.x + 5.7.x | 3.4.x + 5.8.x | 3.5.x And add the service provider in `config/app.php`: @@ -63,8 +65,10 @@ The service provider will register a mongodb database extension with the origina For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add: ```php -$capsule->getDatabaseManager()->extend('mongodb', function($config) +$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) { + $config['name'] = $name; + return new Jenssegers\Mongodb\Connection($config); }); ``` @@ -298,7 +302,7 @@ This service provider will slightly modify the internal DatabaseReminderReposito ### Queues -If you want to use MongoDB as your database backend, change the the driver in `config/queue.php`: +If you want to use MongoDB as your database backend, change the driver in `config/queue.php`: ```php 'connections' => [ @@ -480,7 +484,7 @@ User::where('name', 'Jaques')->decrement('weight', 50); The number of updated objects is returned: ```php -$count = User->increment('age'); +$count = User::increment('age'); ``` You may also specify additional columns to update: @@ -545,13 +549,13 @@ User::where('name', 'regex', new \MongoDB\BSON\Regex("/.*doe/i"))->get(); **NOTE:** you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoDB\BSON\Regex object. ```php -User::where('name', 'regexp', '/.*doe/i'))->get(); +User::where('name', 'regexp', '/.*doe/i')->get(); ``` And the inverse: ```php -User::where('name', 'not regexp', '/.*doe/i'))->get(); +User::where('name', 'not regexp', '/.*doe/i')->get(); ``` **Type** @@ -689,7 +693,7 @@ For more information about model manipulation, check http://laravel.com/docs/elo ### Dates -Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators +Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields, you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators Example: @@ -806,7 +810,7 @@ class User extends Eloquent { } ``` -You access the embedded models through the dynamic property: +You can access the embedded models through the dynamic property: ```php $books = User::first()->books; @@ -868,7 +872,7 @@ Embedded relations will return a Collection of embedded items instead of a query ### EmbedsOne Relations -The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model. +The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. ```php use Jenssegers\Mongodb\Eloquent\Model as Eloquent; @@ -883,7 +887,7 @@ class Book extends Eloquent { } ``` -You access the embedded models through the dynamic property: +You can access the embedded models through the dynamic property: ```php $author = Book::first()->author; @@ -1033,7 +1037,7 @@ DB::collection('items')->paginate($limit, $projections); **Push** -Add an items to an array. +Add items to an array. ```php DB::collection('users')->where('name', 'John')->push('items', 'boots'); diff --git a/composer.json b/composer.json index ce32f6407..b683abfc8 100644 --- a/composer.json +++ b/composer.json @@ -1,51 +1,59 @@ -{ - "name": "jenssegers/mongodb", - "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", - "keywords": ["laravel","eloquent","mongodb","mongo","database","model","moloquent"], - "homepage": "https://github.com/jenssegers/laravel-mongodb", - "authors": [ - { - "name": "Jens Segers", - "homepage": "https://jenssegers.com" - } - ], - "license" : "MIT", - "require": { - "illuminate/support": "^5.6", - "illuminate/container": "^5.6", - "illuminate/database": "^5.6", - "illuminate/events": "^5.6", - "mongodb/mongodb": "^1.0.0" - }, - "require-dev": { - "phpunit/phpunit": "^6.0|^7.0", - "orchestra/testbench": "^3.1", - "mockery/mockery": "^1.0", - "satooshi/php-coveralls": "^2.0", - "doctrine/dbal": "^2.5" - }, - "autoload": { - "psr-0": { - "Jenssegers\\Mongodb": "src/" - } - }, - "autoload-dev": { - "classmap": [ - "tests/TestCase.php", - "tests/models", - "tests/seeds" - ] - }, - "suggest": { - "jenssegers/mongodb-session": "Add MongoDB session support to Laravel-MongoDB", - "jenssegers/mongodb-sentry": "Add Sentry support to Laravel-MongoDB" - }, - "extra": { - "laravel": { - "providers": [ - "Jenssegers\\Mongodb\\MongodbServiceProvider", - "Jenssegers\\Mongodb\\MongodbQueueServiceProvider" - ] - } - } -} +{ + "name": "jenssegers/mongodb", + "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", + "keywords": [ + "laravel", + "eloquent", + "mongodb", + "mongo", + "database", + "model", + "moloquent" + ], + "homepage": "https://github.com/jenssegers/laravel-mongodb", + "authors": [ + { + "name": "Jens Segers", + "homepage": "https://jenssegers.com" + } + ], + "license": "MIT", + "require": { + "illuminate/support": "^5.8|^6.0", + "illuminate/container": "^5.8|^6.0", + "illuminate/database": "^5.8|^6.0", + "illuminate/events": "^5.8|^6.0", + "mongodb/mongodb": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^6.0|^7.0|^8.0", + "orchestra/testbench": "^3.1|^4.0", + "mockery/mockery": "^1.0", + "satooshi/php-coveralls": "^2.0", + "doctrine/dbal": "^2.5" + }, + "autoload": { + "psr-0": { + "Jenssegers\\Mongodb": "src/" + } + }, + "autoload-dev": { + "classmap": [ + "tests/TestCase.php", + "tests/models", + "tests/seeds" + ] + }, + "suggest": { + "jenssegers/mongodb-session": "Add MongoDB session support to Laravel-MongoDB", + "jenssegers/mongodb-sentry": "Add Sentry support to Laravel-MongoDB" + }, + "extra": { + "laravel": { + "providers": [ + "Jenssegers\\Mongodb\\MongodbServiceProvider", + "Jenssegers\\Mongodb\\MongodbQueueServiceProvider" + ] + } + } +} diff --git a/docker-compose.yml b/docker-compose.yml index c1d83dd97..c6f20163e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,23 +1,21 @@ version: '3' services: - - php: - container_name: php + tests: + container_name: tests build: context: . dockerfile: Dockerfile volumes: - .:/code working_dir: /code - command: bash -c "composer install --prefer-source --no-interaction && php ./vendor/bin/phpunit" depends_on: - - mysql - mongodb + - mysql mysql: container_name: mysql - image: mysql + image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: MYSQL_DATABASE: unittest @@ -28,5 +26,7 @@ services: mongodb: container_name: mongodb image: mongo + ports: + - 27017:27017 logging: driver: none diff --git a/phpunit.xml.dist b/phpunit.xml.dist index bd9d7f5c4..0a10014c2 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -7,42 +7,46 @@ convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" - stopOnFailure="false" - syntaxCheck="false" - verbose="true" -> + stopOnFailure="false"> tests/ - tests/MysqlRelationsTest.php - tests/SchemaTest.php + tests/SchemaTest.php - tests/SeederTest.php + tests/SeederTest.php - tests/CacheTest.php + tests/CacheTest.php - tests/QueryBuilderTest.php - tests/QueryTest.php + tests/QueryBuilderTest.php + tests/QueryTest.php - tests/ModelTest.php - tests/RelationsTest.php + tests/ModelTest.php + tests/RelationsTest.php - tests/RelationsTest.php - tests/EmbeddedRelationsTest.php + tests/RelationsTest.php + tests/EmbeddedRelationsTest.php - tests/RelationsTest.php - tests/MysqlRelationsTest.php + tests/RelationsTest.php - tests/ValidationTest.php + tests/ValidationTest.php + + + + + + + + + diff --git a/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php b/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php index da6159f9e..a825bbc44 100644 --- a/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php +++ b/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php @@ -14,7 +14,11 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository */ protected function getPayload($email, $token) { - return ['email' => $email, 'token' => $this->hasher->make($token), 'created_at' => new UTCDateTime(time() * 1000)]; + return [ + 'email' => $email, + 'token' => $this->hasher->make($token), + 'created_at' => new UTCDateTime(time() * 1000), + ]; } /** @@ -27,7 +31,7 @@ protected function tokenExpired($createdAt) $date = $createdAt->toDateTime(); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); $createdAt = $date->format('Y-m-d H:i:s'); - } elseif (is_array($createdAt) and isset($createdAt['date'])) { + } elseif (is_array($createdAt) && isset($createdAt['date'])) { $date = new DateTime($createdAt['date'], new DateTimeZone(isset($createdAt['timezone']) ? $createdAt['timezone'] : 'UTC')); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); $createdAt = $date->format('Y-m-d H:i:s'); diff --git a/src/Jenssegers/Mongodb/Auth/PasswordBrokerManager.php b/src/Jenssegers/Mongodb/Auth/PasswordBrokerManager.php index 5320ae890..281f8af75 100644 --- a/src/Jenssegers/Mongodb/Auth/PasswordBrokerManager.php +++ b/src/Jenssegers/Mongodb/Auth/PasswordBrokerManager.php @@ -11,14 +11,6 @@ class PasswordBrokerManager extends BasePasswordBrokerManager */ protected function createTokenRepository(array $config) { - $key = $this->app['config']['app.key']; - - if (\Illuminate\Support\Str::startsWith($key, 'base64:')) { - $key = base64_decode(substr($key, 7)); - } - - $connection = isset($config['connection']) ? $config['connection'] : null; - return new DatabaseTokenRepository( $this->app['db']->connection(), $this->app['hash'], diff --git a/src/Jenssegers/Mongodb/Auth/PasswordResetServiceProvider.php b/src/Jenssegers/Mongodb/Auth/PasswordResetServiceProvider.php index ba4e32e62..6e678d2ec 100644 --- a/src/Jenssegers/Mongodb/Auth/PasswordResetServiceProvider.php +++ b/src/Jenssegers/Mongodb/Auth/PasswordResetServiceProvider.php @@ -8,7 +8,6 @@ class PasswordResetServiceProvider extends BasePasswordResetServiceProvider { /** * Register the token repository implementation. - * * @return void */ protected function registerTokenRepository() diff --git a/src/Jenssegers/Mongodb/Collection.php b/src/Jenssegers/Mongodb/Collection.php index 7f5c42b9b..4192edd43 100644 --- a/src/Jenssegers/Mongodb/Collection.php +++ b/src/Jenssegers/Mongodb/Collection.php @@ -10,14 +10,12 @@ class Collection { /** * The connection instance. - * * @var Connection */ protected $connection; /** * The MongoCollection instance.. - * * @var MongoCollection */ protected $collection; @@ -34,9 +32,8 @@ public function __construct(Connection $connection, MongoCollection $collection) /** * Handle dynamic method calls. - * - * @param string $method - * @param array $parameters + * @param string $method + * @param array $parameters * @return mixed */ public function __call($method, $parameters) diff --git a/src/Jenssegers/Mongodb/Connection.php b/src/Jenssegers/Mongodb/Connection.php index 7276155a6..7920ec9f6 100644 --- a/src/Jenssegers/Mongodb/Connection.php +++ b/src/Jenssegers/Mongodb/Connection.php @@ -10,22 +10,19 @@ class Connection extends BaseConnection { /** * The MongoDB database handler. - * * @var \MongoDB\Database */ protected $db; /** * The MongoDB connection handler. - * * @var \MongoDB\Client */ protected $connection; /** * Create a new database connection instance. - * - * @param array $config + * @param array $config */ public function __construct(array $config) { @@ -52,8 +49,7 @@ public function __construct(array $config) /** * Begin a fluent query against a database collection. - * - * @param string $collection + * @param string $collection * @return Query\Builder */ public function collection($collection) @@ -65,19 +61,18 @@ public function collection($collection) /** * Begin a fluent query against a database collection. - * - * @param string $table + * @param string $table + * @param string|null $as * @return Query\Builder */ - public function table($table) + public function table($table, $as = null) { return $this->collection($table); } /** * Get a MongoDB collection. - * - * @param string $name + * @param string $name * @return Collection */ public function getCollection($name) @@ -95,7 +90,6 @@ public function getSchemaBuilder() /** * Get the MongoDB database object. - * * @return \MongoDB\Database */ public function getMongoDB() @@ -105,7 +99,6 @@ public function getMongoDB() /** * return MongoDB object. - * * @return \MongoDB\Client */ public function getMongoClient() @@ -113,12 +106,19 @@ public function getMongoClient() return $this->connection; } + /** + * {@inheritdoc} + */ + public function getDatabaseName() + { + return $this->getMongoDB()->getDatabaseName(); + } + /** * Create a new MongoDB connection. - * - * @param string $dsn - * @param array $config - * @param array $options + * @param string $dsn + * @param array $config + * @param array $options * @return \MongoDB\Client */ protected function createConnection($dsn, array $config, array $options) @@ -151,19 +151,17 @@ public function disconnect() /** * Determine if the given configuration array has a dsn string. - * - * @param array $config + * @param array $config * @return bool */ protected function hasDsnString(array $config) { - return isset($config['dsn']) && ! empty($config['dsn']); + return isset($config['dsn']) && !empty($config['dsn']); } /** * Get the DSN string form configuration. - * - * @param array $config + * @param array $config * @return string */ protected function getDsnString(array $config) @@ -173,8 +171,7 @@ protected function getDsnString(array $config) /** * Get the DSN string for a host / port configuration. - * - * @param array $config + * @param array $config * @return string */ protected function getHostDsn(array $config) @@ -197,8 +194,7 @@ protected function getHostDsn(array $config) /** * Create a DSN string from a configuration. - * - * @param array $config + * @param array $config * @return string */ protected function getDsn(array $config) @@ -250,9 +246,8 @@ protected function getDefaultSchemaGrammar() /** * Dynamically pass methods to the connection. - * - * @param string $method - * @param array $parameters + * @param string $method + * @param array $parameters * @return mixed */ public function __call($method, $parameters) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index 1ee1c41fe..90b58484f 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -13,7 +13,6 @@ class Builder extends EloquentBuilder /** * The methods that should be returned from query builder. - * * @var array */ protected $passthru = [ @@ -44,7 +43,7 @@ public function update(array $values, array $options = []) return 1; } - return $this->query->update($this->addUpdatedAtColumn($values), $options); + return $this->toBase()->update($this->addUpdatedAtColumn($values), $options); } /** @@ -177,6 +176,29 @@ public function raw($expression = null) return $results; } + /** + * Add the "updated at" column to an array of values. + * TODO Remove if https://github.com/laravel/framework/commit/6484744326531829341e1ff886cc9b628b20d73e + * wiil be reverted + * Issue in laravel frawework https://github.com/laravel/framework/issues/27791 + * @param array $values + * @return array + */ + protected function addUpdatedAtColumn(array $values) + { + if (!$this->model->usesTimestamps() || $this->model->getUpdatedAtColumn() === null) { + return $values; + } + + $column = $this->model->getUpdatedAtColumn(); + $values = array_merge( + [$column => $this->model->freshTimestampString()], + $values + ); + + return $values; + } + /** * @return \Illuminate\Database\ConnectionInterface */ diff --git a/src/Jenssegers/Mongodb/Eloquent/EmbedsRelations.php b/src/Jenssegers/Mongodb/Eloquent/EmbedsRelations.php index 307f5e330..caef0e693 100644 --- a/src/Jenssegers/Mongodb/Eloquent/EmbedsRelations.php +++ b/src/Jenssegers/Mongodb/Eloquent/EmbedsRelations.php @@ -10,11 +10,10 @@ trait EmbedsRelations { /** * Define an embedded one-to-many relationship. - * - * @param string $related - * @param string $localKey - * @param string $foreignKey - * @param string $relation + * @param string $related + * @param string $localKey + * @param string $foreignKey + * @param string $relation * @return \Jenssegers\Mongodb\Relations\EmbedsMany */ protected function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null) @@ -22,17 +21,17 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most // of the time this will be what we desire to use for the relationships. - if (is_null($relation)) { + if ($relation === null) { list(, $caller) = debug_backtrace(false); $relation = $caller['function']; } - if (is_null($localKey)) { + if ($localKey === null) { $localKey = $relation; } - if (is_null($foreignKey)) { + if ($foreignKey === null) { $foreignKey = Str::snake(class_basename($this)); } @@ -45,11 +44,10 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r /** * Define an embedded one-to-many relationship. - * - * @param string $related - * @param string $localKey - * @param string $foreignKey - * @param string $relation + * @param string $related + * @param string $localKey + * @param string $foreignKey + * @param string $relation * @return \Jenssegers\Mongodb\Relations\EmbedsOne */ protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) @@ -57,17 +55,17 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most // of the time this will be what we desire to use for the relationships. - if (is_null($relation)) { + if ($relation === null) { list(, $caller) = debug_backtrace(false); $relation = $caller['function']; } - if (is_null($localKey)) { + if ($localKey === null) { $localKey = $relation; } - if (is_null($foreignKey)) { + if ($foreignKey === null) { $foreignKey = Str::snake(class_basename($this)); } diff --git a/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php b/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php index 34b8b5788..bfe9a2b2c 100644 --- a/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php +++ b/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php @@ -16,10 +16,9 @@ trait HybridRelations { /** * Define a one-to-one relationship. - * - * @param string $related - * @param string $foreignKey - * @param string $localKey + * @param string $related + * @param string $foreignKey + * @param string $localKey * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function hasOne($related, $foreignKey = null, $localKey = null) @@ -40,12 +39,11 @@ public function hasOne($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-one relationship. - * - * @param string $related - * @param string $name - * @param string $type - * @param string $id - * @param string $localKey + * @param string $related + * @param string $name + * @param string $type + * @param string $id + * @param string $localKey * @return \Illuminate\Database\Eloquent\Relations\MorphOne */ public function morphOne($related, $name, $type = null, $id = null, $localKey = null) @@ -66,10 +64,9 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey = /** * Define a one-to-many relationship. - * - * @param string $related - * @param string $foreignKey - * @param string $localKey + * @param string $related + * @param string $foreignKey + * @param string $localKey * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function hasMany($related, $foreignKey = null, $localKey = null) @@ -90,12 +87,11 @@ public function hasMany($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-many relationship. - * - * @param string $related - * @param string $name - * @param string $type - * @param string $id - * @param string $localKey + * @param string $related + * @param string $name + * @param string $type + * @param string $id + * @param string $localKey * @return \Illuminate\Database\Eloquent\Relations\MorphMany */ public function morphMany($related, $name, $type = null, $id = null, $localKey = null) @@ -121,11 +117,10 @@ public function morphMany($related, $name, $type = null, $id = null, $localKey = /** * Define an inverse one-to-one or many relationship. - * - * @param string $related - * @param string $foreignKey - * @param string $otherKey - * @param string $relation + * @param string $related + * @param string $foreignKey + * @param string $otherKey + * @param string $relation * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null) @@ -133,7 +128,7 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most // of the time this will be what we desire to use for the relationships. - if (is_null($relation)) { + if ($relation === null) { list($current, $caller) = debug_backtrace(false, 2); $relation = $caller['function']; @@ -147,7 +142,7 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat // If no foreign key was supplied, we can use a backtrace to guess the proper // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. - if (is_null($foreignKey)) { + if ($foreignKey === null) { $foreignKey = Str::snake($relation) . '_id'; } @@ -165,11 +160,10 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat /** * Define a polymorphic, inverse one-to-one or many relationship. - * - * @param string $name - * @param string $type - * @param string $id - * @param string $ownerKey + * @param string $name + * @param string $type + * @param string $id + * @param string $ownerKey * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null) @@ -177,7 +171,7 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // If no name is provided, we will use the backtrace to get the function name // since that is most likely the name of the polymorphic interface. We can // use that to get both the class and foreign key that will be utilized. - if (is_null($name)) { + if ($name === null) { list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $name = Str::snake($caller['function']); @@ -188,7 +182,7 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // If the type value is null it is probably safe to assume we're eager loading // the relationship. When that is the case we will pass in a dummy query as // there are multiple types in the morph and we can't use single queries. - if (is_null($class = $this->$type)) { + if (($class = $this->$type) === null) { return new MorphTo( $this->newQuery(), $this, $id, null, $type, $name ); @@ -197,27 +191,24 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // If we are not eager loading the relationship we will essentially treat this // as a belongs-to style relationship since morph-to extends that class and // we will pass in the appropriate values so that it behaves as expected. - else { - $class = $this->getActualClassNameForMorph($class); + $class = $this->getActualClassNameForMorph($class); - $instance = new $class; + $instance = new $class; - return new MorphTo( - $instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name - ); - } + return new MorphTo( + $instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name + ); } /** * Define a many-to-many relationship. - * - * @param string $related - * @param string $collection - * @param string $foreignKey - * @param string $otherKey - * @param string $parentKey - * @param string $relatedKey - * @param string $relation + * @param string $related + * @param string $collection + * @param string $foreignKey + * @param string $otherKey + * @param string $parentKey + * @param string $relatedKey + * @param string $relation * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function belongsToMany( @@ -232,7 +223,7 @@ public function belongsToMany( // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. - if (is_null($relation)) { + if ($relation === null) { $relation = $this->guessBelongsToManyRelation(); } @@ -261,7 +252,7 @@ public function belongsToMany( // If no table name was provided, we can guess it by concatenating the two // models using underscores in alphabetical order. The two model names // are transformed to snake case from their default CamelCase also. - if (is_null($collection)) { + if ($collection === null) { $collection = $instance->getTable(); } @@ -284,7 +275,6 @@ public function belongsToMany( /** * Get the relationship name of the belongs to many. - * * @return string */ protected function guessBelongsToManyRelation() @@ -303,8 +293,8 @@ public function newEloquentBuilder($query) { if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) { return new Builder($query); - } else { - return new EloquentBuilder($query); } + + return new EloquentBuilder($query); } } diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 3f47df1d9..1ef6412ed 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -4,15 +4,16 @@ use Carbon\Carbon; use DateTime; +use Illuminate\Contracts\Queue\QueueableCollection; +use Illuminate\Contracts\Queue\QueueableEntity; use Illuminate\Database\Eloquent\Model as BaseModel; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Jenssegers\Mongodb\Query\Builder as QueryBuilder; +use MongoDB\BSON\Binary; use MongoDB\BSON\ObjectID; use MongoDB\BSON\UTCDateTime; -use Illuminate\Contracts\Queue\QueueableEntity; -use Illuminate\Contracts\Queue\QueueableCollection; abstract class Model extends BaseModel { @@ -20,29 +21,31 @@ abstract class Model extends BaseModel /** * The collection associated with the model. - * * @var string */ protected $collection; /** * The primary key for the model. - * * @var string */ protected $primaryKey = '_id'; + /** + * The primary key type. + * @var string + */ + protected $keyType = 'string'; + /** * The parent relation instance. - * * @var Relation */ protected $parentRelation; /** * Custom accessor for the model's id. - * - * @param mixed $value + * @param mixed $value * @return mixed */ public function getIdAttribute($value = null) @@ -56,6 +59,8 @@ public function getIdAttribute($value = null) // Convert ObjectID to string. if ($value instanceof ObjectID) { return (string) $value; + } elseif ($value instanceof Binary) { + return (string) $value->getData(); } return $value; @@ -297,6 +302,8 @@ public function attributesToArray() } } else { $value = (string) $value; + } elseif ($value instanceof Binary) { + $value = (string) $value->getData(); } Arr::set($attributes, $key, $value); @@ -328,7 +335,7 @@ public function getObjectIds() /** * @inheritdoc */ - protected function originalIsEquivalent($key, $current) + public function originalIsEquivalent($key, $current) { if (!array_key_exists($key, $this->original)) { return false; @@ -362,8 +369,7 @@ protected function originalIsEquivalent($key, $current) /** * Remove one or more fields. - * - * @param mixed $columns + * @param mixed $columns * @return int */ public function drop($columns) @@ -424,9 +430,8 @@ public function push() /** * Remove one or more values from an array. - * - * @param string $column - * @param mixed $values + * @param string $column + * @param mixed $values * @return mixed */ public function pull($column, $values) @@ -443,10 +448,9 @@ public function pull($column, $values) /** * Append one or more values to the underlying attribute value and sync with original. - * - * @param string $column - * @param array $values - * @param bool $unique + * @param string $column + * @param array $values + * @param bool $unique */ protected function pushAttributeValues($column, array $values, $unique = false) { @@ -551,9 +555,8 @@ public function getAttributeValue($key) /** * Remove one or more values to the underlying attribute value and sync with original. - * - * @param string $column - * @param array $values + * @param string $column + * @param array $values */ protected function pullAttributeValues($column, array $values) { @@ -584,8 +587,7 @@ public function getForeignKey() /** * Set the parent relation. - * - * @param \Illuminate\Database\Eloquent\Relations\Relation $relation + * @param \Illuminate\Database\Eloquent\Relations\Relation $relation */ public function setParentRelation(Relation $relation) { @@ -594,7 +596,6 @@ public function setParentRelation(Relation $relation) /** * Get the parent relation. - * * @return \Illuminate\Database\Eloquent\Relations\Relation */ public function getParentRelation() @@ -630,7 +631,6 @@ protected function removeTableFromKey($key) /** * Get the queueable relationships for the entity. - * * @return array */ public function getQueueableRelations() @@ -644,13 +644,13 @@ public function getQueueableRelations() if ($relation instanceof QueueableCollection) { foreach ($relation->getQueueableRelations() as $collectionValue) { - $relations[] = $key.'.'.$collectionValue; + $relations[] = $key . '.' . $collectionValue; } } if ($relation instanceof QueueableEntity) { foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) { - $relations[] = $key.'.'.$entityValue; + $relations[] = $key . '.' . $entityValue; } } } @@ -660,7 +660,6 @@ public function getQueueableRelations() /** * Get loaded relations for the instance without parent. - * * @return array */ protected function getRelationsWithoutParent() diff --git a/src/Jenssegers/Mongodb/Helpers/QueriesRelationships.php b/src/Jenssegers/Mongodb/Helpers/QueriesRelationships.php index 5fe908208..99798ea4f 100644 --- a/src/Jenssegers/Mongodb/Helpers/QueriesRelationships.php +++ b/src/Jenssegers/Mongodb/Helpers/QueriesRelationships.php @@ -3,6 +3,8 @@ namespace Jenssegers\Mongodb\Helpers; use Closure; +use Exception; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasOneOrMany; @@ -12,13 +14,12 @@ trait QueriesRelationships { /** * Add a relationship count / exists condition to the query. - * - * @param string $relation - * @param string $operator - * @param int $count - * @param string $boolean - * @param \Closure|null $callback - * @return \Illuminate\Database\Eloquent\Builder|static + * @param string $relation + * @param string $operator + * @param int $count + * @param string $boolean + * @param Closure|null $callback + * @return Builder|static */ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) { @@ -74,7 +75,7 @@ protected function isAcrossConnections($relation) * @param string $boolean * @param Closure|null $callback * @return mixed - * @throws \Exception + * @throws Exception */ public function addHybridHas($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) { @@ -97,29 +98,6 @@ public function addHybridHas($relation, $operator = '>=', $count = 1, $boolean = return $this->whereIn($this->getRelatedConstraintKey($relation), $relatedIds, $boolean, $not); } - /** - * Returns key we are constraining this parent model's query with - * @param $relation - * @return string - * @throws \Exception - */ - protected function getRelatedConstraintKey($relation) - { - if ($relation instanceof HasOneOrMany) { - return $this->model->getKeyName(); - } - - if ($relation instanceof BelongsTo) { - return $relation->getForeignKey(); - } - - if ($relation instanceof BelongsToMany && ! $this->isAcrossConnections($relation)) { - return $this->model->getKeyName(); - } - - throw new \Exception(class_basename($relation) . ' is not supported for hybrid query constraints.'); - } - /** * @param $relation * @return string @@ -130,7 +108,7 @@ protected function getHasCompareKey($relation) return $relation->getHasCompareKey(); } - return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKey(); + return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKeyName(); } /** @@ -166,4 +144,27 @@ protected function getConstrainedRelatedIds($relations, $operator, $count) // All related ids. return array_keys($relationCount); } + + /** + * Returns key we are constraining this parent model's query with + * @param $relation + * @return string + * @throws Exception + */ + protected function getRelatedConstraintKey($relation) + { + if ($relation instanceof HasOneOrMany) { + return $this->model->getKeyName(); + } + + if ($relation instanceof BelongsTo) { + return $relation->getForeignKeyName(); + } + + if ($relation instanceof BelongsToMany && !$this->isAcrossConnections($relation)) { + return $this->model->getKeyName(); + } + + throw new Exception(class_basename($relation) . ' is not supported for hybrid query constraints.'); + } } diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 7a1980e4c..1d6d568a9 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -11,6 +11,7 @@ use Illuminate\Support\Str; use Jenssegers\Mongodb\Connection; use MongoCollection; +use MongoDB\BSON\Binary; use MongoDB\BSON\ObjectID; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -19,35 +20,30 @@ class Builder extends BaseBuilder { /** * The database collection. - * * @var MongoCollection */ protected $collection; /** * The column projections. - * * @var array */ public $projections; /** * The cursor timeout value. - * * @var int */ public $timeout; /** * The cursor hint value. - * * @var int */ public $hint; /** * Custom options to add to the query. - * * @var array */ public $options = []; @@ -61,14 +57,12 @@ class Builder extends BaseBuilder /** * Indicate if we are executing a pagination query. - * * @var bool */ public $paginating = false; /** * All of the available clause operators. - * * @var array */ public $operators = [ @@ -116,7 +110,6 @@ class Builder extends BaseBuilder /** * Operator conversion. - * * @var array */ protected $conversion = [ @@ -131,7 +124,6 @@ class Builder extends BaseBuilder /** * Check if we need to return Collections instead of plain arrays (laravel >= 5.3 ) - * * @var boolean */ protected $useCollections; @@ -149,7 +141,6 @@ public function __construct(Connection $connection, Processor $processor) /** * Returns true if Laravel or Lumen >= 5.3 - * * @return bool */ protected function shouldUseCollections() @@ -159,12 +150,13 @@ protected function shouldUseCollections() $version = filter_var(explode(')', $version)[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // lumen return version_compare($version, '5.3', '>='); } + + return true; } /** * Set the projections. - * - * @param array $columns + * @param array $columns * @return $this */ public function project($columns) @@ -176,8 +168,7 @@ public function project($columns) /** * Set the cursor timeout in seconds. - * - * @param int $seconds + * @param int $seconds * @return $this */ public function timeout($seconds) @@ -189,8 +180,7 @@ public function timeout($seconds) /** * Set the cursor hint. - * - * @param mixed $index + * @param mixed $index * @return $this */ public function hint($index) @@ -208,6 +198,16 @@ public function find($id, $columns = []) return $this->where('_id', '=', $this->convertKey($id))->first($columns); } + /** + * @inheritdoc + */ + public function value($column) + { + $result = (array) $this->first([$column]); + + return Arr::get($result, $column); + } + /** * @inheritdoc */ @@ -218,8 +218,7 @@ public function get($columns = []) /** * Execute the query as a fresh "select" statement. - * - * @param array $columns + * @param array $columns * @return array|static[]|Collection */ public function getFresh($columns = []) @@ -227,7 +226,7 @@ public function getFresh($columns = []) // If no columns have been specified for the select statement, we will set them // here to either the passed columns, or the standard default of retrieving // all of the columns on the table using the "wildcard" column character. - if (is_null($this->columns)) { + if ($this->columns === null) { $this->columns = $columns; } @@ -406,7 +405,6 @@ public function getFresh($columns = []) /** * Generate the unique cache key for the current query. - * * @return string */ public function generateCacheKey() @@ -463,7 +461,7 @@ public function aggregate($function, $columns = []) */ public function exists() { - return !is_null($this->first()); + return $this->first() !== null; } /** @@ -500,11 +498,10 @@ public function orderBy($column, $direction = 'asc') /** * Add a "where all" clause to the query. - * - * @param string $column - * @param array $values - * @param string $boolean - * @param bool $not + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not * @return $this */ public function whereAll($column, array $values, $boolean = 'and', $not = false) @@ -574,7 +571,7 @@ public function insertGetId(array $values, $sequence = null) $result = $this->collection->insertOne($values); if (1 == (int) $result->isAcknowledged()) { - if (is_null($sequence)) { + if ($sequence === null) { $sequence = '_id'; } @@ -638,12 +635,6 @@ public function chunkById($count, callable $callback, $column = '_id', $alias = */ public function forPageAfterId($perPage = 15, $lastId = 0, $column = '_id') { - // When using ObjectIDs to paginate, we need to use a hex string as the - // "minimum" ID rather than the integer zero so the '$lt' query works. - if ($column === '_id' && $lastId === 0) { - $lastId = '000000000000000000000000'; - } - return parent::forPageAfterId($perPage, $lastId, $column); } @@ -652,7 +643,7 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = '_id') */ public function pluck($column, $key = null) { - $results = $this->get(is_null($key) ? [$column] : [$column, $key]); + $results = $this->get($key === null ? [$column] : [$column, $key]); // Convert ObjectID's to strings if ($key == '_id') { @@ -674,7 +665,7 @@ public function delete($id = null) // If an ID is passed to the method, we will set the where clause to check // the ID to allow developers to simply and quickly remove a single row // from their database without manually specifying the where clauses. - if (!is_null($id)) { + if ($id !== null) { $this->where('_id', '=', $id); } @@ -690,7 +681,7 @@ public function delete($id = null) /** * @inheritdoc */ - public function from($collection) + public function from($collection, $as = null) { if ($collection) { $this->collection = $this->connection->getCollection($collection); @@ -711,11 +702,10 @@ public function truncate() /** * Get an array with the values of a given column. - * - * @deprecated - * @param string $column - * @param string $key + * @param string $column + * @param string $key * @return array + * @deprecated */ public function lists($column, $key = null) { @@ -730,8 +720,10 @@ public function raw($expression = null) // Execute the closure on the mongodb collection if ($expression instanceof Closure) { return call_user_func($expression, $this->collection); - } // Create an expression for the given value - elseif (!is_null($expression)) { + } + + // Create an expression for the given value + if ($expression !== null) { return new Expression($expression); } @@ -741,7 +733,6 @@ public function raw($expression = null) /** * Append one or more values to an array. - * * @param mixed $column * @param mixed $value * @param bool $unique @@ -768,9 +759,8 @@ public function push($column, $value = null, $unique = false) /** * Remove one or more values from an array. - * - * @param mixed $column - * @param mixed $value + * @param mixed $column + * @param mixed $value * @return int */ public function pull($column, $value = null) @@ -795,8 +785,7 @@ public function pull($column, $value = null) /** * Remove one or more fields. - * - * @param mixed $columns + * @param mixed $columns * @return int */ public function drop($columns) @@ -826,9 +815,8 @@ public function newQuery() /** * Perform an update query. - * - * @param array $query - * @param array $options + * @param array $query + * @param array $options * @return int */ protected function performUpdate($query, array $options = []) @@ -849,8 +837,7 @@ protected function performUpdate($query, array $options = []) /** * Convert a key to ObjectID if needed. - * - * @param mixed $id + * @param mixed $id * @return mixed */ public function convertKey($id) @@ -859,6 +846,10 @@ public function convertKey($id) return new ObjectID($id); } + if (is_string($id) && strlen($id) === 16 && preg_match('~[^\x20-\x7E\t\r\n]~', $id) > 0) { + return new Binary($id, Binary::TYPE_UUID); + } + return $id; } @@ -898,7 +889,6 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' /** * Compile the where array. - * * @return array */ protected function compileWheres() @@ -1020,9 +1010,13 @@ protected function compileWhereBasic(array $where) { extract($where); - // Replace like with a Regex instance. - if ($operator == 'like') { - $operator = '='; + // Replace like or not like with a Regex instance. + if (in_array($operator, ['like', 'not like'])) { + if ($operator === 'not like') { + $operator = 'not'; + } else { + $operator = '='; + } // Convert to regular expression. $regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value)); @@ -1032,7 +1026,7 @@ protected function compileWhereBasic(array $where) $regex = '^' . $regex; } if (!Str::endsWith($value, '%')) { - $regex = $regex . '$'; + $regex .= '$'; } $value = new Regex($regex, 'i'); @@ -1144,14 +1138,14 @@ protected function compileWhereBetween(array $where) ], ], ]; - } else { - return [ - $column => [ - '$gte' => $values[0], - '$lte' => $values[1], - ], - ]; } + + return [ + $column => [ + '$gte' => $values[0], + '$lte' => $values[1], + ], + ]; } /** @@ -1165,8 +1159,7 @@ protected function compileWhereRaw(array $where) /** * Set custom options for the query. - * - * @param array $options + * @param array $options * @return $this */ public function options(array $options) diff --git a/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php b/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php index 5548dd86f..a02639f88 100644 --- a/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php +++ b/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php @@ -9,11 +9,9 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider { /** * Log a failed job into storage. - * - * @param string $connection - * @param string $queue - * @param string $payload - * + * @param string $connection + * @param string $queue + * @param string $payload * @return void */ public function log($connection, $queue, $payload, $exception) @@ -25,7 +23,6 @@ public function log($connection, $queue, $payload, $exception) /** * Get a list of all of the failed jobs. - * * @return object[] */ public function all() @@ -42,8 +39,7 @@ public function all() /** * Get a single failed job. - * - * @param mixed $id + * @param mixed $id * @return object */ public function find($id) @@ -57,8 +53,7 @@ public function find($id) /** * Delete a single failed job from storage. - * - * @param mixed $id + * @param mixed $id * @return bool */ public function forget($id) diff --git a/src/Jenssegers/Mongodb/Queue/MongoConnector.php b/src/Jenssegers/Mongodb/Queue/MongoConnector.php index 839ac027e..91cea8c35 100644 --- a/src/Jenssegers/Mongodb/Queue/MongoConnector.php +++ b/src/Jenssegers/Mongodb/Queue/MongoConnector.php @@ -10,15 +10,13 @@ class MongoConnector implements ConnectorInterface { /** * Database connections. - * * @var \Illuminate\Database\ConnectionResolverInterface */ protected $connections; /** * Create a new connector instance. - * - * @param \Illuminate\Database\ConnectionResolverInterface $connections + * @param \Illuminate\Database\ConnectionResolverInterface $connections */ public function __construct(ConnectionResolverInterface $connections) { @@ -27,8 +25,7 @@ public function __construct(ConnectionResolverInterface $connections) /** * Establish a queue connection. - * - * @param array $config + * @param array $config * @return \Illuminate\Contracts\Queue\Queue */ public function connect(array $config) diff --git a/src/Jenssegers/Mongodb/Queue/MongoJob.php b/src/Jenssegers/Mongodb/Queue/MongoJob.php index f1a61cf46..336515f09 100644 --- a/src/Jenssegers/Mongodb/Queue/MongoJob.php +++ b/src/Jenssegers/Mongodb/Queue/MongoJob.php @@ -8,7 +8,6 @@ class MongoJob extends DatabaseJob { /** * Indicates if the job has been reserved. - * * @return bool */ public function isReserved() diff --git a/src/Jenssegers/Mongodb/Queue/MongoQueue.php b/src/Jenssegers/Mongodb/Queue/MongoQueue.php index e9cd8da9c..44249456a 100644 --- a/src/Jenssegers/Mongodb/Queue/MongoQueue.php +++ b/src/Jenssegers/Mongodb/Queue/MongoQueue.php @@ -11,14 +11,12 @@ class MongoQueue extends DatabaseQueue { /** * The expiration time of a job. - * * @var int|null */ protected $retryAfter = 60; /** * The connection name for the queue. - * * @var string */ protected $connectionName; @@ -39,7 +37,7 @@ public function pop($queue = null) { $queue = $this->getQueue($queue); - if (!is_null($this->retryAfter)) { + if ($this->retryAfter !== null) { $this->releaseJobsThatHaveBeenReservedTooLong($queue); } @@ -52,17 +50,13 @@ public function pop($queue = null) /** * Get the next available job for the queue and mark it as reserved. - * * When using multiple daemon queue listeners to process jobs there * is a possibility that multiple processes can end up reading the * same record before one has flagged it as reserved. - * * This race condition can result in random jobs being run more then * once. To solve this we use findOneAndUpdate to lock the next jobs * record while flagging it as reserved at the same time. - * - * @param string|null $queue - * + * @param string|null $queue * @return \StdClass|null */ protected function getNextAvailableJobAndReserve($queue) @@ -94,8 +88,7 @@ protected function getNextAvailableJobAndReserve($queue) /** * Release the jobs that have been reserved for too long. - * - * @param string $queue + * @param string $queue * @return void */ protected function releaseJobsThatHaveBeenReservedTooLong($queue) @@ -124,9 +117,8 @@ protected function releaseJobsThatHaveBeenReservedTooLong($queue) /** * Release the given job ID from reservation. - * - * @param string $id - * @param int $attempts + * @param string $id + * @param int $attempts * @return void */ protected function releaseJob($id, $attempts) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsTo.php b/src/Jenssegers/Mongodb/Relations/BelongsTo.php index 78b5d63be..b47e856fa 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsTo.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsTo.php @@ -3,12 +3,12 @@ namespace Jenssegers\Mongodb\Relations; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model as EloquentModel; class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo { /** * Get the key for comparing against the parent key in "has" query. - * * @return string */ public function getHasCompareKey() @@ -52,11 +52,21 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, /** * Get the owner key with backwards compatible support. - * * @return string */ public function getOwnerKey() { return property_exists($this, 'ownerKey') ? $this->ownerKey : $this->otherKey; } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php index 73816b049..c57857638 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php @@ -5,6 +5,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany; use Illuminate\Support\Arr; @@ -12,7 +13,6 @@ class BelongsToMany extends EloquentBelongsToMany { /** * Get the key for comparing against the parent key in "has" query. - * * @return string */ public function getHasCompareKey() @@ -38,8 +38,7 @@ protected function hydratePivotRelation(array $models) /** * Set the select clause for the relation query. - * - * @param array $columns + * @param array $columns * @return array */ protected function getSelectColumns(array $columns = ['*']) @@ -67,7 +66,6 @@ public function addConstraints() /** * Set the where clause for the relation query. - * * @return $this */ protected function setWhere() @@ -274,7 +272,6 @@ protected function newPivotQuery() /** * Create a new query builder for the related model. - * * @return \Illuminate\Database\Query\Builder */ public function newRelatedQuery() @@ -284,7 +281,6 @@ public function newRelatedQuery() /** * Get the fully qualified foreign key for the relation. - * * @return string */ public function getForeignKey() @@ -311,10 +307,9 @@ public function getQualifiedRelatedPivotKeyName() /** * Format the sync list so that it is keyed by ID. (Legacy Support) * The original function has been renamed to formatRecordsList since Laravel 5.3 - * - * @deprecated - * @param array $records + * @param array $records * @return array + * @deprecated */ protected function formatSyncList(array $records) { @@ -330,11 +325,21 @@ protected function formatSyncList(array $records) /** * Get the related key with backwards compatible support. - * * @return string */ public function getRelatedKey() { return property_exists($this, 'relatedPivotKey') ? $this->relatedPivotKey : $this->relatedKey; } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/EmbedsMany.php b/src/Jenssegers/Mongodb/Relations/EmbedsMany.php index b0e40893d..df61c2778 100644 --- a/src/Jenssegers/Mongodb/Relations/EmbedsMany.php +++ b/src/Jenssegers/Mongodb/Relations/EmbedsMany.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use MongoDB\BSON\ObjectID; @@ -32,8 +33,7 @@ public function getResults() /** * Save a new model and attach it to the parent model. - * - * @param Model $model + * @param Model $model * @return Model|bool */ public function performInsert(Model $model) @@ -62,8 +62,7 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. - * - * @param Model $model + * @param Model $model * @return Model|bool */ public function performUpdate(Model $model) @@ -94,8 +93,7 @@ public function performUpdate(Model $model) /** * Delete an existing model and detach it from the parent model. - * - * @param Model $model + * @param Model $model * @return int */ public function performDelete(Model $model) @@ -121,23 +119,21 @@ public function performDelete(Model $model) /** * Associate the model instance to the given parent, without saving it to the database. - * - * @param Model $model + * @param Model $model * @return Model */ public function associate(Model $model) { if (!$this->contains($model)) { return $this->associateNew($model); - } else { - return $this->associateExisting($model); } + + return $this->associateExisting($model); } /** * Dissociate the model instance from the given parent, without saving it to the database. - * - * @param mixed $ids + * @param mixed $ids * @return int */ public function dissociate($ids = []) @@ -165,8 +161,7 @@ public function dissociate($ids = []) /** * Destroy the embedded models for the given IDs. - * - * @param mixed $ids + * @param mixed $ids * @return int */ public function destroy($ids = []) @@ -190,7 +185,6 @@ public function destroy($ids = []) /** * Delete all embedded models. - * * @return int */ public function delete() @@ -207,8 +201,7 @@ public function delete() /** * Destroy alias. - * - * @param mixed $ids + * @param mixed $ids * @return int */ public function detach($ids = []) @@ -218,8 +211,7 @@ public function detach($ids = []) /** * Save alias. - * - * @param Model $model + * @param Model $model * @return Model */ public function attach(Model $model) @@ -229,14 +221,13 @@ public function attach(Model $model) /** * Associate a new model instance to the given parent, without saving it to the database. - * - * @param Model $model + * @param Model $model * @return Model */ protected function associateNew($model) { // Create a new key if needed. - if (!$model->getAttribute('_id')) { + if ($model->getKeyName() === '_id' && !$model->getAttribute('_id')) { $model->setAttribute('_id', new ObjectID); } @@ -250,8 +241,7 @@ protected function associateNew($model) /** * Associate an existing model instance to the given parent, without saving it to the database. - * - * @param Model $model + * @param Model $model * @return Model */ protected function associateExisting($model) @@ -276,8 +266,7 @@ protected function associateExisting($model) /** * Get a paginator for the "select" statement. - * - * @param int $perPage + * @param int $perPage * @return \Illuminate\Pagination\AbstractPaginator */ public function paginate($perPage = null) @@ -328,4 +317,15 @@ public function __call($method, $parameters) return parent::__call($method, $parameters); } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/EmbedsOne.php b/src/Jenssegers/Mongodb/Relations/EmbedsOne.php index 2efbfe1df..a0e713bc1 100644 --- a/src/Jenssegers/Mongodb/Relations/EmbedsOne.php +++ b/src/Jenssegers/Mongodb/Relations/EmbedsOne.php @@ -3,6 +3,7 @@ namespace Jenssegers\Mongodb\Relations; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Model as EloquentModel; use MongoDB\BSON\ObjectID; class EmbedsOne extends EmbedsOneOrMany @@ -29,8 +30,7 @@ public function getResults() /** * Save a new model and attach it to the parent model. - * - * @param Model $model + * @param Model $model * @return Model|bool */ public function performInsert(Model $model) @@ -58,8 +58,7 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. - * - * @param Model $model + * @param Model $model * @return Model|bool */ public function performUpdate(Model $model) @@ -84,7 +83,6 @@ public function performUpdate(Model $model) /** * Delete an existing model and detach it from the parent model. - * * @return int */ public function performDelete() @@ -108,8 +106,7 @@ public function performDelete() /** * Attach the model to its parent. - * - * @param Model $model + * @param Model $model * @return Model */ public function associate(Model $model) @@ -119,7 +116,6 @@ public function associate(Model $model) /** * Detach the model from its parent. - * * @return Model */ public function dissociate() @@ -129,11 +125,21 @@ public function dissociate() /** * Delete all embedded models. - * * @return int */ public function delete() { return $this->performDelete(); } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php b/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php index a8f90544d..5a7f636e7 100644 --- a/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php +++ b/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\Relation; use Jenssegers\Mongodb\Eloquent\Model; @@ -11,34 +12,30 @@ abstract class EmbedsOneOrMany extends Relation { /** * The local key of the parent model. - * * @var string */ protected $localKey; /** * The foreign key of the parent model. - * * @var string */ protected $foreignKey; /** * The "name" of the relationship. - * * @var string */ protected $relation; /** * Create a new embeds many relationship instance. - * - * @param Builder $query - * @param Model $parent - * @param Model $related - * @param string $localKey - * @param string $foreignKey - * @param string $relation + * @param Builder $query + * @param Model $parent + * @param Model $related + * @param string $localKey + * @param string $foreignKey + * @param string $relation */ public function __construct(Builder $query, Model $parent, Model $related, $localKey, $foreignKey, $relation) { @@ -93,9 +90,7 @@ public function match(array $models, Collection $results, $relation) /** * Shorthand to get the results of the relationship. - * - * @param array $columns - * + * @param array $columns * @return Collection */ public function get($columns = ['*']) @@ -105,7 +100,6 @@ public function get($columns = ['*']) /** * Get the number of embedded models. - * * @return int */ public function count() @@ -115,8 +109,7 @@ public function count() /** * Attach a model instance to the parent model. - * - * @param Model $model + * @param Model $model * @return Model|bool */ public function save(Model $model) @@ -128,8 +121,7 @@ public function save(Model $model) /** * Attach a collection of models to the parent instance. - * - * @param Collection|array $models + * @param Collection|array $models * @return Collection|array */ public function saveMany($models) @@ -143,8 +135,7 @@ public function saveMany($models) /** * Create a new instance of the related model. - * - * @param array $attributes + * @param array $attributes * @return Model */ public function create(array $attributes = []) @@ -163,8 +154,7 @@ public function create(array $attributes = []) /** * Create an array of new instances of the related model. - * - * @param array $records + * @param array $records * @return array */ public function createMany(array $records) @@ -180,8 +170,7 @@ public function createMany(array $records) /** * Transform single ID, single Model or array of Models into an array of IDs. - * - * @param mixed $ids + * @param mixed $ids * @return array */ protected function getIdsArrayFrom($ids) @@ -235,8 +224,7 @@ protected function setEmbedded($records) /** * Get the foreign key value for the relation. - * - * @param mixed $id + * @param mixed $id * @return mixed */ protected function getForeignKeyValue($id) @@ -251,8 +239,7 @@ protected function getForeignKeyValue($id) /** * Convert an array of records to a Collection. - * - * @param array $records + * @param array $records * @return Collection */ protected function toCollection(array $records = []) @@ -272,13 +259,12 @@ protected function toCollection(array $records = []) /** * Create a related model instanced. - * - * @param array $attributes + * @param array $attributes * @return Model */ protected function toModel($attributes = []) { - if (is_null($attributes)) { + if ($attributes === null) { return; } @@ -301,7 +287,6 @@ protected function toModel($attributes = []) /** * Get the relation instance of the parent. - * * @return Relation */ protected function getParentRelation() @@ -331,7 +316,6 @@ public function getBaseQuery() /** * Check if this relation is nested in another relation. - * * @return bool */ protected function isNested() @@ -341,8 +325,7 @@ protected function isNested() /** * Get the fully qualified local key name. - * - * @param string $glue + * @param string $glue * @return string */ protected function getPathHierarchy($glue = '.') @@ -368,7 +351,6 @@ public function getQualifiedParentKeyName() /** * Get the primary key value of the parent. - * * @return string */ protected function getParentKey() @@ -378,7 +360,6 @@ protected function getParentKey() /** * Return update values - * * @param $array * @param string $prepend * @return array @@ -388,7 +369,7 @@ public static function getUpdateValues($array, $prepend = '') $results = []; foreach ($array as $key => $value) { - $results[$prepend.$key] = $value; + $results[$prepend . $key] = $value; } return $results; @@ -396,11 +377,21 @@ public static function getUpdateValues($array, $prepend = '') /** * Get the foreign key for the relationship. - * * @return string */ public function getQualifiedForeignKeyName() { return $this->foreignKey; } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/HasMany.php b/src/Jenssegers/Mongodb/Relations/HasMany.php index 47e60e533..b10426635 100644 --- a/src/Jenssegers/Mongodb/Relations/HasMany.php +++ b/src/Jenssegers/Mongodb/Relations/HasMany.php @@ -3,13 +3,13 @@ namespace Jenssegers\Mongodb\Relations; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany; class HasMany extends EloquentHasMany { /** * Get the plain foreign key. - * * @return string */ public function getForeignKeyName() @@ -19,7 +19,6 @@ public function getForeignKeyName() /** * Get the plain foreign key. - * * @return string */ public function getPlainForeignKey() @@ -29,7 +28,6 @@ public function getPlainForeignKey() /** * Get the key for comparing against the parent key in "has" query. - * * @return string */ public function getHasCompareKey() @@ -49,9 +47,8 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, /** * Add the constraints for a relationship count query. - * - * @param Builder $query - * @param Builder $parent + * @param Builder $query + * @param Builder $parent * @return Builder */ public function getRelationCountQuery(Builder $query, Builder $parent) @@ -63,10 +60,9 @@ public function getRelationCountQuery(Builder $query, Builder $parent) /** * Add the constraints for a relationship query. - * - * @param Builder $query - * @param Builder $parent - * @param array|mixed $columns + * @param Builder $query + * @param Builder $parent + * @param array|mixed $columns * @return Builder */ public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) @@ -77,4 +73,15 @@ public function getRelationQuery(Builder $query, Builder $parent, $columns = ['* return $query->where($this->getHasCompareKey(), 'exists', true); } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/HasOne.php b/src/Jenssegers/Mongodb/Relations/HasOne.php index c91a65787..91741c297 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOne.php +++ b/src/Jenssegers/Mongodb/Relations/HasOne.php @@ -3,13 +3,13 @@ namespace Jenssegers\Mongodb\Relations; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne; class HasOne extends EloquentHasOne { /** * Get the key for comparing against the parent key in "has" query. - * * @return string */ public function getForeignKeyName() @@ -19,7 +19,6 @@ public function getForeignKeyName() /** * Get the key for comparing against the parent key in "has" query. - * * @return string */ public function getHasCompareKey() @@ -29,7 +28,6 @@ public function getHasCompareKey() /** * Get the plain foreign key. - * * @return string */ public function getPlainForeignKey() @@ -49,9 +47,8 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, /** * Add the constraints for a relationship count query. - * - * @param Builder $query - * @param Builder $parent + * @param Builder $query + * @param Builder $parent * @return Builder */ public function getRelationCountQuery(Builder $query, Builder $parent) @@ -63,10 +60,9 @@ public function getRelationCountQuery(Builder $query, Builder $parent) /** * Add the constraints for a relationship query. - * - * @param Builder $query - * @param Builder $parent - * @param array|mixed $columns + * @param Builder $query + * @param Builder $parent + * @param array|mixed $columns * @return Builder */ public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*']) @@ -77,4 +73,15 @@ public function getRelationQuery(Builder $query, Builder $parent, $columns = ['* return $query->where($this->getForeignKeyName(), 'exists', true); } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Relations/MorphTo.php b/src/Jenssegers/Mongodb/Relations/MorphTo.php index 08344f526..704c4722c 100644 --- a/src/Jenssegers/Mongodb/Relations/MorphTo.php +++ b/src/Jenssegers/Mongodb/Relations/MorphTo.php @@ -2,6 +2,7 @@ namespace Jenssegers\Mongodb\Relations; +use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo; class MorphTo extends EloquentMorphTo @@ -35,11 +36,21 @@ protected function getResultsByType($type) /** * Get the owner key with backwards compatible support. - * * @return string */ public function getOwnerKey() { return property_exists($this, 'ownerKey') ? $this->ownerKey : $this->otherKey; } + + /** + * Get the name of the "where in" method for eager loading. + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @return string + */ + protected function whereInMethod(EloquentModel $model, $key) + { + return 'whereIn'; + } } diff --git a/src/Jenssegers/Mongodb/Schema/Blueprint.php b/src/Jenssegers/Mongodb/Schema/Blueprint.php index 0c01c96aa..063d5e9e9 100644 --- a/src/Jenssegers/Mongodb/Schema/Blueprint.php +++ b/src/Jenssegers/Mongodb/Schema/Blueprint.php @@ -8,21 +8,18 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint { /** * The MongoConnection object for this blueprint. - * * @var \Jenssegers\Mongodb\Connection */ protected $connection; /** * The MongoCollection object for this blueprint. - * * @var \Jenssegers\Mongodb\Collection|\MongoDB\Collection */ protected $collection; /** * Fluent columns. - * * @var array */ protected $columns = []; @@ -77,6 +74,54 @@ public function primary($columns = null, $name = null, $algorithm = null, $optio * @inheritdoc */ public function dropIndex($indexOrColumns = null) + { + $indexOrColumns = $this->transformColumns($indexOrColumns); + + $this->collection->dropIndex($indexOrColumns); + + return $this; + } + + /** + * Indicate that the given index should be dropped, but do not fail if it didn't exist. + * + * @param string|array $indexOrColumns + * @return Blueprint + */ + public function dropIndexIfExists($indexOrColumns = null) + { + if ($this->hasIndex($indexOrColumns)) { + $this->dropIndex($indexOrColumns); + } + return $this; + } + + /** + * Check whether the given index exists. + * + * @param string|array $indexOrColumns + * @return bool + */ + public function hasIndex($indexOrColumns = null) + { + $indexOrColumns = $this->transformColumns($indexOrColumns); + foreach ($this->collection->listIndexes() as $index) { + if (is_array($indexOrColumns) && in_array($index->getName(), $indexOrColumns)) { + return true; + } + + if (is_string($indexOrColumns) && $index->getName() == $indexOrColumns) { + return true; + } + } + return false; + } + + /** + * @param string|array $indexOrColumns + * @return string + */ + protected function transformColumns($indexOrColumns) { if (is_array($indexOrColumns)) { $indexOrColumns = $this->fluent($indexOrColumns); @@ -88,12 +133,9 @@ public function dropIndex($indexOrColumns = null) $transform[$column] = $column . '_1'; } - $indexOrColumns = join('_', $transform); + $indexOrColumns = implode('_', $transform); } - - $this->collection->dropIndex($indexOrColumns); - - return $this; + return $indexOrColumns; } /** @@ -112,8 +154,7 @@ public function unique($columns = null, $name = null, $algorithm = null, $option /** * Specify a non blocking index for the collection. - * - * @param string|array $columns + * @param string|array $columns * @return Blueprint */ public function background($columns = null) @@ -127,9 +168,8 @@ public function background($columns = null) /** * Specify a sparse index for the collection. - * - * @param string|array $columns - * @param array $options + * @param string|array $columns + * @param array $options * @return Blueprint */ public function sparse($columns = null, $options = []) @@ -145,10 +185,9 @@ public function sparse($columns = null, $options = []) /** * Specify a geospatial index for the collection. - * - * @param string|array $columns - * @param string $index - * @param array $options + * @param string|array $columns + * @param string $index + * @param array $options * @return Blueprint */ public function geospatial($columns = null, $index = '2d', $options = []) @@ -171,9 +210,8 @@ public function geospatial($columns = null, $index = '2d', $options = []) /** * Specify the number of seconds after wich a document should be considered expired based, * on the given single-field index containing a date. - * - * @param string|array $columns - * @param int $seconds + * @param string|array $columns + * @param int $seconds * @return Blueprint */ public function expire($columns, $seconds) @@ -218,9 +256,8 @@ public function addColumn($type, $name, array $parameters = []) /** * Specify a sparse and unique index for the collection. - * - * @param string|array $columns - * @param array $options + * @param string|array $columns + * @param array $options * @return Blueprint */ public function sparse_and_unique($columns = null, $options = []) @@ -237,13 +274,12 @@ public function sparse_and_unique($columns = null, $options = []) /** * Allow fluent columns. - * - * @param string|array $columns + * @param string|array $columns * @return string|array */ protected function fluent($columns = null) { - if (is_null($columns)) { + if ($columns === null) { return $this->columns; } elseif (is_string($columns)) { return $this->columns = [$columns]; @@ -254,7 +290,6 @@ protected function fluent($columns = null) /** * Allows the use of unsupported schema methods. - * * @param $method * @param $args * @return Blueprint diff --git a/src/Jenssegers/Mongodb/Schema/Builder.php b/src/Jenssegers/Mongodb/Schema/Builder.php index 799fe8e80..1bca6c02e 100644 --- a/src/Jenssegers/Mongodb/Schema/Builder.php +++ b/src/Jenssegers/Mongodb/Schema/Builder.php @@ -33,8 +33,7 @@ public function hasColumns($table, array $columns) /** * Determine if the given collection exists. - * - * @param string $collection + * @param string $collection * @return bool */ public function hasCollection($collection) @@ -60,9 +59,8 @@ public function hasTable($collection) /** * Modify a collection on the schema. - * - * @param string $collection - * @param Closure $callback + * @param string $collection + * @param Closure $callback * @return bool */ public function collection($collection, Closure $callback) @@ -85,11 +83,11 @@ public function table($collection, Closure $callback) /** * @inheritdoc */ - public function create($collection, Closure $callback = null) + public function create($collection, Closure $callback = null, array $options = []) { $blueprint = $this->createBlueprint($collection); - $blueprint->create(); + $blueprint->create($options); if ($callback) { $callback($blueprint); @@ -138,7 +136,6 @@ protected function createBlueprint($collection, Closure $callback = null) /** * Get all of the collections names for the database. - * * @return array */ protected function getAllCollections() diff --git a/src/Jenssegers/Mongodb/Validation/DatabasePresenceVerifier.php b/src/Jenssegers/Mongodb/Validation/DatabasePresenceVerifier.php index 75722a8cc..a7d57a89b 100644 --- a/src/Jenssegers/Mongodb/Validation/DatabasePresenceVerifier.php +++ b/src/Jenssegers/Mongodb/Validation/DatabasePresenceVerifier.php @@ -6,20 +6,19 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe { /** * Count the number of objects in a collection having the given value. - * - * @param string $collection - * @param string $column - * @param string $value - * @param int $excludeId - * @param string $idColumn - * @param array $extra + * @param string $collection + * @param string $column + * @param string $value + * @param int $excludeId + * @param string $idColumn + * @param array $extra * @return int */ public function getCount($collection, $column, $value, $excludeId = null, $idColumn = null, array $extra = []) { $query = $this->table($collection)->where($column, 'regex', "/$value/i"); - if (!is_null($excludeId) && $excludeId != 'NULL') { + if ($excludeId !== null && $excludeId != 'NULL') { $query->where($idColumn ?: 'id', '<>', $excludeId); } @@ -32,11 +31,10 @@ public function getCount($collection, $column, $value, $excludeId = null, $idCol /** * Count the number of objects in a collection with the given values. - * - * @param string $collection - * @param string $column - * @param array $values - * @param array $extra + * @param string $collection + * @param string $column + * @param array $values + * @param array $extra * @return int */ public function getMultiCount($collection, $column, array $values, array $extra = []) diff --git a/tests/AuthTest.php b/tests/AuthTest.php index 2b671fdd5..2628fa626 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -2,11 +2,13 @@ use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Foundation\Application; +use MongoDB\BSON\UTCDateTime; class AuthTest extends TestCase { - public function tearDown() + public function tearDown(): void { + parent::setUp(); User::truncate(); DB::collection('password_reminders')->truncate(); } @@ -14,8 +16,8 @@ public function tearDown() public function testAuthAttempt() { $user = User::create([ - 'name' => 'John Doe', - 'email' => 'john@doe.com', + 'name' => 'John Doe', + 'email' => 'john@doe.com', 'password' => Hash::make('foobar'), ]); @@ -36,8 +38,8 @@ public function testRemindOld() $broker = new PasswordBroker($tokens, $users, $mailer, ''); $user = User::create([ - 'name' => 'John Doe', - 'email' => 'john@doe.com', + 'name' => 'John Doe', + 'email' => 'john@doe.com', 'password' => Hash::make('foobar'), ]); @@ -48,13 +50,13 @@ public function testRemindOld() $reminder = DB::collection('password_resets')->first(); $this->assertEquals('john@doe.com', $reminder['email']); $this->assertNotNull($reminder['token']); - $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $reminder['created_at']); + $this->assertInstanceOf(UTCDateTime::class, $reminder['created_at']); $credentials = [ - 'email' => 'john@doe.com', - 'password' => 'foobar', + 'email' => 'john@doe.com', + 'password' => 'foobar', 'password_confirmation' => 'foobar', - 'token' => $reminder['token'], + 'token' => $reminder['token'], ]; $response = $broker->reset($credentials, function ($user, $password) { diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index f7b37bbac..ab0b29b21 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -1,9 +1,10 @@ assertInstanceOf('Jenssegers\Mongodb\Connection', $connection); + $this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $connection); } public function testReconnect() @@ -23,28 +26,28 @@ public function testReconnect() public function testDb() { $connection = DB::connection('mongodb'); - $this->assertInstanceOf('MongoDB\Database', $connection->getMongoDB()); + $this->assertInstanceOf(\MongoDB\Database::class, $connection->getMongoDB()); $connection = DB::connection('mongodb'); - $this->assertInstanceOf('MongoDB\Client', $connection->getMongoClient()); + $this->assertInstanceOf(\MongoDB\Client::class, $connection->getMongoClient()); } public function testCollection() { $collection = DB::connection('mongodb')->getCollection('unittest'); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf(Jenssegers\Mongodb\Collection::class, $collection); $collection = DB::connection('mongodb')->collection('unittests'); - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); + $this->assertInstanceOf(Jenssegers\Mongodb\Query\Builder::class, $collection); $collection = DB::connection('mongodb')->table('unittests'); - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); + $this->assertInstanceOf(Jenssegers\Mongodb\Query\Builder::class, $collection); } // public function testDynamic() // { // $dbs = DB::connection('mongodb')->listCollections(); - // $this->assertInternalType('array', $dbs); + // $this->assertIsArray($dbs); // } // public function testMultipleConnections() @@ -87,7 +90,7 @@ public function testQueryLog() public function testSchemaBuilder() { $schema = DB::connection('mongodb')->getSchemaBuilder(); - $this->assertInstanceOf('Jenssegers\Mongodb\Schema\Builder', $schema); + $this->assertInstanceOf(\Jenssegers\Mongodb\Schema\Builder::class, $schema); } public function testDriverName() diff --git a/tests/DsnTest.php b/tests/DsnTest.php index 08fa0a8aa..2eed354f4 100644 --- a/tests/DsnTest.php +++ b/tests/DsnTest.php @@ -1,4 +1,5 @@ 'John Doe']); $address = new Address(['city' => 'London']); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($address), $address); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.creating: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . get_class($address), $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address); $address = $user->addresses()->save($address); $address->unsetEventDispatcher(); $this->assertNotNull($user->addresses); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $user->addresses); + $this->assertInstanceOf(\Illuminate\Database\Eloquent\Collection::class, $user->addresses); $this->assertEquals(['London'], $user->addresses->pluck('city')->all()); - $this->assertInstanceOf('DateTime', $address->created_at); - $this->assertInstanceOf('DateTime', $address->updated_at); + $this->assertInstanceOf(DateTime::class, $address->created_at); + $this->assertInstanceOf(DateTime::class, $address->updated_at); $this->assertNotNull($address->_id); - $this->assertInternalType('string', $address->_id); + $this->assertIsString($address->_id); $raw = $address->getAttributes(); - $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['_id']); $address = $user->addresses()->save(new Address(['city' => 'Paris'])); $user = User::find($user->_id); $this->assertEquals(['London', 'Paris'], $user->addresses->pluck('city')->all()); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.updated: ' . get_class($address), $address); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.updating: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . get_class($address), $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address); $address->city = 'New York'; $user->addresses()->save($address); @@ -68,9 +85,9 @@ public function testEmbedsManySave() $address = $user->addresses->first(); $this->assertEquals('London', $address->city); - $this->assertInstanceOf('DateTime', $address->created_at); - $this->assertInstanceOf('DateTime', $address->updated_at); - $this->assertInstanceOf('User', $address->user); + $this->assertInstanceOf(DateTime::class, $address->created_at); + $this->assertInstanceOf(DateTime::class, $address->updated_at); + $this->assertInstanceOf(User::class, $address->user); $this->assertEmpty($address->relationsToArray()); // prevent infinite loop $user = User::find($user->_id); @@ -91,19 +108,19 @@ public function testEmbedsManySave() // $user = User::create(['name' => 'John Doe']); // $address = new Address(['city' => 'London']); - // $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); + // $address->setEventDispatcher($events = Mockery::mock(\Illuminate\Events\Dispatcher::class)); // $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); // $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(true); - // $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($address), $address); - // $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + // $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . get_class($address), $address); + // $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address); // $address->save(); - // $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); + // $address->setEventDispatcher($events = Mockery::mock(\Illuminate\Events\Dispatcher::class)); // $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); // $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(true); - // $events->shouldReceive('fire')->once()->with('eloquent.updated: ' . get_class($address), $address); - // $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + // $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . get_class($address), $address); + // $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address); // $address->city = 'Paris'; // $address->save(); @@ -175,29 +192,29 @@ public function testEmbedsManyCreate() { $user = User::create([]); $address = $user->addresses()->create(['city' => 'Bruxelles']); - $this->assertInstanceOf('Address', $address); - $this->assertInternalType('string', $address->_id); + $this->assertInstanceOf(Address::class, $address); + $this->assertIsString($address->_id); $this->assertEquals(['Bruxelles'], $user->addresses->pluck('city')->all()); $raw = $address->getAttributes(); - $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['_id']); $freshUser = User::find($user->id); $this->assertEquals(['Bruxelles'], $freshUser->addresses->pluck('city')->all()); $user = User::create([]); $address = $user->addresses()->create(['_id' => '', 'city' => 'Bruxelles']); - $this->assertInternalType('string', $address->_id); + $this->assertIsString($address->_id); $raw = $address->getAttributes(); - $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['_id']); } public function testEmbedsManyCreateMany() { $user = User::create([]); list($bruxelles, $paris) = $user->addresses()->createMany([['city' => 'Bruxelles'], ['city' => 'Paris']]); - $this->assertInstanceOf('Address', $bruxelles); + $this->assertInstanceOf(Address::class, $bruxelles); $this->assertEquals('Bruxelles', $bruxelles->city); $this->assertEquals(['Bruxelles', 'Paris'], $user->addresses->pluck('city')->all()); @@ -208,14 +225,23 @@ public function testEmbedsManyCreateMany() public function testEmbedsManyDestroy() { $user = User::create(['name' => 'John Doe']); - $user->addresses()->saveMany([new Address(['city' => 'London']), new Address(['city' => 'Bristol']), new Address(['city' => 'Bruxelles'])]); + $user->addresses()->saveMany([ + new Address(['city' => 'London']), + new Address(['city' => 'Bristol']), + new Address(['city' => 'Bruxelles']), + ]); $address = $user->addresses->first(); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::type('Address'))->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.deleted: ' . get_class($address), Mockery::type('Address')); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.deleting: ' . get_class($address), Mockery::type(Address::class)) + ->andReturn(true); + $events->shouldReceive('dispatch') + ->once() + ->with('eloquent.deleted: ' . get_class($address), Mockery::type(Address::class)); $user->addresses()->destroy($address->_id); $this->assertEquals(['Bristol', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -239,7 +265,11 @@ public function testEmbedsManyDestroy() $freshUser = User::find($user->id); $this->assertEquals([], $freshUser->addresses->pluck('city')->all()); - list($london, $bristol, $bruxelles) = $user->addresses()->saveMany([new Address(['city' => 'London']), new Address(['city' => 'Bristol']), new Address(['city' => 'Bruxelles'])]); + list($london, $bristol, $bruxelles) = $user->addresses()->saveMany([ + new Address(['city' => 'London']), + new Address(['city' => 'Bristol']), + new Address(['city' => 'Bruxelles']), + ]); $user->addresses()->destroy([$london, $bruxelles]); $this->assertEquals(['Bristol'], $user->addresses->pluck('city')->all()); } @@ -247,14 +277,23 @@ public function testEmbedsManyDestroy() public function testEmbedsManyDelete() { $user = User::create(['name' => 'John Doe']); - $user->addresses()->saveMany([new Address(['city' => 'London']), new Address(['city' => 'Bristol']), new Address(['city' => 'Bruxelles'])]); + $user->addresses()->saveMany([ + new Address(['city' => 'London']), + new Address(['city' => 'Bristol']), + new Address(['city' => 'Bruxelles']), + ]); $address = $user->addresses->first(); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::type('Address'))->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.deleted: ' . get_class($address), Mockery::type('Address')); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.deleting: ' . get_class($address), Mockery::type(Address::class)) + ->andReturn(true); + $events->shouldReceive('dispatch') + ->once() + ->with('eloquent.deleted: ' . get_class($address), Mockery::type(Address::class)); $address->delete(); @@ -300,10 +339,16 @@ public function testEmbedsManyCreatingEventReturnsFalse() $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(false); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.creating: ' . get_class($address), $address) + ->andReturn(false); $this->assertFalse($user->addresses()->save($address)); $address->unsetEventDispatcher(); @@ -315,9 +360,12 @@ public function testEmbedsManySavingEventReturnsFalse() $address = new Address(['city' => 'Paris']); $address->exists = true; - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(false); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($address), $address) + ->andReturn(false); $this->assertFalse($user->addresses()->save($address)); $address->unsetEventDispatcher(); @@ -329,10 +377,16 @@ public function testEmbedsManyUpdatingEventReturnsFalse() $address = new Address(['city' => 'New York']); $user->addresses()->save($address); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(false); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($address), $address) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.updating: ' . get_class($address), $address) + ->andReturn(false); $address->city = 'Warsaw'; @@ -347,9 +401,12 @@ public function testEmbedsManyDeletingEventReturnsFalse() $address = $user->addresses->first(); - $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::mustBe($address))->andReturn(false); + $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($address), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.deleting: ' . get_class($address), Mockery::mustBe($address)) + ->andReturn(false); $this->assertEquals(0, $user->addresses()->destroy($address)); $this->assertEquals(['New York'], $user->addresses->pluck('city')->all()); @@ -387,14 +444,14 @@ public function testEmbedsManyEagerLoading() $relations = $user->getRelations(); $this->assertArrayNotHasKey('addresses', $relations); $this->assertArrayHasKey('addresses', $user->toArray()); - $this->assertInternalType('array', $user->toArray()['addresses']); + $this->assertIsArray($user->toArray()['addresses']); $user = User::with('addresses')->get()->first(); $relations = $user->getRelations(); $this->assertArrayHasKey('addresses', $relations); $this->assertEquals(2, $relations['addresses']->count()); $this->assertArrayHasKey('addresses', $user->toArray()); - $this->assertInternalType('array', $user->toArray()['addresses']); + $this->assertIsArray($user->toArray()['addresses']); } public function testEmbedsManyDeleteAll() @@ -424,22 +481,52 @@ public function testEmbedsManyDeleteAll() public function testEmbedsManyCollectionMethods() { $user = User::create(['name' => 'John Doe']); - $user->addresses()->save(new Address(['city' => 'Paris', 'country' => 'France', 'visited' => 4, 'created_at' => new DateTime('3 days ago')])); - $user->addresses()->save(new Address(['city' => 'Bruges', 'country' => 'Belgium', 'visited' => 7, 'created_at' => new DateTime('5 days ago')])); - $user->addresses()->save(new Address(['city' => 'Brussels', 'country' => 'Belgium', 'visited' => 2, 'created_at' => new DateTime('4 days ago')])); - $user->addresses()->save(new Address(['city' => 'Ghent', 'country' => 'Belgium', 'visited' => 13, 'created_at' => new DateTime('2 days ago')])); + $user->addresses()->save(new Address([ + 'city' => 'Paris', + 'country' => 'France', + 'visited' => 4, + 'created_at' => new DateTime('3 days ago'), + ])); + $user->addresses()->save(new Address([ + 'city' => 'Bruges', + 'country' => 'Belgium', + 'visited' => 7, + 'created_at' => new DateTime('5 days ago'), + ])); + $user->addresses()->save(new Address([ + 'city' => 'Brussels', + 'country' => 'Belgium', + 'visited' => 2, + 'created_at' => new DateTime('4 days ago'), + ])); + $user->addresses()->save(new Address([ + 'city' => 'Ghent', + 'country' => 'Belgium', + 'visited' => 13, + 'created_at' => new DateTime('2 days ago'), + ])); $this->assertEquals(['Paris', 'Bruges', 'Brussels', 'Ghent'], $user->addresses()->pluck('city')->all()); - $this->assertEquals(['Bruges', 'Brussels', 'Ghent', 'Paris'], $user->addresses()->sortBy('city')->pluck('city')->all()); + $this->assertEquals(['Bruges', 'Brussels', 'Ghent', 'Paris'], $user->addresses() + ->sortBy('city') + ->pluck('city') + ->all()); $this->assertEquals([], $user->addresses()->where('city', 'New York')->pluck('city')->all()); - $this->assertEquals(['Bruges', 'Brussels', 'Ghent'], $user->addresses()->where('country', 'Belgium')->pluck('city')->all()); - $this->assertEquals(['Bruges', 'Brussels', 'Ghent'], $user->addresses()->where('country', 'Belgium')->sortBy('city')->pluck('city')->all()); + $this->assertEquals(['Bruges', 'Brussels', 'Ghent'], $user->addresses() + ->where('country', 'Belgium') + ->pluck('city') + ->all()); + $this->assertEquals(['Bruges', 'Brussels', 'Ghent'], $user->addresses() + ->where('country', 'Belgium') + ->sortBy('city') + ->pluck('city') + ->all()); $results = $user->addresses->first(); - $this->assertInstanceOf('Address', $results); + $this->assertInstanceOf(Address::class, $results); $results = $user->addresses()->where('country', 'Belgium'); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $results); + $this->assertInstanceOf(Collection::class, $results); $this->assertEquals(3, $results->count()); $results = $user->addresses()->whereIn('visited', [7, 13]); @@ -451,32 +538,44 @@ public function testEmbedsOne() $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); - $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.creating: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($father), $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); $this->assertNotNull($user->father); $this->assertEquals('Mark Doe', $user->father->name); - $this->assertInstanceOf('DateTime', $father->created_at); - $this->assertInstanceOf('DateTime', $father->updated_at); + $this->assertInstanceOf(DateTime::class, $father->created_at); + $this->assertInstanceOf(DateTime::class, $father->updated_at); $this->assertNotNull($father->_id); - $this->assertInternalType('string', $father->_id); + $this->assertIsString($father->_id); $raw = $father->getAttributes(); - $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); - - $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.updated: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $this->assertInstanceOf(ObjectId::class, $raw['_id']); + + $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.updating: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($father), $father); $father->name = 'Tom Doe'; $user->father()->save($father); @@ -487,12 +586,18 @@ public function testEmbedsOne() $father = new User(['name' => 'Jim Doe']); - $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); + $events->shouldReceive('until') + ->once() + ->with('eloquent.saving: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('until') + ->once() + ->with('eloquent.creating: ' . get_class($father), $father) + ->andReturn(true); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($father), $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); @@ -506,8 +611,8 @@ public function testEmbedsOneAssociate() $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); - $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('fire')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); + $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . get_class($father), Mockery::any()); $events->shouldReceive('until')->times(0)->with('eloquent.saving: ' . get_class($father), $father); $father = $user->father()->associate($father); @@ -534,6 +639,7 @@ public function testEmbedsOneDelete() public function testEmbedsManyToArray() { + /** @var User $user */ $user = User::create(['name' => 'John Doe']); $user->addresses()->save(new Address(['city' => 'New York'])); $user->addresses()->save(new Address(['city' => 'Paris'])); @@ -541,12 +647,14 @@ public function testEmbedsManyToArray() $array = $user->toArray(); $this->assertArrayHasKey('addresses', $array); - $this->assertInternalType('array', $array['addresses']); + $this->assertIsArray($array['addresses']); } public function testEmbeddedSave() { + /** @var User $user */ $user = User::create(['name' => 'John Doe']); + /** @var \Address $address */ $address = $user->addresses()->create(['city' => 'New York']); $father = $user->father()->create(['name' => 'Mark Doe']); diff --git a/tests/GeospatialTest.php b/tests/GeospatialTest.php index 2d646b337..51d44abc7 100644 --- a/tests/GeospatialTest.php +++ b/tests/GeospatialTest.php @@ -1,8 +1,9 @@ [ 'type' => 'Polygon', - 'coordinates' => [[ - [ - -0.1450383, - 51.5069158, - ], - [ - -0.1367563, - 51.5100913, - ], - [ - -0.1270247, - 51.5013233, - ], - [ - -0.1460866, - 51.4952136, - ], + 'coordinates' => [ [ - -0.1450383, - 51.5069158, + [ + -0.1450383, + 51.5069158, + ], + [ + -0.1367563, + 51.5100913, + ], + [ + -0.1270247, + 51.5013233, + ], + [ + -0.1460866, + 51.4952136, + ], + [ + -0.1450383, + 51.5069158, + ], ], - ]], + ], ], ]); @@ -104,7 +107,7 @@ public function testGeoIntersects() 51.5078646, ], ], - ] + ], ]); $this->assertEquals(1, $locations->count()); diff --git a/tests/HybridRelationsTest.php b/tests/HybridRelationsTest.php index 2223950ec..025a1aa4d 100644 --- a/tests/HybridRelationsTest.php +++ b/tests/HybridRelationsTest.php @@ -1,8 +1,11 @@ assertInstanceOf('MysqlUser', $user); - $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); + $this->assertInstanceOf(MysqlUser::class, $user); + $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); // Mysql User $user->name = "John Doe"; $user->save(); - $this->assertInternalType('int', $user->id); + $this->assertIsInt($user->id); // SQL has many $book = new Book(['title' => 'Game of Thrones']); @@ -79,10 +82,10 @@ public function testHybridWhereHas() { $user = new MysqlUser; $otherUser = new MysqlUser; - $this->assertInstanceOf('MysqlUser', $user); - $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); - $this->assertInstanceOf('MysqlUser', $otherUser); - $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $otherUser->getConnection()); + $this->assertInstanceOf(MysqlUser::class, $user); + $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); + $this->assertInstanceOf(MysqlUser::class, $otherUser); + $this->assertInstanceOf(MySqlConnection::class, $otherUser->getConnection()); //MySql User $user->name = "John Doe"; @@ -93,8 +96,8 @@ public function testHybridWhereHas() $otherUser->id = 3; $otherUser->save(); // Make sure they are created - $this->assertInternalType('int', $user->id); - $this->assertInternalType('int', $otherUser->id); + $this->assertIsInt($user->id); + $this->assertIsInt($otherUser->id); // Clear to start $user->books()->truncate(); $otherUser->books()->truncate(); @@ -133,10 +136,10 @@ public function testHybridWith() { $user = new MysqlUser; $otherUser = new MysqlUser; - $this->assertInstanceOf('MysqlUser', $user); - $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); - $this->assertInstanceOf('MysqlUser', $otherUser); - $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $otherUser->getConnection()); + $this->assertInstanceOf(MysqlUser::class, $user); + $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); + $this->assertInstanceOf(MysqlUser::class, $otherUser); + $this->assertInstanceOf(MySqlConnection::class, $otherUser->getConnection()); //MySql User $user->name = "John Doe"; @@ -147,8 +150,8 @@ public function testHybridWith() $otherUser->id = 3; $otherUser->save(); // Make sure they are created - $this->assertInternalType('int', $user->id); - $this->assertInternalType('int', $otherUser->id); + $this->assertIsInt($user->id); + $this->assertIsInt($otherUser->id); // Clear to start Book::truncate(); MysqlBook::truncate(); diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 4387d1231..d774e5306 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -1,14 +1,16 @@ assertInstanceOf(Model::class, $user); - $this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection()); + $this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $user->getConnection()); $this->assertFalse($user->exists); $this->assertEquals('users', $user->getTable()); $this->assertEquals('_id', $user->getKeyName()); } - public function testInsert() + public function testInsert(): void { $user = new User; $user->name = 'John Doe'; @@ -39,7 +41,7 @@ public function testInsert() $this->assertEquals(1, User::count()); $this->assertTrue(isset($user->_id)); - $this->assertInternalType('string', $user->_id); + $this->assertIsString($user->_id); $this->assertNotEquals('', (string) $user->_id); $this->assertNotEquals(0, strlen((string) $user->_id)); $this->assertInstanceOf(Carbon::class, $user->created_at); @@ -51,7 +53,7 @@ public function testInsert() $this->assertEquals(35, $user->age); } - public function testUpdate() + public function testUpdate(): void { $user = new User; $user->name = 'John Doe'; @@ -62,8 +64,8 @@ public function testUpdate() $raw = $user->getAttributes(); $this->assertInstanceOf(ObjectID::class, $raw['_id']); + /** @var User $check */ $check = User::find($user->_id); - $check->age = 36; $check->save(); @@ -84,7 +86,7 @@ public function testUpdate() $this->assertEquals(20, $check->age); } - public function testManualStringId() + public function testManualStringId(): void { $user = new User; $user->_id = '4af9f23d8ead0e1d32000000'; @@ -110,10 +112,10 @@ public function testManualStringId() $this->assertEquals('customId', $user->_id); $raw = $user->getAttributes(); - $this->assertInternalType('string', $raw['_id']); + $this->assertIsString($raw['_id']); } - public function testManualIntId() + public function testManualIntId(): void { $user = new User; $user->_id = 1; @@ -126,10 +128,10 @@ public function testManualIntId() $this->assertEquals(1, $user->_id); $raw = $user->getAttributes(); - $this->assertInternalType('integer', $raw['_id']); + $this->assertIsInt($raw['_id']); } - public function testDelete() + public function testDelete(): void { $user = new User; $user->name = 'John Doe'; @@ -145,7 +147,7 @@ public function testDelete() $this->assertEquals(0, User::count()); } - public function testAll() + public function testAll(): void { $user = new User; $user->name = 'John Doe'; @@ -166,7 +168,7 @@ public function testAll() $this->assertContains('Jane Doe', $all->pluck('name')); } - public function testFind() + public function testFind(): void { $user = new User; $user->name = 'John Doe'; @@ -174,6 +176,7 @@ public function testFind() $user->age = 35; $user->save(); + /** @var User $check */ $check = User::find($user->_id); $this->assertInstanceOf(Model::class, $check); @@ -184,7 +187,7 @@ public function testFind() $this->assertEquals(35, $check->age); } - public function testGet() + public function testGet(): void { User::insert([ ['name' => 'John Doe'], @@ -197,19 +200,20 @@ public function testGet() $this->assertInstanceOf(Model::class, $users[0]); } - public function testFirst() + public function testFirst(): void { User::insert([ ['name' => 'John Doe'], ['name' => 'Jane Doe'], ]); + /** @var User $user */ $user = User::first(); $this->assertInstanceOf(Model::class, $user); $this->assertEquals('John Doe', $user->name); } - public function testNoDocument() + public function testNoDocument(): void { $items = Item::where('name', 'nothing')->get(); $this->assertInstanceOf(Collection::class, $items); @@ -222,25 +226,27 @@ public function testNoDocument() $this->assertNull($item); } - public function testFindOrfail() + public function testFindOrFail(): void { - $this->expectException(Illuminate\Database\Eloquent\ModelNotFoundException::class); - User::findOrfail('51c33d8981fec6813e00000a'); + $this->expectException(ModelNotFoundException::class); + User::findOrFail('51c33d8981fec6813e00000a'); } - public function testCreate() + public function testCreate(): void { + /** @var User $user */ $user = User::create(['name' => 'Jane Poe']); $this->assertInstanceOf(Model::class, $user); $this->assertTrue($user->exists); $this->assertEquals('Jane Poe', $user->name); + /** @var User $check */ $check = User::where('name', 'Jane Poe')->first(); $this->assertEquals($user->_id, $check->_id); } - public function testDestroy() + public function testDestroy(): void { $user = new User; $user->name = 'John Doe'; @@ -253,7 +259,7 @@ public function testDestroy() $this->assertEquals(0, User::count()); } - public function testTouch() + public function testTouch(): void { $user = new User; $user->name = 'John Doe'; @@ -262,21 +268,23 @@ public function testTouch() $user->save(); $old = $user->updated_at; - sleep(1); $user->touch(); + + /** @var User $check */ $check = User::find($user->_id); $this->assertNotEquals($old, $check->updated_at); } - public function testSoftDelete() + public function testSoftDelete(): void { Soft::create(['name' => 'John Doe']); Soft::create(['name' => 'Jane Doe']); $this->assertEquals(2, Soft::count()); + /** @var Soft $user */ $user = Soft::where('name', 'John Doe')->first(); $this->assertTrue($user->exists); $this->assertFalse($user->trashed()); @@ -301,7 +309,7 @@ public function testSoftDelete() $this->assertEquals(2, Soft::count()); } - public function testPrimaryKey() + public function testPrimaryKey(): void { $user = new User; $this->assertEquals('_id', $user->getKeyName()); @@ -315,13 +323,14 @@ public function testPrimaryKey() $this->assertEquals('A Game of Thrones', $book->getKey()); + /** @var Book $check */ $check = Book::find('A Game of Thrones'); $this->assertEquals('title', $check->getKeyName()); $this->assertEquals('A Game of Thrones', $check->getKey()); $this->assertEquals('A Game of Thrones', $check->title); } - public function testScope() + public function testScope(): void { Item::insert([ ['name' => 'knife', 'type' => 'sharp'], @@ -332,7 +341,7 @@ public function testScope() $this->assertEquals(1, $sharp->count()); } - public function testToArray() + public function testToArray(): void { $item = Item::create(['name' => 'fork', 'type' => 'sharp']); @@ -340,12 +349,12 @@ public function testToArray() $keys = array_keys($array); sort($keys); $this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys); - $this->assertInternalType('string', $array['created_at']); - $this->assertInternalType('string', $array['updated_at']); - $this->assertInternalType('string', $array['_id']); + $this->assertIsString($array['created_at']); + $this->assertIsString($array['updated_at']); + $this->assertIsString($array['_id']); } - public function testUnset() + public function testUnset(): void { $user1 = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']); $user2 = User::create(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']); @@ -372,7 +381,7 @@ public function testUnset() $this->assertObjectNotHasAttribute('note2', $user2); } - public function testDates() + public function testDates(): void { $birthday = new DateTime('1980/1/1'); $user = User::create(['name' => 'John Doe', 'birthday' => $birthday]); @@ -399,10 +408,12 @@ public function testDates() $this->assertLessThan(2, abs(time() - $item->created_at->getTimestamp())); // test default date format for json output + /** @var Item $item */ $item = Item::create(['name' => 'sword']); $json = $item->toArray(); $this->assertEquals($item->created_at->format('Y-m-d H:i:s'), $json['created_at']); + /** @var User $user */ $user = User::create(['name' => 'Jane Doe', 'birthday' => time()]); $this->assertInstanceOf(Carbon::class, $user->birthday); @@ -423,8 +434,9 @@ public function testDates() $this->assertEquals((string) $user->getAttribute('entry.date')->format('Y-m-d H:i:s'), $data['entry']['date']); } - public function testIdAttribute() + public function testIdAttribute(): void { + /** @var User $user */ $user = User::create(['name' => 'John Doe']); $this->assertEquals($user->id, $user->_id); @@ -432,8 +444,9 @@ public function testIdAttribute() $this->assertNotEquals($user->id, $user->_id); } - public function testPushPull() + public function testPushPull(): void { + /** @var User $user */ $user = User::create(['name' => 'John Doe']); $user->push('tags', 'tag1'); @@ -458,36 +471,36 @@ public function testPushPull() $this->assertEquals([], $user->tags); } - public function testRaw() + public function testRaw(): void { User::create(['name' => 'John Doe', 'age' => 35]); User::create(['name' => 'Jane Doe', 'age' => 35]); User::create(['name' => 'Harry Hoe', 'age' => 15]); - $users = User::raw(function ($collection) { + $users = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { return $collection->find(['age' => 35]); }); $this->assertInstanceOf(Collection::class, $users); $this->assertInstanceOf(Model::class, $users[0]); - $user = User::raw(function ($collection) { + $user = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { return $collection->findOne(['age' => 35]); }); $this->assertInstanceOf(Model::class, $user); - $count = User::raw(function ($collection) { + $count = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { return $collection->count(); }); $this->assertEquals(3, $count); - $result = User::raw(function ($collection) { + $result = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { return $collection->insertOne(['name' => 'Yvonne Yoe', 'age' => 35]); }); $this->assertNotNull($result); } - public function testDotNotation() + public function testDotNotation(): void { $user = User::create([ 'name' => 'John Doe', @@ -509,8 +522,9 @@ public function testDotNotation() $this->assertEquals('Strasbourg', $user['address.city']); } - public function testMultipleLevelDotNotation() + public function testMultipleLevelDotNotation(): void { + /** @var Book $book */ $book = Book::create([ 'title' => 'A Game of Thrones', 'chapters' => [ @@ -525,7 +539,7 @@ public function testMultipleLevelDotNotation() $this->assertEquals('The first chapter', $book['chapters.one.title']); } - public function testGetDirtyDates() + public function testGetDirtyDates(): void { $user = new User(); $user->setRawAttributes(['name' => 'John Doe', 'birthday' => new DateTime('19 august 1989')], true); @@ -535,14 +549,14 @@ public function testGetDirtyDates() $this->assertEmpty($user->getDirty()); } - public function testChunkById() + public function testChunkById(): void { - User::create(['name' => 'fork', 'tags' => ['sharp', 'pointy']]); + User::create(['name' => 'fork', 'tags' => ['sharp', 'pointy']]); User::create(['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']]); User::create(['name' => 'spoon', 'tags' => ['round', 'bowl']]); $count = 0; - User::chunkById(2, function ($items) use (&$count) { + User::chunkById(2, function (\Illuminate\Database\Eloquent\Collection $items) use (&$count) { $count += count($items); }); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index ac1479d26..bc30ad66b 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -1,11 +1,17 @@ truncate(); DB::collection('items')->truncate(); @@ -40,14 +46,14 @@ public function testDeleteWithId() DB::collection('items')->where('user_id', $user_id)->delete($pid); - DB::collection('items')->where('user_id', $user_id)->delete(str_random(32)); + DB::collection('items')->where('user_id', $user_id)->delete(md5('random-id')); $this->assertEquals(2, DB::collection('items')->count()); } public function testCollection() { - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users')); + $this->assertInstanceOf(Builder::class, DB::collection('users')); } public function testGet() @@ -85,13 +91,13 @@ public function testInsert() $user = $users[0]; $this->assertEquals('John Doe', $user['name']); - $this->assertInternalType('array', $user['tags']); + $this->assertIsArray($user['tags']); } public function testInsertGetId() { $id = DB::collection('users')->insertGetId(['name' => 'John Doe']); - $this->assertInstanceOf('MongoDB\BSON\ObjectID', $id); + $this->assertInstanceOf(ObjectId::class, $id); } public function testBatchInsert() @@ -109,7 +115,7 @@ public function testBatchInsert() $users = DB::collection('users')->get(); $this->assertCount(2, $users); - $this->assertInternalType('array', $users[0]['tags']); + $this->assertIsArray($users[0]['tags']); } public function testFind() @@ -177,11 +183,11 @@ public function testSubKey() { DB::collection('users')->insert([ [ - 'name' => 'John Doe', + 'name' => 'John Doe', 'address' => ['country' => 'Belgium', 'city' => 'Ghent'], ], [ - 'name' => 'Jane Doe', + 'name' => 'Jane Doe', 'address' => ['country' => 'France', 'city' => 'Paris'], ], ]); @@ -220,14 +226,14 @@ public function testRaw() return $collection->find(['age' => 20]); }); - $this->assertInstanceOf('MongoDB\Driver\Cursor', $cursor); + $this->assertInstanceOf(Cursor::class, $cursor); $this->assertCount(1, $cursor->toArray()); $collection = DB::collection('users')->raw(); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf(Collection::class, $collection); $collection = User::raw(); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf(Collection::class, $collection); $results = DB::collection('users')->whereRaw(['age' => 20])->get(); $this->assertCount(1, $results); @@ -237,15 +243,15 @@ public function testRaw() public function testPush() { $id = DB::collection('users')->insertGetId([ - 'name' => 'John Doe', - 'tags' => [], + 'name' => 'John Doe', + 'tags' => [], 'messages' => [], ]); DB::collection('users')->where('_id', $id)->push('tags', 'tag1'); $user = DB::collection('users')->find($id); - $this->assertInternalType('array', $user['tags']); + $this->assertIsArray($user['tags']); $this->assertCount(1, $user['tags']); $this->assertEquals('tag1', $user['tags'][0]); @@ -267,17 +273,25 @@ public function testPush() $message = ['from' => 'Jane', 'body' => 'Hi John']; DB::collection('users')->where('_id', $id)->push('messages', $message); $user = DB::collection('users')->find($id); - $this->assertInternalType('array', $user['messages']); + $this->assertIsArray($user['messages']); $this->assertCount(1, $user['messages']); $this->assertEquals($message, $user['messages'][0]); // Raw - DB::collection('users')->where('_id', $id)->push(['tags' => 'tag3', 'messages' => ['from' => 'Mark', 'body' => 'Hi John']]); + DB::collection('users')->where('_id', $id)->push([ + 'tags' => 'tag3', + 'messages' => ['from' => 'Mark', 'body' => 'Hi John'], + ]); $user = DB::collection('users')->find($id); $this->assertCount(4, $user['tags']); $this->assertCount(2, $user['messages']); - DB::collection('users')->where('_id', $id)->push(['messages' => ['date' => new DateTime(), 'body' => 'Hi John']]); + DB::collection('users')->where('_id', $id)->push([ + 'messages' => [ + 'date' => new DateTime(), + 'body' => 'Hi John', + ], + ]); $user = DB::collection('users')->find($id); $this->assertCount(3, $user['messages']); } @@ -288,22 +302,22 @@ public function testPull() $message2 = ['from' => 'Mark', 'body' => 'Hi John']; $id = DB::collection('users')->insertGetId([ - 'name' => 'John Doe', - 'tags' => ['tag1', 'tag2', 'tag3', 'tag4'], + 'name' => 'John Doe', + 'tags' => ['tag1', 'tag2', 'tag3', 'tag4'], 'messages' => [$message1, $message2], ]); DB::collection('users')->where('_id', $id)->pull('tags', 'tag3'); $user = DB::collection('users')->find($id); - $this->assertInternalType('array', $user['tags']); + $this->assertIsArray($user['tags']); $this->assertCount(3, $user['tags']); $this->assertEquals('tag4', $user['tags'][2]); DB::collection('users')->where('_id', $id)->pull('messages', $message1); $user = DB::collection('users')->find($id); - $this->assertInternalType('array', $user['messages']); + $this->assertIsArray($user['messages']); $this->assertCount(1, $user['messages']); // Raw @@ -317,7 +331,7 @@ public function testDistinct() { DB::collection('items')->insert([ ['name' => 'knife', 'type' => 'sharp'], - ['name' => 'fork', 'type' => 'sharp'], + ['name' => 'fork', 'type' => 'sharp'], ['name' => 'spoon', 'type' => 'round'], ['name' => 'spoon', 'type' => 'round'], ]); @@ -337,7 +351,7 @@ public function testCustomId() { DB::collection('items')->insert([ ['_id' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['_id' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['_id' => 'fork', 'type' => 'sharp', 'amount' => 20], ['_id' => 'spoon', 'type' => 'round', 'amount' => 3], ]); @@ -360,7 +374,7 @@ public function testTake() { DB::collection('items')->insert([ ['name' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 14], ]); @@ -374,7 +388,7 @@ public function testSkip() { DB::collection('items')->insert([ ['name' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 14], ]); @@ -399,7 +413,7 @@ public function testList() { DB::collection('items')->insert([ ['name' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 14], ]); @@ -422,7 +436,7 @@ public function testAggregate() { DB::collection('items')->insert([ ['name' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 14], ]); @@ -441,7 +455,7 @@ public function testSubdocumentAggregate() { DB::collection('items')->insert([ ['name' => 'knife', 'amount' => ['hidden' => 10, 'found' => 3]], - ['name' => 'fork', 'amount' => ['hidden' => 35, 'found' => 12]], + ['name' => 'fork', 'amount' => ['hidden' => 35, 'found' => 12]], ['name' => 'spoon', 'amount' => ['hidden' => 14, 'found' => 21]], ['name' => 'spoon', 'amount' => ['hidden' => 6, 'found' => 4]], ]); @@ -457,7 +471,14 @@ public function testSubdocumentArrayAggregate() { DB::collection('items')->insert([ ['name' => 'knife', 'amount' => [['hidden' => 10, 'found' => 3], ['hidden' => 5, 'found' => 2]]], - ['name' => 'fork', 'amount' => [['hidden' => 35, 'found' => 12], ['hidden' => 7, 'found' => 17], ['hidden' => 1, 'found' => 19]]], + [ + 'name' => 'fork', + 'amount' => [ + ['hidden' => 35, 'found' => 12], + ['hidden' => 7, 'found' => 17], + ['hidden' => 1, 'found' => 19], + ], + ], ['name' => 'spoon', 'amount' => [['hidden' => 14, 'found' => 21]]], ['name' => 'teaspoon', 'amount' => []], ]); @@ -472,15 +493,15 @@ public function testSubdocumentArrayAggregate() public function testUpsert() { DB::collection('items')->where('name', 'knife') - ->update( - ['amount' => 1], - ['upsert' => true] - ); + ->update( + ['amount' => 1], + ['upsert' => true] + ); $this->assertEquals(1, DB::collection('items')->count()); Item::where('name', 'spoon') - ->update( + ->update( ['amount' => 1], ['upsert' => true] ); @@ -529,7 +550,9 @@ public function testDates() ['name' => 'Mark Moe', 'birthday' => new UTCDateTime(1000 * strtotime("1983-01-01 00:00:00"))], ]); - $user = DB::collection('users')->where('birthday', new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00")))->first(); + $user = DB::collection('users') + ->where('birthday', new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00"))) + ->first(); $this->assertEquals('John Doe', $user['name']); $user = DB::collection('users')->where('birthday', '=', new DateTime("1980-01-01 00:00:00"))->first(); @@ -576,7 +599,7 @@ public function testOperators() $this->assertCount(0, $results); DB::collection('items')->insert([ - ['name' => 'fork', 'tags' => ['sharp', 'pointy']], + ['name' => 'fork', 'tags' => ['sharp', 'pointy']], ['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']], ['name' => 'spoon', 'tags' => ['round', 'bowl']], ]); @@ -618,14 +641,14 @@ public function testOperators() DB::collection('users')->insert([ [ - 'name' => 'John Doe', + 'name' => 'John Doe', 'addresses' => [ ['city' => 'Ghent'], ['city' => 'Paris'], ], ], [ - 'name' => 'Jane Doe', + 'name' => 'Jane Doe', 'addresses' => [ ['city' => 'Brussels'], ['city' => 'Paris'], @@ -690,7 +713,7 @@ public function testIncrement() public function testProjections() { DB::collection('items')->insert([ - ['name' => 'fork', 'tags' => ['sharp', 'pointy']], + ['name' => 'fork', 'tags' => ['sharp', 'pointy']], ['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']], ['name' => 'spoon', 'tags' => ['round', 'bowl']], ]); @@ -701,4 +724,17 @@ public function testProjections() $this->assertEquals(1, count($result['tags'])); } } + + public function testValue() + { + DB::collection('books')->insert([ + ['title' => 'Moby-Dick', 'author' => ['first_name' => 'Herman', 'last_name' => 'Melville']], + ]); + + $this->assertEquals('Moby-Dick', DB::collection('books')->value('title')); + $this->assertEquals(['first_name' => 'Herman', 'last_name' => 'Melville'], DB::collection('books') + ->value('author')); + $this->assertEquals('Herman', DB::collection('books')->value('author.first_name')); + $this->assertEquals('Melville', DB::collection('books')->value('author.last_name')); + } } diff --git a/tests/QueryTest.php b/tests/QueryTest.php index 2011305c2..ab36d1886 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -1,10 +1,11 @@ 'John Doe', 'age' => 35, 'title' => 'admin']); @@ -18,13 +19,14 @@ public function setUp() User::create(['name' => 'Error', 'age' => null, 'title' => null]); } - public function tearDown() + public function tearDown(): void { User::truncate(); + Scoped::truncate(); parent::tearDown(); } - public function testWhere() + public function testWhere(): void { $users = User::where('age', 35)->get(); $this->assertCount(3, $users); @@ -45,7 +47,7 @@ public function testWhere() $this->assertCount(6, $users); } - public function testAndWhere() + public function testAndWhere(): void { $users = User::where('age', 35)->where('title', 'admin')->get(); $this->assertCount(2, $users); @@ -54,7 +56,7 @@ public function testAndWhere() $this->assertCount(2, $users); } - public function testLike() + public function testLike(): void { $users = User::where('name', 'like', '%doe')->get(); $this->assertCount(2, $users); @@ -69,7 +71,22 @@ public function testLike() $this->assertCount(1, $users); } - public function testSelect() + public function testNotLike(): void + { + $users = User::where('name', 'not like', '%doe')->get(); + $this->assertCount(7, $users); + + $users = User::where('name', 'not like', '%y%')->get(); + $this->assertCount(6, $users); + + $users = User::where('name', 'not LIKE', '%y%')->get(); + $this->assertCount(6, $users); + + $users = User::where('name', 'not like', 't%')->get(); + $this->assertCount(8, $users); + } + + public function testSelect(): void { $user = User::where('name', 'John Doe')->select('name')->first(); @@ -95,7 +112,7 @@ public function testSelect() $this->assertNull($user->age); } - public function testOrWhere() + public function testOrWhere(): void { $users = User::where('age', 13)->orWhere('title', 'admin')->get(); $this->assertCount(4, $users); @@ -104,7 +121,7 @@ public function testOrWhere() $this->assertCount(2, $users); } - public function testBetween() + public function testBetween(): void { $users = User::whereBetween('age', [0, 25])->get(); $this->assertCount(2, $users); @@ -117,7 +134,7 @@ public function testBetween() $this->assertCount(6, $users); } - public function testIn() + public function testIn(): void { $users = User::whereIn('age', [13, 23])->get(); $this->assertCount(2, $users); @@ -129,23 +146,23 @@ public function testIn() $this->assertCount(4, $users); $users = User::whereNotNull('age') - ->whereNotIn('age', [33, 35])->get(); + ->whereNotIn('age', [33, 35])->get(); $this->assertCount(3, $users); } - public function testWhereNull() + public function testWhereNull(): void { $users = User::whereNull('age')->get(); $this->assertCount(1, $users); } - public function testWhereNotNull() + public function testWhereNotNull(): void { $users = User::whereNotNull('age')->get(); $this->assertCount(8, $users); } - public function testOrder() + public function testOrder(): void { $user = User::whereNotNull('age')->orderBy('age', 'asc')->first(); $this->assertEquals(13, $user->age); @@ -166,7 +183,7 @@ public function testOrder() $this->assertEquals(35, $user->age); } - public function testGroupBy() + public function testGroupBy(): void { $users = User::groupBy('title')->get(); $this->assertCount(3, $users); @@ -196,7 +213,7 @@ public function testGroupBy() $this->assertNotNull($users[0]->name); } - public function testCount() + public function testCount(): void { $count = User::where('age', '<>', 35)->count(); $this->assertEquals(6, $count); @@ -206,17 +223,17 @@ public function testCount() $this->assertEquals(6, $count); } - public function testExists() + public function testExists(): void { $this->assertFalse(User::where('age', '>', 37)->exists()); $this->assertTrue(User::where('age', '<', 37)->exists()); } - public function testSubquery() + public function testSubQuery(): void { $users = User::where('title', 'admin')->orWhere(function ($query) { $query->where('name', 'Tommy Toe') - ->orWhere('name', 'Error'); + ->orWhere('name', 'Error'); }) ->get(); @@ -224,7 +241,7 @@ public function testSubquery() $users = User::where('title', 'user')->where(function ($query) { $query->where('age', 35) - ->orWhere('name', 'like', '%harry%'); + ->orWhere('name', 'like', '%harry%'); }) ->get(); @@ -232,36 +249,36 @@ public function testSubquery() $users = User::where('age', 35)->orWhere(function ($query) { $query->where('title', 'admin') - ->orWhere('name', 'Error'); + ->orWhere('name', 'Error'); }) ->get(); $this->assertCount(5, $users); $users = User::whereNull('deleted_at') - ->where('title', 'admin') - ->where(function ($query) { - $query->where('age', '>', 15) - ->orWhere('name', 'Harry Hoe'); - }) - ->get(); + ->where('title', 'admin') + ->where(function ($query) { + $query->where('age', '>', 15) + ->orWhere('name', 'Harry Hoe'); + }) + ->get(); $this->assertEquals(3, $users->count()); $users = User::whereNull('deleted_at') - ->where(function ($query) { - $query->where('name', 'Harry Hoe') - ->orWhere(function ($query) { - $query->where('age', '>', 15) - ->where('title', '<>', 'admin'); - }); - }) - ->get(); + ->where(function ($query) { + $query->where('name', 'Harry Hoe') + ->orWhere(function ($query) { + $query->where('age', '>', 15) + ->where('title', '<>', 'admin'); + }); + }) + ->get(); $this->assertEquals(5, $users->count()); } - public function testWhereRaw() + public function testWhereRaw(): void { $where = ['age' => ['$gt' => 30, '$lt' => 40]]; $users = User::whereRaw($where)->get(); @@ -269,34 +286,34 @@ public function testWhereRaw() $this->assertCount(6, $users); $where1 = ['age' => ['$gt' => 30, '$lte' => 35]]; - $where2 = ['age' => ['$gt' => 35, '$lt' => 40]]; + $where2 = ['age' => ['$gt' => 35, '$lt' => 40]]; $users = User::whereRaw($where1)->orWhereRaw($where2)->get(); $this->assertCount(6, $users); } - public function testMultipleOr() + public function testMultipleOr(): void { $users = User::where(function ($query) { $query->where('age', 35)->orWhere('age', 33); }) - ->where(function ($query) { - $query->where('name', 'John Doe')->orWhere('name', 'Jane Doe'); - })->get(); + ->where(function ($query) { + $query->where('name', 'John Doe')->orWhere('name', 'Jane Doe'); + })->get(); $this->assertCount(2, $users); $users = User::where(function ($query) { $query->orWhere('age', 35)->orWhere('age', 33); }) - ->where(function ($query) { - $query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe'); - })->get(); + ->where(function ($query) { + $query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe'); + })->get(); $this->assertCount(2, $users); } - public function testPaginate() + public function testPaginate(): void { $results = User::paginate(2); $this->assertEquals(2, $results->count()); @@ -309,4 +326,21 @@ public function testPaginate() $this->assertEquals(9, $results->total()); $this->assertEquals(1, $results->currentPage()); } + + public function testUpdate(): void + { + $this->assertEquals(1, User::where(['name' => 'John Doe'])->update(['name' => 'Jim Morrison'])); + $this->assertEquals(1, User::where(['name' => 'Jim Morrison'])->count()); + + Scoped::create(['favorite' => true]); + Scoped::create(['favorite' => false]); + + $this->assertCount(1, Scoped::get()); + $this->assertEquals(1, Scoped::query()->update(['name' => 'Johnny'])); + $this->assertCount(1, Scoped::withoutGlobalScopes()->where(['name' => 'Johnny'])->get()); + + $this->assertCount(2, Scoped::withoutGlobalScopes()->get()); + $this->assertEquals(2, Scoped::withoutGlobalScopes()->update(['name' => 'Jimmy'])); + $this->assertCount(2, Scoped::withoutGlobalScopes()->where(['name' => 'Jimmy'])->get()); + } } diff --git a/tests/QueueTest.php b/tests/QueueTest.php index 35be33f9a..6ff26d35c 100644 --- a/tests/QueueTest.php +++ b/tests/QueueTest.php @@ -1,8 +1,9 @@ table(Config::get('queue.failed.table'))->truncate(); } - public function testQueueJobLifeCycle() + public function testQueueJobLifeCycle(): void { $id = Queue::push('test', ['action' => 'QueueJobLifeCycle'], 'test'); $this->assertNotNull($id); @@ -24,6 +25,7 @@ public function testQueueJobLifeCycle() 'displayName' => 'test', 'job' => 'test', 'maxTries' => null, + 'delay' => null, 'timeout' => null, 'data' => ['action' => 'QueueJobLifeCycle'], ]), $job->getRawBody()); @@ -33,7 +35,7 @@ public function testQueueJobLifeCycle() $this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count()); } - public function testQueueJobExpired() + public function testQueueJobExpired(): void { $id = Queue::push('test', ['action' => 'QueueJobExpired'], 'test'); $this->assertNotNull($id); diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 1e2aaa491..a50329682 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -1,8 +1,11 @@ 'George R. R. Martin']); Book::create(['title' => 'A Game of Thrones', 'author_id' => $author->_id]); @@ -36,7 +39,7 @@ public function testHasMany() $this->assertCount(3, $items); } - public function testBelongsTo() + public function testBelongsTo(): void { $user = User::create(['name' => 'George R. R. Martin']); Book::create(['title' => 'A Game of Thrones', 'author_id' => $user->_id]); @@ -55,7 +58,7 @@ public function testBelongsTo() $this->assertNull($book->author); } - public function testHasOne() + public function testHasOne(): void { $user = User::create(['name' => 'John Doe']); Role::create(['type' => 'admin', 'user_id' => $user->_id]); @@ -78,7 +81,7 @@ public function testHasOne() $this->assertEquals($user->_id, $role->user_id); } - public function testWithBelongsTo() + public function testWithBelongsTo(): void { $user = User::create(['name' => 'John Doe']); Item::create(['type' => 'knife', 'user_id' => $user->_id]); @@ -89,13 +92,13 @@ public function testWithBelongsTo() $items = Item::with('user')->orderBy('user_id', 'desc')->get(); $user = $items[0]->getRelation('user'); - $this->assertInstanceOf('User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('John Doe', $user->name); $this->assertCount(1, $items[0]->getRelations()); $this->assertNull($items[3]->getRelation('user')); } - public function testWithHashMany() + public function testWithHashMany(): void { $user = User::create(['name' => 'John Doe']); Item::create(['type' => 'knife', 'user_id' => $user->_id]); @@ -107,10 +110,10 @@ public function testWithHashMany() $items = $user->getRelation('items'); $this->assertCount(3, $items); - $this->assertInstanceOf('Item', $items[0]); + $this->assertInstanceOf(Item::class, $items[0]); } - public function testWithHasOne() + public function testWithHasOne(): void { $user = User::create(['name' => 'John Doe']); Role::create(['type' => 'admin', 'user_id' => $user->_id]); @@ -119,11 +122,11 @@ public function testWithHasOne() $user = User::with('role')->find($user->_id); $role = $user->getRelation('role'); - $this->assertInstanceOf('Role', $role); + $this->assertInstanceOf(Role::class, $role); $this->assertEquals('admin', $role->type); } - public function testEasyRelation() + public function testEasyRelation(): void { // Has Many $user = User::create(['name' => 'John Doe']); @@ -133,7 +136,7 @@ public function testEasyRelation() $user = User::find($user->_id); $items = $user->items; $this->assertCount(1, $items); - $this->assertInstanceOf('Item', $items[0]); + $this->assertInstanceOf(Item::class, $items[0]); $this->assertEquals($user->_id, $items[0]->user_id); // Has one @@ -143,12 +146,12 @@ public function testEasyRelation() $user = User::find($user->_id); $role = $user->role; - $this->assertInstanceOf('Role', $role); + $this->assertInstanceOf(Role::class, $role); $this->assertEquals('admin', $role->type); $this->assertEquals($user->_id, $role->user_id); } - public function testBelongsToMany() + public function testBelongsToMany(): void { $user = User::create(['name' => 'John Doe']); @@ -167,18 +170,18 @@ public function testBelongsToMany() $clients = $user->getRelation('clients'); $users = $client->getRelation('users'); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $clients); - $this->assertInstanceOf('Client', $clients[0]); - $this->assertInstanceOf('User', $users[0]); + $this->assertInstanceOf(Collection::class, $users); + $this->assertInstanceOf(Collection::class, $clients); + $this->assertInstanceOf(Client::class, $clients[0]); + $this->assertInstanceOf(User::class, $users[0]); $this->assertCount(2, $user->clients); $this->assertCount(1, $client->users); // Now create a new user to an existing client $user = $client->users()->create(['name' => 'Jane Doe']); - $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $user->clients); - $this->assertInstanceOf('Client', $user->clients->first()); + $this->assertInstanceOf(Collection::class, $user->clients); + $this->assertInstanceOf(Client::class, $user->clients->first()); $this->assertCount(1, $user->clients); // Get user and unattached client @@ -186,8 +189,8 @@ public function testBelongsToMany() $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Check the models are what they should be - $this->assertInstanceOf('Client', $client); - $this->assertInstanceOf('User', $user); + $this->assertInstanceOf(Client::class, $client); + $this->assertInstanceOf(User::class, $user); // Assert they are not attached $this->assertNotContains($client->_id, $user->client_ids); @@ -222,7 +225,7 @@ public function testBelongsToMany() $this->assertCount(1, $client->users); } - public function testBelongsToManyAttachesExistingModels() + public function testBelongsToManyAttachesExistingModels(): void { $user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]); @@ -261,7 +264,7 @@ public function testBelongsToManyAttachesExistingModels() $this->assertStringStartsWith('synced', $user->clients[1]->name); } - public function testBelongsToManySync() + public function testBelongsToManySync(): void { // create test instances $user = User::create(['name' => 'John Doe']); @@ -280,7 +283,7 @@ public function testBelongsToManySync() $this->assertCount(1, $user->clients); } - public function testBelongsToManyAttachArray() + public function testBelongsToManyAttachArray(): void { $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1'])->_id; @@ -291,7 +294,7 @@ public function testBelongsToManyAttachArray() $this->assertCount(2, $user->clients); } - public function testBelongsToManyAttachEloquentCollection() + public function testBelongsToManyAttachEloquentCollection(): void { $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1']); @@ -303,7 +306,7 @@ public function testBelongsToManyAttachEloquentCollection() $this->assertCount(2, $user->clients); } - public function testBelongsToManySyncAlreadyPresent() + public function testBelongsToManySyncAlreadyPresent(): void { $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1'])->_id; @@ -320,7 +323,7 @@ public function testBelongsToManySyncAlreadyPresent() $this->assertCount(1, $user['client_ids']); } - public function testBelongsToManyCustom() + public function testBelongsToManyCustom(): void { $user = User::create(['name' => 'John Doe']); $group = $user->groups()->create(['name' => 'Admins']); @@ -340,7 +343,7 @@ public function testBelongsToManyCustom() $this->assertEquals($user->_id, $group->users()->first()->_id); } - public function testMorph() + public function testMorph(): void { $user = User::create(['name' => 'John Doe']); $client = Client::create(['name' => 'Jane Doe']); @@ -376,14 +379,14 @@ public function testMorph() $photos = Photo::with('imageable')->get(); $relations = $photos[0]->getRelations(); $this->assertArrayHasKey('imageable', $relations); - $this->assertInstanceOf('User', $photos[0]->imageable); + $this->assertInstanceOf(User::class, $photos[0]->imageable); $relations = $photos[1]->getRelations(); $this->assertArrayHasKey('imageable', $relations); - $this->assertInstanceOf('Client', $photos[1]->imageable); + $this->assertInstanceOf(Client::class, $photos[1]->imageable); } - public function testHasManyHas() + public function testHasManyHas(): void { $author1 = User::create(['name' => 'George R. R. Martin']); $author1->books()->create(['title' => 'A Game of Thrones', 'rating' => 5]); @@ -433,7 +436,7 @@ public function testHasManyHas() $this->assertCount(1, $authors); } - public function testHasOneHas() + public function testHasOneHas(): void { $user1 = User::create(['name' => 'John Doe']); $user1->role()->create(['title' => 'admin']); @@ -455,19 +458,19 @@ public function testHasOneHas() $this->assertCount(2, $users); } - public function testNestedKeys() + public function testNestedKeys(): void { $client = Client::create([ 'data' => [ 'client_id' => 35298, - 'name' => 'John Doe', + 'name' => 'John Doe', ], ]); $address = $client->addresses()->create([ 'data' => [ 'address_id' => 1432, - 'city' => 'Paris', + 'city' => 'Paris', ], ]); @@ -481,7 +484,7 @@ public function testNestedKeys() $this->assertEquals('Paris', $client->addresses->first()->data['city']); } - public function testDoubleSaveOneToMany() + public function testDoubleSaveOneToMany(): void { $author = User::create(['name' => 'George R. R. Martin']); $book = Book::create(['title' => 'A Game of Thrones']); @@ -504,7 +507,7 @@ public function testDoubleSaveOneToMany() $this->assertEquals($author->_id, $book->author_id); } - public function testDoubleSaveManyToMany() + public function testDoubleSaveManyToMany(): void { $user = User::create(['name' => 'John Doe']); $client = Client::create(['name' => 'Admins']); diff --git a/tests/SchemaTest.php b/tests/SchemaTest.php index a04715d9d..147cf8b96 100644 --- a/tests/SchemaTest.php +++ b/tests/SchemaTest.php @@ -1,51 +1,62 @@ assertTrue(Schema::hasCollection('newcollection')); $this->assertTrue(Schema::hasTable('newcollection')); } - public function testCreateWithCallback() + public function testCreateWithCallback(): void { $instance = $this; Schema::create('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf(Blueprint::class, $collection); }); $this->assertTrue(Schema::hasCollection('newcollection')); } - public function testDrop() + public function testCreateWithOptions(): void + { + Schema::create('newcollection_two', null, ['capped' => true, 'size' => 1024]); + $this->assertTrue(Schema::hasCollection('newcollection_two')); + $this->assertTrue(Schema::hasTable('newcollection_two')); + } + + public function testDrop(): void { Schema::create('newcollection'); Schema::drop('newcollection'); $this->assertFalse(Schema::hasCollection('newcollection')); } - public function testBluePrint() + public function testBluePrint(): void { $instance = $this; Schema::collection('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf(Blueprint::class, $collection); }); Schema::table('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf(Blueprint::class, $collection); }); } - public function testIndex() + public function testIndex(): void { Schema::collection('newcollection', function ($collection) { $collection->index('mykey1'); @@ -69,7 +80,7 @@ public function testIndex() $this->assertEquals(1, $index['key']['mykey3']); } - public function testPrimary() + public function testPrimary(): void { Schema::collection('newcollection', function ($collection) { $collection->string('mykey', 100)->primary(); @@ -79,7 +90,7 @@ public function testPrimary() $this->assertEquals(1, $index['unique']); } - public function testUnique() + public function testUnique(): void { Schema::collection('newcollection', function ($collection) { $collection->unique('uniquekey'); @@ -89,7 +100,7 @@ public function testUnique() $this->assertEquals(1, $index['unique']); } - public function testDropIndex() + public function testDropIndex(): void { Schema::collection('newcollection', function ($collection) { $collection->unique('uniquekey'); @@ -136,7 +147,77 @@ public function testDropIndex() $this->assertFalse($index); } - public function testBackground() + public function testDropIndexIfExists(): void + { + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->unique('uniquekey'); + $collection->dropIndexIfExists('uniquekey_1'); + }); + + $index = $this->getIndex('newcollection', 'uniquekey'); + $this->assertEquals(null, $index); + + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->unique('uniquekey'); + $collection->dropIndexIfExists(['uniquekey']); + }); + + $index = $this->getIndex('newcollection', 'uniquekey'); + $this->assertEquals(null, $index); + + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->index(['field_a', 'field_b']); + }); + + $index = $this->getIndex('newcollection', 'field_a_1_field_b_1'); + $this->assertNotNull($index); + + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->dropIndexIfExists(['field_a', 'field_b']); + }); + + $index = $this->getIndex('newcollection', 'field_a_1_field_b_1'); + $this->assertFalse($index); + + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->index(['field_a', 'field_b'], 'custom_index_name'); + }); + + $index = $this->getIndex('newcollection', 'custom_index_name'); + $this->assertNotNull($index); + + Schema::collection('newcollection', function (Blueprint $collection) { + $collection->dropIndexIfExists('custom_index_name'); + }); + + $index = $this->getIndex('newcollection', 'custom_index_name'); + $this->assertFalse($index); + } + + public function testHasIndex(): void + { + $instance = $this; + + Schema::collection('newcollection', function (Blueprint $collection) use ($instance) { + $collection->index('myhaskey1'); + $instance->assertTrue($collection->hasIndex('myhaskey1_1')); + $instance->assertFalse($collection->hasIndex('myhaskey1')); + }); + + Schema::collection('newcollection', function (Blueprint $collection) use ($instance) { + $collection->index('myhaskey2'); + $instance->assertTrue($collection->hasIndex(['myhaskey2'])); + $instance->assertFalse($collection->hasIndex(['myhaskey2_1'])); + }); + + Schema::collection('newcollection', function (Blueprint $collection) use ($instance) { + $collection->index(['field_a', 'field_b']); + $instance->assertTrue($collection->hasIndex(['field_a_1_field_b'])); + $instance->assertFalse($collection->hasIndex(['field_a_1_field_b_1'])); + }); + } + + public function testBackground(): void { Schema::collection('newcollection', function ($collection) { $collection->background('backgroundkey'); @@ -146,7 +227,7 @@ public function testBackground() $this->assertEquals(1, $index['background']); } - public function testSparse() + public function testSparse(): void { Schema::collection('newcollection', function ($collection) { $collection->sparse('sparsekey'); @@ -156,7 +237,7 @@ public function testSparse() $this->assertEquals(1, $index['sparse']); } - public function testExpire() + public function testExpire(): void { Schema::collection('newcollection', function ($collection) { $collection->expire('expirekey', 60); @@ -166,7 +247,7 @@ public function testExpire() $this->assertEquals(60, $index['expireAfterSeconds']); } - public function testSoftDeletes() + public function testSoftDeletes(): void { Schema::collection('newcollection', function ($collection) { $collection->softDeletes(); @@ -180,7 +261,7 @@ public function testSoftDeletes() $this->assertEquals(1, $index['key']['email']); } - public function testFluent() + public function testFluent(): void { Schema::collection('newcollection', function ($collection) { $collection->string('email')->index(); @@ -195,7 +276,7 @@ public function testFluent() $this->assertEquals(1, $index['key']['token']); } - public function testGeospatial() + public function testGeospatial(): void { Schema::collection('newcollection', function ($collection) { $collection->geospatial('point'); @@ -213,7 +294,7 @@ public function testGeospatial() $this->assertEquals('2dsphere', $index['key']['continent']); } - public function testDummies() + public function testDummies(): void { Schema::collection('newcollection', function ($collection) { $collection->boolean('activated')->default(0); @@ -221,7 +302,7 @@ public function testDummies() }); } - public function testSparseUnique() + public function testSparseUnique(): void { Schema::collection('newcollection', function ($collection) { $collection->sparse_and_unique('sparseuniquekey'); @@ -232,7 +313,7 @@ public function testSparseUnique() $this->assertEquals(1, $index['unique']); } - protected function getIndex($collection, $name) + protected function getIndex(string $collection, string $name) { $collection = DB::getCollection($collection); diff --git a/tests/SeederTest.php b/tests/SeederTest.php index 9581df3d3..d78117799 100644 --- a/tests/SeederTest.php +++ b/tests/SeederTest.php @@ -1,13 +1,14 @@ run(); @@ -16,7 +17,7 @@ public function testSeed() $this->assertTrue($user->seed); } - public function testArtisan() + public function testArtisan(): void { Artisan::call('db:seed'); diff --git a/tests/TestCase.php b/tests/TestCase.php index f4b26be2d..c27fec178 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,27 +1,27 @@ set('queue.default', 'database'); $app['config']->set('queue.connections.database', [ 'driver' => 'mongodb', - 'table' => 'jobs', - 'queue' => 'default', + 'table' => 'jobs', + 'queue' => 'default', 'expire' => 60, ]); } diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index 16e31f4cf..638398866 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -1,13 +1,14 @@ 'John Doe'], @@ -42,7 +43,7 @@ public function testUnique() $this->assertFalse($validator->fails()); } - public function testExists() + public function testExists(): void { $validator = Validator::make( ['name' => 'John Doe'], diff --git a/tests/config/database.php b/tests/config/database.php index f24d20d2f..23f8ca990 100644 --- a/tests/config/database.php +++ b/tests/config/database.php @@ -1,31 +1,34 @@ [ 'mongodb' => [ - 'name' => 'mongodb', - 'driver' => 'mongodb', - 'host' => 'mongodb', - 'database' => 'unittest', + 'name' => 'mongodb', + 'driver' => 'mongodb', + 'host' => $mongoHost, + 'database' => env('MONGO_DATABASE', 'unittest'), ], 'dsn_mongodb' => [ - 'driver' => 'mongodb', - 'dsn' => 'mongodb://mongodb:27017', - 'database' => 'unittest', + 'driver' => 'mongodb', + 'dsn' => "mongodb://$mongoHost:$mongoPort", + 'database' => env('MONGO_DATABASE', 'unittest'), ], 'mysql' => [ - 'driver' => 'mysql', - 'host' => 'mysql', - 'database' => 'unittest', - 'username' => 'root', - 'password' => '', - 'charset' => 'utf8', + 'driver' => 'mysql', + 'host' => env('MYSQL_HOST', 'mysql'), + 'database' => env('MYSQL_DATABASE', 'unittest'), + 'username' => env('MYSQL_USERNAME', 'root'), + 'password' => env('MYSQL_PASSWORD', ''), + 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', - 'prefix' => '', + 'prefix' => '', ], ], diff --git a/tests/config/queue.php b/tests/config/queue.php index 03bc12044..20ef36703 100644 --- a/tests/config/queue.php +++ b/tests/config/queue.php @@ -2,22 +2,22 @@ return [ - 'default' => 'database', + 'default' => env('QUEUE_CONNECTION'), 'connections' => [ 'database' => [ 'driver' => 'mongodb', - 'table' => 'jobs', - 'queue' => 'default', + 'table' => 'jobs', + 'queue' => 'default', 'expire' => 60, ], ], 'failed' => [ - 'database' => 'mongodb', - 'table' => 'failed_jobs', + 'database' => env('MONGO_DATABASE'), + 'table' => 'failed_jobs', ], ]; diff --git a/tests/models/Address.php b/tests/models/Address.php index f2f1278e1..9d094cfcd 100644 --- a/tests/models/Address.php +++ b/tests/models/Address.php @@ -1,13 +1,15 @@ embedsMany('Address'); } diff --git a/tests/models/Book.php b/tests/models/Book.php index 1cf8d22cb..e37cb7eaf 100644 --- a/tests/models/Book.php +++ b/tests/models/Book.php @@ -1,7 +1,15 @@ belongsTo('User', 'author_id'); } - public function mysqlAuthor() + public function mysqlAuthor(): BelongsTo { return $this->belongsTo('MysqlUser', 'author_id'); } diff --git a/tests/models/Client.php b/tests/models/Client.php index b8309deef..dc023e00a 100644 --- a/tests/models/Client.php +++ b/tests/models/Client.php @@ -1,5 +1,9 @@ belongsToMany('User'); } - public function photo() + public function photo(): MorphOne { return $this->morphOne('Photo', 'imageable'); } - public function addresses() + public function addresses(): HasMany { return $this->hasMany('Address', 'data.client_id', 'data.client_id'); } diff --git a/tests/models/Group.php b/tests/models/Group.php index 494836ad9..369f673e8 100644 --- a/tests/models/Group.php +++ b/tests/models/Group.php @@ -1,5 +1,7 @@ belongsToMany('User', 'users', 'groups', 'users', '_id', '_id', 'users'); } diff --git a/tests/models/Item.php b/tests/models/Item.php index ac52226db..b06484d25 100644 --- a/tests/models/Item.php +++ b/tests/models/Item.php @@ -1,19 +1,26 @@ belongsTo('User'); } - public function scopeSharp($query) + public function scopeSharp(Builder $query) { return $query->where('type', 'sharp'); } diff --git a/tests/models/Location.php b/tests/models/Location.php index aa5f36a57..3d44d5ea5 100644 --- a/tests/models/Location.php +++ b/tests/models/Location.php @@ -1,4 +1,5 @@ belongsTo('User', 'author_id'); } @@ -20,12 +23,13 @@ public function author() /** * Check if we need to run the schema. */ - public static function executeSchema() + public static function executeSchema(): void { + /** @var \Illuminate\Database\Schema\MySqlBuilder $schema */ $schema = Schema::connection('mysql'); if (!$schema->hasTable('books')) { - Schema::connection('mysql')->create('books', function ($table) { + Schema::connection('mysql')->create('books', function (Blueprint $table) { $table->string('title'); $table->string('author_id')->nullable(); $table->integer('mysql_user_id')->unsigned()->nullable(); diff --git a/tests/models/MysqlRole.php b/tests/models/MysqlRole.php index e7db21d60..c721ad8c0 100644 --- a/tests/models/MysqlRole.php +++ b/tests/models/MysqlRole.php @@ -1,5 +1,8 @@ belongsTo('User'); } - public function mysqlUser() + public function mysqlUser(): BelongsTo { return $this->belongsTo('MysqlUser'); } @@ -26,10 +29,11 @@ public function mysqlUser() */ public static function executeSchema() { + /** @var \Illuminate\Database\Schema\MySqlBuilder $schema */ $schema = Schema::connection('mysql'); if (!$schema->hasTable('roles')) { - Schema::connection('mysql')->create('roles', function ($table) { + Schema::connection('mysql')->create('roles', function (Blueprint $table) { $table->string('type'); $table->string('user_id'); $table->timestamps(); diff --git a/tests/models/MysqlUser.php b/tests/models/MysqlUser.php index ca15c53ff..67b1052ee 100644 --- a/tests/models/MysqlUser.php +++ b/tests/models/MysqlUser.php @@ -1,5 +1,9 @@ hasMany('Book', 'author_id'); } - public function role() + public function role(): HasOne { return $this->hasOne('Role'); } - public function mysqlBooks() + public function mysqlBooks(): HasMany { return $this->hasMany(MysqlBook::class); } @@ -29,12 +33,13 @@ public function mysqlBooks() /** * Check if we need to run the schema. */ - public static function executeSchema() + public static function executeSchema(): void { + /** @var \Illuminate\Database\Schema\MySqlBuilder $schema */ $schema = Schema::connection('mysql'); if (!$schema->hasTable('users')) { - Schema::connection('mysql')->create('users', function ($table) { + Schema::connection('mysql')->create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); diff --git a/tests/models/Photo.php b/tests/models/Photo.php index 81a5cc2de..beff63825 100644 --- a/tests/models/Photo.php +++ b/tests/models/Photo.php @@ -1,5 +1,7 @@ morphTo(); } diff --git a/tests/models/Role.php b/tests/models/Role.php index a59ce7e02..1e1dc9eb6 100644 --- a/tests/models/Role.php +++ b/tests/models/Role.php @@ -1,5 +1,7 @@ belongsTo('User'); } - public function mysqlUser() + public function mysqlUser(): BelongsTo { return $this->belongsTo('MysqlUser'); } diff --git a/tests/models/Scoped.php b/tests/models/Scoped.php new file mode 100644 index 000000000..9f312f943 --- /dev/null +++ b/tests/models/Scoped.php @@ -0,0 +1,21 @@ +where('favorite', true); + }); + } +} diff --git a/tests/models/Soft.php b/tests/models/Soft.php index 783cf0289..e34f1dbfb 100644 --- a/tests/models/Soft.php +++ b/tests/models/Soft.php @@ -1,8 +1,13 @@