Commit 3e2837b7 authored by jose miguel's avatar jose miguel

Merge branch 'master' of github.com:jenssegers/laravel-mongodb into paginating

parents 82757887 cdc6e1d6
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
github: jenssegers
open_collective: laravel-mongodb
......@@ -7,3 +7,4 @@ composer.lock
*.sublime-workspace
*.project
.idea/
.phpunit.result.cache
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
- cat Dockerfile
- docker-compose build --build-arg PHP_VERSION=${TRAVIS_PHP_VERSION}
- 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
ARG PHP_VERSION=7.2
ARG COMPOSER_VERSION=1.8
FROM composer:${COMPOSER_VERSION}
FROM php:${PHP_VERSION}-cli
RUN pecl install xdebug
RUN apt-get update && \
apt-get install -y autoconf pkg-config libssl-dev git zlib1g-dev
RUN pecl install mongodb && docker-php-ext-enable mongodb && \
docker-php-ext-install -j$(nproc) pdo pdo_mysql zip && docker-php-ext-enable xdebug
apt-get install -y autoconf pkg-config libssl-dev git libzip-dev zlib1g-dev && \
pecl install mongodb && docker-php-ext-enable mongodb && \
pecl install xdebug && docker-php-ext-enable xdebug && \
docker-php-ext-install -j$(nproc) pdo_mysql zip
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
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
ENV PATH="~/.composer/vendor/bin:./vendor/bin:${PATH}"
WORKDIR /code
......@@ -43,6 +43,9 @@ 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
6.0.x | 3.6.x
And add the service provider in `config/app.php`:
......@@ -63,8 +66,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);
});
```
......@@ -480,7 +485,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 +550,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**
......
{
"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"
]
}
}
}
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
......@@ -27,5 +26,7 @@ services:
mongodb:
container_name: mongodb
image: mongo
ports:
- 27017:27017
logging:
driver: none
......@@ -7,42 +7,46 @@
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
verbose="true"
>
stopOnFailure="false">
<testsuites>
<testsuite name="all">
<directory>tests/</directory>
<exclude>tests/MysqlRelationsTest.php</exclude>
</testsuite>
<testsuite name="schema">
<directory>tests/SchemaTest.php</directory>
<file>tests/SchemaTest.php</file>
</testsuite>
<testsuite name="seeder">
<directory>tests/SeederTest.php</directory>
<file>tests/SeederTest.php</file>
</testsuite>
<testsuite name="cache">
<directory>tests/CacheTest.php</directory>
<file>tests/CacheTest.php</file>
</testsuite>
<testsuite name="builder">
<directory>tests/QueryBuilderTest.php</directory>
<directory>tests/QueryTest.php</directory>
<file>tests/QueryBuilderTest.php</file>
<file>tests/QueryTest.php</file>
</testsuite>
<testsuite name="model">
<directory>tests/ModelTest.php</directory>
<directory>tests/RelationsTest.php</directory>
<file>tests/ModelTest.php</file>
<file>tests/RelationsTest.php</file>
</testsuite>
<testsuite name="relations">
<directory>tests/RelationsTest.php</directory>
<directory>tests/EmbeddedRelationsTest.php</directory>
<file>tests/RelationsTest.php</file>
<file>tests/EmbeddedRelationsTest.php</file>
</testsuite>
<testsuite name="mysqlrelations">
<directory>tests/RelationsTest.php</directory>
<directory>tests/MysqlRelationsTest.php</directory>
<file>tests/RelationsTest.php</file>
</testsuite>
<testsuite name="validation">
<directory>tests/ValidationTest.php</directory>
<file>tests/ValidationTest.php</file>
</testsuite>
</testsuites>
<php>
<env name="MONGO_HOST" value="mongodb"/>
<env name="MONGO_DATABASE" value="unittest"/>
<env name="MONGO_PORT" value="27017"/>
<env name="MYSQL_HOST" value="mysql"/>
<env name="MYSQL_DATABASE" value="unittest"/>
<env name="MYSQL_USERNAME" value="root"/>
<env name="QUEUE_CONNECTION" value="database"/>
</php>
</phpunit>
......@@ -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 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
$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');
......
......@@ -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'],
......
......@@ -8,7 +8,6 @@ class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{
/**
* Register the token repository implementation.
*
* @return void
*/
protected function registerTokenRepository()
......
......@@ -10,14 +10,12 @@ class Collection
{
/**
* The connection instance.
*
* @var Connection
*/
protected $connection;
/**
* The MongoCollection instance..
*
* @var MongoCollection
*/
protected $collection;
......@@ -34,9 +32,8 @@ class Collection
/**
* Handle dynamic method calls.
*
* @param string $method
* @param array $parameters
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
......
......@@ -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 @@ class Connection extends BaseConnection
/**
* 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 @@ class Connection extends BaseConnection
/**
* 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 @@ class Connection extends BaseConnection
/**
* Get the MongoDB database object.
*
* @return \MongoDB\Database
*/
public function getMongoDB()
......@@ -105,7 +99,6 @@ class Connection extends BaseConnection
/**
* return MongoDB object.
*
* @return \MongoDB\Client
*/
public function getMongoClient()
......@@ -113,12 +106,19 @@ class Connection extends BaseConnection
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 @@ class Connection extends BaseConnection
/**
* 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 @@ class Connection extends BaseConnection
/**
* 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 @@ class Connection extends BaseConnection
/**
* Create a DSN string from a configuration.
*
* @param array $config
* @param array $config
* @return string
*/
protected function getDsn(array $config)
......@@ -250,9 +246,8 @@ class Connection extends BaseConnection
/**
* 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)
......
......@@ -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 @@ class Builder extends EloquentBuilder
return 1;
}
return $this->query->update($this->addUpdatedAtColumn($values), $options);
return $this->toBase()->update($this->addUpdatedAtColumn($values), $options);
}
/**
......@@ -177,6 +176,29 @@ class Builder extends EloquentBuilder
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
*/
......
......@@ -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 @@ trait EmbedsRelations
// 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 @@ 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\EmbedsOne
*/
protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null)
......@@ -57,17 +55,17 @@ trait EmbedsRelations
// 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));
}
......
......@@ -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 @@ trait HybridRelations
/**
* 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 @@ trait HybridRelations
/**
* 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 @@ trait HybridRelations
/**
* 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 @@ trait HybridRelations
/**
* 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
/**
* 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
// 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 @@ trait HybridRelations
/**
* Get the relationship name of the belongs to many.
*
* @return string
*/
protected function guessBelongsToManyRelation()
......@@ -303,8 +293,8 @@ trait HybridRelations
{
if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) {
return new Builder($query);
} else {
return new EloquentBuilder($query);
}
return new EloquentBuilder($query);
}
}
......@@ -4,15 +4,16 @@ namespace Jenssegers\Mongodb\Eloquent;
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,36 +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)
......@@ -63,6 +59,8 @@ abstract class Model extends BaseModel
// Convert ObjectID to string.
if ($value instanceof ObjectID) {
return (string) $value;
} elseif ($value instanceof Binary) {
return (string) $value->getData();
}
return $value;
......@@ -204,6 +202,8 @@ abstract class Model extends BaseModel
foreach ($attributes as $key => &$value) {
if ($value instanceof ObjectID) {
$value = (string) $value;
} elseif ($value instanceof Binary) {
$value = (string) $value->getData();
}
}
......@@ -228,7 +228,7 @@ abstract class Model extends BaseModel
/**
* @inheritdoc
*/
protected function originalIsEquivalent($key, $current)
public function originalIsEquivalent($key, $current)
{
if (!array_key_exists($key, $this->original)) {
return false;
......@@ -262,8 +262,7 @@ abstract class Model extends BaseModel
/**
* Remove one or more fields.
*
* @param mixed $columns
* @param mixed $columns
* @return int
*/
public function drop($columns)
......@@ -308,9 +307,8 @@ abstract class Model extends BaseModel
/**
* 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)
......@@ -327,10 +325,9 @@ abstract class Model extends BaseModel
/**
* 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)
{
......@@ -352,9 +349,8 @@ abstract class Model extends BaseModel
/**
* 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)
{
......@@ -385,8 +381,7 @@ abstract class Model extends BaseModel
/**
* Set the parent relation.
*
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation
*/
public function setParentRelation(Relation $relation)
{
......@@ -395,7 +390,6 @@ abstract class Model extends BaseModel
/**
* Get the parent relation.
*
* @return \Illuminate\Database\Eloquent\Relations\Relation
*/
public function getParentRelation()
......@@ -431,7 +425,6 @@ abstract class Model extends BaseModel
/**
* Get the queueable relationships for the entity.
*
* @return array
*/
public function getQueueableRelations()
......@@ -445,13 +438,13 @@ abstract class Model extends BaseModel
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;
}
}
}
......@@ -461,7 +454,6 @@ abstract class Model extends BaseModel
/**
* Get loaded relations for the instance without parent.
*
* @return array
*/
protected function getRelationsWithoutParent()
......
......@@ -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 @@ trait QueriesRelationships
* @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 @@ trait QueriesRelationships
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 @@ trait QueriesRelationships
return $relation->getHasCompareKey();
}
return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKey();
return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKeyName();
}
/**
......@@ -166,4 +144,27 @@ trait QueriesRelationships
// 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.');
}
}
......@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb;
use DB;
use Illuminate\Queue\QueueServiceProvider;
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
......@@ -13,7 +14,7 @@ class MongodbQueueServiceProvider extends QueueServiceProvider
protected function registerFailedJobServices()
{
// Add compatible queue failer if mongodb is configured.
if (config('queue.failed.database') == 'mongodb') {
if (DB::connection(config('queue.failed.database'))->getDriverName() == 'mongodb') {
$this->app->singleton('queue.failer', function ($app) {
return new MongoFailedJobProvider($app['db'], config('queue.failed.database'), config('queue.failed.table'));
});
......
This diff is collapsed.
......@@ -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 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/**
* Get a list of all of the failed jobs.
*
* @return object[]
*/
public function all()
......@@ -42,14 +39,17 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/**
* Get a single failed job.
*
* @param mixed $id
* @param mixed $id
* @return object
*/
public function find($id)
{
$job = $this->getTable()->find($id);
if (!$job) {
return;
}
$job['id'] = (string) $job['_id'];
return (object) $job;
......@@ -57,8 +57,7 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/**
* Delete a single failed job from storage.
*
* @param mixed $id
* @param mixed $id
* @return bool
*/
public function forget($id)
......
......@@ -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 @@ class MongoConnector implements ConnectorInterface
/**
* Establish a queue connection.
*
* @param array $config
* @param array $config
* @return \Illuminate\Contracts\Queue\Queue
*/
public function connect(array $config)
......
......@@ -8,7 +8,6 @@ class MongoJob extends DatabaseJob
{
/**
* Indicates if the job has been reserved.
*
* @return bool
*/
public function isReserved()
......
......@@ -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 @@ class MongoQueue extends DatabaseQueue
{
$queue = $this->getQueue($queue);
if (!is_null($this->retryAfter)) {
if ($this->retryAfter !== null) {
$this->releaseJobsThatHaveBeenReservedTooLong($queue);
}
......@@ -52,17 +50,13 @@ class MongoQueue extends DatabaseQueue
/**
* 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)
......@@ -70,7 +64,7 @@ class MongoQueue extends DatabaseQueue
$job = $this->database->getCollection($this->table)->findOneAndUpdate(
[
'queue' => $this->getQueue($queue),
'reserved' => 0,
'reserved' => ['$ne' => 1],
'available_at' => ['$lte' => Carbon::now()->getTimestamp()],
],
[
......@@ -78,6 +72,9 @@ class MongoQueue extends DatabaseQueue
'reserved' => 1,
'reserved_at' => Carbon::now()->getTimestamp(),
],
'$inc' => [
'attempts' => 1,
],
],
[
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
......@@ -94,39 +91,28 @@ class MongoQueue extends DatabaseQueue
/**
* Release the jobs that have been reserved for too long.
*
* @param string $queue
* @param string $queue
* @return void
*/
protected function releaseJobsThatHaveBeenReservedTooLong($queue)
{
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$now = time();
$reserved = $this->database->collection($this->table)
->where('queue', $this->getQueue($queue))
->where(function ($query) use ($expiration, $now) {
// Check for available jobs
$query->where(function ($query) use ($now) {
$query->whereNull('reserved_at');
$query->where('available_at', '<=', $now);
});
// Check for jobs that are reserved but have expired
$query->orWhere('reserved_at', '<=', $expiration);
})->get();
->whereNotNull('reserved_at')
->where('reserved_at', '<=', $expiration)
->get();
foreach ($reserved as $job) {
$attempts = $job['attempts'] + 1;
$this->releaseJob($job['_id'], $attempts);
$this->releaseJob($job['_id'], $job['attempts']);
}
}
/**
* 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)
......
......@@ -9,7 +9,6 @@ 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()
......@@ -53,7 +52,6 @@ class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo
/**
* Get the owner key with backwards compatible support.
*
* @return string
*/
public function getOwnerKey()
......@@ -63,9 +61,8 @@ class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -5,15 +5,14 @@ namespace Jenssegers\Mongodb\Relations;
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;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class BelongsToMany extends EloquentBelongsToMany
{
/**
* Get the key for comparing against the parent key in "has" query.
*
* @return string
*/
public function getHasCompareKey()
......@@ -39,8 +38,7 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Set the select clause for the relation query.
*
* @param array $columns
* @param array $columns
* @return array
*/
protected function getSelectColumns(array $columns = ['*'])
......@@ -68,7 +66,6 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Set the where clause for the relation query.
*
* @return $this
*/
protected function setWhere()
......@@ -275,7 +272,6 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Create a new query builder for the related model.
*
* @return \Illuminate\Database\Query\Builder
*/
public function newRelatedQuery()
......@@ -285,7 +281,6 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Get the fully qualified foreign key for the relation.
*
* @return string
*/
public function getForeignKey()
......@@ -312,10 +307,9 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* 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)
{
......@@ -331,7 +325,6 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Get the related key with backwards compatible support.
*
* @return string
*/
public function getRelatedKey()
......@@ -341,9 +334,8 @@ class BelongsToMany extends EloquentBelongsToMany
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -4,10 +4,10 @@ namespace Jenssegers\Mongodb\Relations;
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;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class EmbedsMany extends EmbedsOneOrMany
{
......@@ -33,8 +33,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* 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)
......@@ -63,8 +62,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* 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)
......@@ -95,8 +93,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Delete an existing model and detach it from the parent model.
*
* @param Model $model
* @param Model $model
* @return int
*/
public function performDelete(Model $model)
......@@ -122,23 +119,21 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* 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 = [])
......@@ -166,8 +161,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Destroy the embedded models for the given IDs.
*
* @param mixed $ids
* @param mixed $ids
* @return int
*/
public function destroy($ids = [])
......@@ -191,7 +185,6 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Delete all embedded models.
*
* @return int
*/
public function delete()
......@@ -208,8 +201,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Destroy alias.
*
* @param mixed $ids
* @param mixed $ids
* @return int
*/
public function detach($ids = [])
......@@ -219,8 +211,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Save alias.
*
* @param Model $model
* @param Model $model
* @return Model
*/
public function attach(Model $model)
......@@ -230,14 +221,13 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* 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);
}
......@@ -251,8 +241,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* 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)
......@@ -277,8 +266,7 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Get a paginator for the "select" statement.
*
* @param int $perPage
* @param int $perPage
* @return \Illuminate\Pagination\AbstractPaginator
*/
public function paginate($perPage = null)
......@@ -332,9 +320,8 @@ class EmbedsMany extends EmbedsOneOrMany
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -3,8 +3,8 @@
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model;
use MongoDB\BSON\ObjectID;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use MongoDB\BSON\ObjectID;
class EmbedsOne extends EmbedsOneOrMany
{
......@@ -30,8 +30,7 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* 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)
......@@ -59,8 +58,7 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* 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)
......@@ -85,7 +83,6 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* Delete an existing model and detach it from the parent model.
*
* @return int
*/
public function performDelete()
......@@ -109,8 +106,7 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* Attach the model to its parent.
*
* @param Model $model
* @param Model $model
* @return Model
*/
public function associate(Model $model)
......@@ -120,7 +116,6 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* Detach the model from its parent.
*
* @return Model
*/
public function dissociate()
......@@ -130,7 +125,6 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* Delete all embedded models.
*
* @return int
*/
public function delete()
......@@ -140,9 +134,8 @@ class EmbedsOne extends EmbedsOneOrMany
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -4,42 +4,38 @@ namespace Jenssegers\Mongodb\Relations;
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;
use Illuminate\Database\Eloquent\Model as EloquentModel;
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)
{
......@@ -94,9 +90,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Shorthand to get the results of the relationship.
*
* @param array $columns
*
* @param array $columns
* @return Collection
*/
public function get($columns = ['*'])
......@@ -106,7 +100,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the number of embedded models.
*
* @return int
*/
public function count()
......@@ -116,8 +109,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Attach a model instance to the parent model.
*
* @param Model $model
* @param Model $model
* @return Model|bool
*/
public function save(Model $model)
......@@ -129,8 +121,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Attach a collection of models to the parent instance.
*
* @param Collection|array $models
* @param Collection|array $models
* @return Collection|array
*/
public function saveMany($models)
......@@ -144,8 +135,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Create a new instance of the related model.
*
* @param array $attributes
* @param array $attributes
* @return Model
*/
public function create(array $attributes = [])
......@@ -164,8 +154,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Create an array of new instances of the related model.
*
* @param array $records
* @param array $records
* @return array
*/
public function createMany(array $records)
......@@ -181,8 +170,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* 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)
......@@ -236,8 +224,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the foreign key value for the relation.
*
* @param mixed $id
* @param mixed $id
* @return mixed
*/
protected function getForeignKeyValue($id)
......@@ -252,8 +239,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Convert an array of records to a Collection.
*
* @param array $records
* @param array $records
* @return Collection
*/
protected function toCollection(array $records = [])
......@@ -273,13 +259,12 @@ abstract class EmbedsOneOrMany extends Relation
/**
* 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;
}
......@@ -302,7 +287,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the relation instance of the parent.
*
* @return Relation
*/
protected function getParentRelation()
......@@ -332,7 +316,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Check if this relation is nested in another relation.
*
* @return bool
*/
protected function isNested()
......@@ -342,8 +325,7 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the fully qualified local key name.
*
* @param string $glue
* @param string $glue
* @return string
*/
protected function getPathHierarchy($glue = '.')
......@@ -369,7 +351,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the primary key value of the parent.
*
* @return string
*/
protected function getParentKey()
......@@ -379,7 +360,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Return update values
*
* @param $array
* @param string $prepend
* @return array
......@@ -389,7 +369,7 @@ abstract class EmbedsOneOrMany extends Relation
$results = [];
foreach ($array as $key => $value) {
$results[$prepend.$key] = $value;
$results[$prepend . $key] = $value;
}
return $results;
......@@ -397,7 +377,6 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the foreign key for the relationship.
*
* @return string
*/
public function getQualifiedForeignKeyName()
......@@ -407,9 +386,8 @@ abstract class EmbedsOneOrMany extends Relation
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -3,14 +3,13 @@
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany;
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()
......@@ -20,7 +19,6 @@ class HasMany extends EloquentHasMany
/**
* Get the plain foreign key.
*
* @return string
*/
public function getPlainForeignKey()
......@@ -30,7 +28,6 @@ class HasMany extends EloquentHasMany
/**
* Get the key for comparing against the parent key in "has" query.
*
* @return string
*/
public function getHasCompareKey()
......@@ -50,9 +47,8 @@ class HasMany extends EloquentHasMany
/**
* 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)
......@@ -64,10 +60,9 @@ class HasMany extends EloquentHasMany
/**
* 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 = ['*'])
......@@ -81,9 +76,8 @@ class HasMany extends EloquentHasMany
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -3,14 +3,13 @@
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne;
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()
......@@ -20,7 +19,6 @@ class HasOne extends EloquentHasOne
/**
* Get the key for comparing against the parent key in "has" query.
*
* @return string
*/
public function getHasCompareKey()
......@@ -30,7 +28,6 @@ class HasOne extends EloquentHasOne
/**
* Get the plain foreign key.
*
* @return string
*/
public function getPlainForeignKey()
......@@ -50,9 +47,8 @@ class HasOne extends EloquentHasOne
/**
* 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)
......@@ -64,10 +60,9 @@ class HasOne extends EloquentHasOne
/**
* 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 = ['*'])
......@@ -78,12 +73,11 @@ class HasOne extends EloquentHasOne
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
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -2,8 +2,8 @@
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo;
class MorphTo extends EloquentMorphTo
{
......@@ -36,7 +36,6 @@ class MorphTo extends EloquentMorphTo
/**
* Get the owner key with backwards compatible support.
*
* @return string
*/
public function getOwnerKey()
......@@ -46,9 +45,8 @@ class MorphTo extends EloquentMorphTo
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
......
......@@ -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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
* @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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
$transform[$column] = $column . '_1';
}
$indexOrColumns = join('_', $transform);
$indexOrColumns = implode('_', $transform);
}
$this->collection->dropIndex($indexOrColumns);
return $this;
return $indexOrColumns;
}
/**
......@@ -112,8 +154,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* 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 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/**
* Allows the use of unsupported schema methods.
*
* @param $method
* @param $args
* @return Blueprint
......
......@@ -33,8 +33,7 @@ class Builder extends \Illuminate\Database\Schema\Builder
/**
* Determine if the given collection exists.
*
* @param string $collection
* @param string $collection
* @return bool
*/
public function hasCollection($collection)
......@@ -60,9 +59,8 @@ class Builder extends \Illuminate\Database\Schema\Builder
/**
* 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 @@ class Builder extends \Illuminate\Database\Schema\Builder
/**
* @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 @@ class Builder extends \Illuminate\Database\Schema\Builder
/**
* Get all of the collections names for the database.
*
* @return array
*/
protected function getAllCollections()
......
......@@ -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 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe
/**
* 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 = [])
......
......@@ -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 @@ class AuthTest extends TestCase
public function testAuthAttempt()
{
$user = User::create([
'name' => 'John Doe',
'email' => 'john@doe.com',
'name' => 'John Doe',
'email' => 'john@doe.com',
'password' => Hash::make('foobar'),
]);
......@@ -26,6 +28,7 @@ class AuthTest extends TestCase
public function testRemindOld()
{
if (Application::VERSION >= '5.2') {
$this->expectNotToPerformAssertions();
return;
}
......@@ -36,8 +39,8 @@ class AuthTest extends TestCase
$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 +51,13 @@ class AuthTest extends TestCase
$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) {
......
<?php
declare(strict_types=1);
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Collection;
use MongoDB\Collection as MongoCollection;
use Jenssegers\Mongodb\Connection;
use MongoDB\BSON\ObjectID;
use MongoDB\Collection as MongoCollection;
class CollectionTest extends TestCase
{
......
<?php
declare(strict_types=1);
use Illuminate\Support\Facades\DB;
class ConnectionTest extends TestCase
{
public function testConnection()
{
$connection = DB::connection('mongodb');
$this->assertInstanceOf('Jenssegers\Mongodb\Connection', $connection);
$this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $connection);
}
public function testReconnect()
......@@ -23,28 +26,28 @@ class ConnectionTest extends TestCase
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 @@ class ConnectionTest extends TestCase
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()
......
<?php
declare(strict_types=1);
class DsnTest extends TestCase
{
......
This diff is collapsed.
<?php
declare(strict_types=1);
class GeospatialTest extends TestCase
{
public function setUp()
public function setUp(): void
{
parent::setUp();
......@@ -43,7 +44,7 @@ class GeospatialTest extends TestCase
]);
}
public function tearDown()
public function tearDown(): void
{
Schema::drop('locations');
}
......@@ -53,28 +54,30 @@ class GeospatialTest extends TestCase
$locations = Location::where('location', 'geoWithin', [
'$geometry' => [
'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 @@ class GeospatialTest extends TestCase
51.5078646,
],
],
]
],
]);
$this->assertEquals(1, $locations->count());
......
<?php
declare(strict_types=1);
use Illuminate\Database\MySqlConnection;
class HybridRelationsTest extends TestCase
{
public function setUp()
public function setUp(): void
{
parent::setUp();
......@@ -11,7 +14,7 @@ class HybridRelationsTest extends TestCase
MysqlRole::executeSchema();
}
public function tearDown()
public function tearDown(): void
{
MysqlUser::truncate();
MysqlBook::truncate();
......@@ -21,13 +24,13 @@ class HybridRelationsTest extends TestCase
public function testMysqlRelations()
{
$user = new MysqlUser;
$this->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 @@ class HybridRelationsTest extends TestCase
{
$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 @@ class HybridRelationsTest extends TestCase
$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 @@ class HybridRelationsTest extends TestCase
{
$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 @@ class HybridRelationsTest extends TestCase
$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();
......
This diff is collapsed.
This diff is collapsed.
<?php
declare(strict_types=1);
class QueryTest extends TestCase
{
protected static $started = false;
public function setUp()
public function setUp(): void
{
parent::setUp();
User::create(['name' => 'John Doe', 'age' => 35, 'title' => 'admin']);
......@@ -18,13 +19,14 @@ class QueryTest extends TestCase
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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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 @@ class QueryTest extends TestCase
$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());
}
}
<?php
declare(strict_types=1);
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
class QueueTest extends TestCase
{
public function setUp()
public function setUp(): void
{
parent::setUp();
......@@ -11,7 +14,7 @@ class QueueTest extends TestCase
Queue::getDatabase()->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 +27,7 @@ class QueueTest extends TestCase
'displayName' => 'test',
'job' => 'test',
'maxTries' => null,
'delay' => null,
'timeout' => null,
'data' => ['action' => 'QueueJobLifeCycle'],
]), $job->getRawBody());
......@@ -33,7 +37,7 @@ class QueueTest extends TestCase
$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);
......@@ -53,4 +57,38 @@ class QueueTest extends TestCase
$job->delete();
$this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count());
}
public function testFailQueueJob(): void
{
$provider = app('queue.failer');
$this->assertInstanceOf(MongoFailedJobProvider::class, $provider);
}
public function testFindFailJobNull(): void
{
Config::set('queue.failed.database', 'mongodb');
$provider = app('queue.failer');
$this->assertNull($provider->find(1));
}
public function testIncrementAttempts(): void
{
$job_id = Queue::push('test1', ['action' => 'QueueJobExpired'], 'test');
$this->assertNotNull($job_id);
$job_id = Queue::push('test2', ['action' => 'QueueJobExpired'], 'test');
$this->assertNotNull($job_id);
$job = Queue::pop('test');
$this->assertEquals(1, $job->attempts());
$job->delete();
$others_jobs = Queue::getDatabase()
->table(Config::get('queue.connections.database.table'))
->get();
$this->assertCount(1, $others_jobs);
$this->assertEquals(0, $others_jobs[0]['attempts']);
}
}
This diff is collapsed.
<?php
declare(strict_types=1);
use Jenssegers\Mongodb\Schema\Blueprint;
class SchemaTest extends TestCase
{
public function tearDown()
public function tearDown(): void
{
Schema::drop('newcollection');
Schema::drop('newcollection_two');
}
public function testCreate()
public function testCreate(): void
{
Schema::create('newcollection');
$this->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 @@ class SchemaTest extends TestCase
$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 @@ class SchemaTest extends TestCase
$this->assertEquals(1, $index['unique']);
}
public function testUnique()
public function testUnique(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->unique('uniquekey');
......@@ -89,7 +100,7 @@ class SchemaTest extends TestCase
$this->assertEquals(1, $index['unique']);
}
public function testDropIndex()
public function testDropIndex(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->unique('uniquekey');
......@@ -136,7 +147,77 @@ class SchemaTest extends TestCase
$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 @@ class SchemaTest extends TestCase
$this->assertEquals(1, $index['background']);
}
public function testSparse()
public function testSparse(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->sparse('sparsekey');
......@@ -156,7 +237,7 @@ class SchemaTest extends TestCase
$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 @@ class SchemaTest extends TestCase
$this->assertEquals(60, $index['expireAfterSeconds']);
}
public function testSoftDeletes()
public function testSoftDeletes(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->softDeletes();
......@@ -180,7 +261,7 @@ class SchemaTest extends TestCase
$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 @@ class SchemaTest extends TestCase
$this->assertEquals(1, $index['key']['token']);
}
public function testGeospatial()
public function testGeospatial(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->geospatial('point');
......@@ -213,15 +294,16 @@ class SchemaTest extends TestCase
$this->assertEquals('2dsphere', $index['key']['continent']);
}
public function testDummies()
public function testDummies(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->boolean('activated')->default(0);
$collection->integer('user_id')->unsigned();
});
$this->expectNotToPerformAssertions();
}
public function testSparseUnique()
public function testSparseUnique(): void
{
Schema::collection('newcollection', function ($collection) {
$collection->sparse_and_unique('sparseuniquekey');
......@@ -232,7 +314,7 @@ class SchemaTest extends TestCase
$this->assertEquals(1, $index['unique']);
}
protected function getIndex($collection, $name)
protected function getIndex(string $collection, string $name)
{
$collection = DB::getCollection($collection);
......
<?php
declare(strict_types=1);
class SeederTest extends TestCase
{
public function tearDown()
public function tearDown(): void
{
User::truncate();
}
public function testSeed()
public function testSeed(): void
{
$seeder = new UserTableSeeder;
$seeder->run();
......@@ -16,7 +17,7 @@ class SeederTest extends TestCase
$this->assertTrue($user->seed);
}
public function testArtisan()
public function testArtisan(): void
{
Artisan::call('db:seed');
......
<?php
declare(strict_types=1);
use Illuminate\Auth\Passwords\PasswordResetServiceProvider;
class TestCase extends Orchestra\Testbench\TestCase
{
/**
* Get application providers.
*
* @param \Illuminate\Foundation\Application $app
*
* @param \Illuminate\Foundation\Application $app
* @return array
*/
protected function getApplicationProviders($app)
{
$providers = parent::getApplicationProviders($app);
unset($providers[array_search('Illuminate\Auth\Passwords\PasswordResetServiceProvider', $providers)]);
unset($providers[array_search(PasswordResetServiceProvider::class, $providers)]);
return $providers;
}
/**
* Get package providers.
*
* @param \Illuminate\Foundation\Application $app
* @param \Illuminate\Foundation\Application $app
* @return array
*/
protected function getPackageProviders($app)
{
return [
Jenssegers\Mongodb\MongodbServiceProvider::class,
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class,
Jenssegers\Mongodb\Validation\ValidationServiceProvider::class
Jenssegers\Mongodb\Validation\ValidationServiceProvider::class,
];
}
/**
* Define environment setup.
*
* @param Illuminate\Foundation\Application $app
* @param Illuminate\Foundation\Application $app
* @return void
*/
protected function getEnvironmentSetUp($app)
......@@ -51,6 +51,7 @@ class TestCase extends Orchestra\Testbench\TestCase
$app['config']->set('database.default', 'mongodb');
$app['config']->set('database.connections.mysql', $config['connections']['mysql']);
$app['config']->set('database.connections.mongodb', $config['connections']['mongodb']);
$app['config']->set('database.connections.mongodb2', $config['connections']['mongodb']);
$app['config']->set('database.connections.dsn_mongodb', $config['connections']['dsn_mongodb']);
$app['config']->set('auth.model', 'User');
......@@ -60,9 +61,10 @@ class TestCase extends Orchestra\Testbench\TestCase
$app['config']->set('queue.default', 'database');
$app['config']->set('queue.connections.database', [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
]);
$app['config']->set('queue.failed.database', 'mongodb2');
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment