Unverified Commit 1ffc7a27 authored by Divine's avatar Divine Committed by GitHub

Merge branch 'pr_1491' into pr/17

parents 929120f1 4d81b402
exclude_paths:
- '.github/**'
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
---
name: "Bug report"
about: 'Report errors or unexpected behavior.'
---
- Laravel-mongodb Version: #.#.#
- PHP Version: #.#.#
- Database Driver & Version:
### Description:
### Steps to reproduce
1.
2.
3.
### Expected behaviour
Tell us what should happen
### Actual behaviour
Tell us what happens instead
<details><summary><b>Logs</b>:</summary>
Insert log.txt here (if necessary)
</details>
---
name: Feature request
about: Suggest an idea.
title: "[Feature Request] "
---
### Is your feature request related to a problem?
A clear and concise description of what the problem is.
### Describe the solution you'd like
A clear and concise description of what you want to happen.
### Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
### Additional context
Add any other context or screenshots about the feature request here.
---
name: Question
about: Ask a question.
title: "[Question] "
labels: 'question'
assignees: ''
---
name: CI
on:
push:
branches:
tags:
pull_request:
jobs:
build:
runs-on: ${{matrix.os}}
strategy:
matrix:
php: ['7.1', '7.2', '7.3', '7.4']
os: ['ubuntu-latest']
mongodb: ['3.6', '4.0', '4.2']
services:
mongo:
image: mongo:${{ matrix.mongodb }}
ports:
- 27017:27017
mysql:
image: mysql:5.7
ports:
- 3307:3306
env:
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
MYSQL_DATABASE: 'unittest'
MYSQL_ROOT_PASSWORD:
name: PHP v${{ matrix.php }} with Mongo v${{ matrix.mongodb }}
steps:
- uses: actions/checkout@v1
- name: Show PHP version
run: php${{ matrix.php }} -v && composer -V
- name: Show Docker version
run: if [[ "$DEBUG" == "true" ]]; then docker version && env; fi
env:
DEBUG: ${{secrets.DEBUG}}
- name: Download Composer cache dependencies from cache
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache Composer dependencies
uses: actions/cache@v1
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ matrix.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ matrix.os }}-composer-
- name: Install dependencies
run: |
composer install --no-interaction
- name: Run tests
run: |
./vendor/bin/phpunit --coverage-clover coverage.xml
env:
MONGO_HOST: 0.0.0.0
MYSQL_HOST: 0.0.0.0
MYSQL_PORT: 3307
- name: Send coveralls
run: vendor/bin/coveralls coverage.xml
env:
COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: false
...@@ -7,3 +7,4 @@ composer.lock ...@@ -7,3 +7,4 @@ composer.lock
*.sublime-workspace *.sublime-workspace
*.project *.project
.idea/ .idea/
.phpunit.result.cache
preset: laravel
sudo: required
dist: trusty
language: php
php:
- "7.2"
- "7.1"
services:
- docker
install:
# Update docker-engine using Ubuntu 'trusty' apt repo
- >
curl -sSL "https://get.docker.com/gpg" |
sudo -E apt-key add -
- >
echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" |
sudo tee -a /etc/apt/sources.list
- sudo apt-get update
- >
sudo apt-get -o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" --assume-yes install docker-engine --allow-unauthenticated
- docker version
# Update docker-compose via pip
- sudo pip install docker-compose
- docker-compose version
- docker-compose up --build -d
- docker ps -a
script:
- docker-compose up --exit-code-from php
ARG PHP_VERSION=7.2
ARG COMPOSER_VERSION=1.8
FROM composer:${COMPOSER_VERSION}
FROM php:${PHP_VERSION}-cli
RUN apt-get update && \
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
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
WORKDIR /code
This diff is collapsed.
{ {
"name": "jenssegers/mongodb", "name": "jenssegers/mongodb",
"description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)",
"keywords": ["laravel","eloquent","mongodb","mongo","database","model","moloquent"], "keywords": [
"laravel",
"eloquent",
"mongodb",
"mongo",
"database",
"model",
"moloquent"
],
"homepage": "https://github.com/jenssegers/laravel-mongodb", "homepage": "https://github.com/jenssegers/laravel-mongodb",
"authors": [ "authors": [
{ {
...@@ -9,20 +17,21 @@ ...@@ -9,20 +17,21 @@
"homepage": "https://jenssegers.com" "homepage": "https://jenssegers.com"
} }
], ],
"license" : "MIT", "license": "MIT",
"require": { "require": {
"illuminate/support": "^5.6", "illuminate/support": "^5.8|^6.0",
"illuminate/container": "^5.6", "illuminate/container": "^5.8|^6.0",
"illuminate/database": "^5.6", "illuminate/database": "^5.8|^6.0",
"illuminate/events": "^5.6", "illuminate/events": "^5.8|^6.0",
"mongodb/mongodb": "^1.0.0" "mongodb/mongodb": "^1.4",
"cedx/coveralls": "^11.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.0|^7.0", "phpunit/phpunit": "^6.0|^7.0|^8.0",
"orchestra/testbench": "^3.1", "orchestra/testbench": "^3.1|^4.0",
"mockery/mockery": "^1.0", "mockery/mockery": "^1.0",
"satooshi/php-coveralls": "^2.0", "doctrine/dbal": "^2.5",
"doctrine/dbal": "^2.5" "phpunit/phpcov": "^6.0"
}, },
"autoload": { "autoload": {
"psr-0": { "psr-0": {
......
version: '3' version: '3'
services: services:
tests:
php: container_name: tests
container_name: php
build: build:
context: . context: .
dockerfile: docker/Dockerfile dockerfile: Dockerfile
volumes: volumes:
- .:/code - .:/code
working_dir: /code working_dir: /code
command: docker/entrypoint.sh
depends_on: depends_on:
- mysql
- mongodb - mongodb
- mysql
mysql: mysql:
container_name: mysql container_name: mysql
image: mysql image: mysql:5.7
environment: environment:
MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD:
MYSQL_DATABASE: unittest MYSQL_DATABASE: unittest
...@@ -28,5 +26,7 @@ services: ...@@ -28,5 +26,7 @@ services:
mongodb: mongodb:
container_name: mongodb container_name: mongodb
image: mongo image: mongo
ports:
- 27017:27017
logging: logging:
driver: none driver: none
FROM php:7.1-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}"
\ No newline at end of file
#!/usr/bin/env bash
sleep 3 && composer install --prefer-source --no-interaction && php ./vendor/bin/phpunit
...@@ -7,42 +7,52 @@ ...@@ -7,42 +7,52 @@
convertNoticesToExceptions="true" convertNoticesToExceptions="true"
convertWarningsToExceptions="true" convertWarningsToExceptions="true"
processIsolation="false" processIsolation="false"
stopOnFailure="false" stopOnFailure="false">
syntaxCheck="false"
verbose="true"
>
<testsuites> <testsuites>
<testsuite name="all"> <testsuite name="all">
<directory>tests/</directory> <directory>tests/</directory>
<exclude>tests/MysqlRelationsTest.php</exclude>
</testsuite> </testsuite>
<testsuite name="schema"> <testsuite name="schema">
<directory>tests/SchemaTest.php</directory> <file>tests/SchemaTest.php</file>
</testsuite> </testsuite>
<testsuite name="seeder"> <testsuite name="seeder">
<directory>tests/SeederTest.php</directory> <file>tests/SeederTest.php</file>
</testsuite> </testsuite>
<testsuite name="cache"> <testsuite name="cache">
<directory>tests/CacheTest.php</directory> <file>tests/CacheTest.php</file>
</testsuite> </testsuite>
<testsuite name="builder"> <testsuite name="builder">
<directory>tests/QueryBuilderTest.php</directory> <file>tests/QueryBuilderTest.php</file>
<directory>tests/QueryTest.php</directory> <file>tests/QueryTest.php</file>
</testsuite> </testsuite>
<testsuite name="model"> <testsuite name="model">
<directory>tests/ModelTest.php</directory> <file>tests/ModelTest.php</file>
<directory>tests/RelationsTest.php</directory> <file>tests/RelationsTest.php</file>
</testsuite> </testsuite>
<testsuite name="relations"> <testsuite name="relations">
<directory>tests/RelationsTest.php</directory> <file>tests/RelationsTest.php</file>
<directory>tests/EmbeddedRelationsTest.php</directory> <file>tests/EmbeddedRelationsTest.php</file>
</testsuite> </testsuite>
<testsuite name="mysqlrelations"> <testsuite name="mysqlrelations">
<directory>tests/RelationsTest.php</directory> <file>tests/RelationsTest.php</file>
<directory>tests/MysqlRelationsTest.php</directory>
</testsuite> </testsuite>
<testsuite name="validation"> <testsuite name="validation">
<directory>tests/ValidationTest.php</directory> <file>tests/ValidationTest.php</file>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<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_PORT" value="3306"/>
<env name="MYSQL_DATABASE" value="unittest"/>
<env name="MYSQL_USERNAME" value="root"/>
<env name="QUEUE_CONNECTION" value="database"/>
</php>
</phpunit> </phpunit>
...@@ -14,25 +14,46 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -14,25 +14,46 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
*/ */
protected function getPayload($email, $token) protected function getPayload($email, $token)
{ {
return ['email' => $email, 'token' => $token, 'created_at' => new UTCDateTime(time() * 1000)]; return [
'email' => $email,
'token' => $this->hasher->make($token),
'created_at' => new UTCDateTime(time() * 1000),
];
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
protected function tokenExpired($token) protected function tokenExpired($createdAt)
{
$createdAt = $this->convertDateTime($createdAt);
return parent::tokenExpired($createdAt);
}
/**
* @inheritdoc
*/
protected function tokenRecentlyCreated($createdAt)
{
$createdAt = $this->convertDateTime($createdAt);
return parent::tokenRecentlyCreated($createdAt);
}
private function convertDateTime($createdAt)
{ {
// Convert UTCDateTime to a date string. // Convert UTCDateTime to a date string.
if ($token['created_at'] instanceof UTCDateTime) { if ($createdAt instanceof UTCDateTime) {
$date = $token['created_at']->toDateTime(); $date = $createdAt->toDateTime();
$date->setTimezone(new DateTimeZone(date_default_timezone_get())); $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$token['created_at'] = $date->format('Y-m-d H:i:s'); $createdAt = $date->format('Y-m-d H:i:s');
} elseif (is_array($token['created_at']) && isset($token['created_at']['date'])) { } elseif (is_array($createdAt) && isset($createdAt['date'])) {
$date = new DateTime($token['created_at']['date'], new DateTimeZone(isset($token['created_at']['timezone']) ? $token['created_at']['timezone'] : 'UTC')); $date = new DateTime($createdAt['date'], new DateTimeZone(isset($createdAt['timezone']) ? $createdAt['timezone'] : 'UTC'));
$date->setTimezone(new DateTimeZone(date_default_timezone_get())); $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
$token['created_at'] = $date->format('Y-m-d H:i:s'); $createdAt = $date->format('Y-m-d H:i:s');
} }
return parent::tokenExpired($token); return $createdAt;
} }
} }
...@@ -11,9 +11,6 @@ class PasswordBrokerManager extends BasePasswordBrokerManager ...@@ -11,9 +11,6 @@ class PasswordBrokerManager extends BasePasswordBrokerManager
*/ */
protected function createTokenRepository(array $config) protected function createTokenRepository(array $config)
{ {
$laravel = app();
if (version_compare($laravel::VERSION, '5.4', '>=')) {
return new DatabaseTokenRepository( return new DatabaseTokenRepository(
$this->app['db']->connection(), $this->app['db']->connection(),
$this->app['hash'], $this->app['hash'],
...@@ -21,13 +18,5 @@ class PasswordBrokerManager extends BasePasswordBrokerManager ...@@ -21,13 +18,5 @@ class PasswordBrokerManager extends BasePasswordBrokerManager
$this->app['config']['app.key'], $this->app['config']['app.key'],
$config['expire'] $config['expire']
); );
} else {
return new DatabaseTokenRepository(
$this->app['db']->connection(),
$config['table'],
$this->app['config']['app.key'],
$config['expire']
);
}
} }
} }
...@@ -8,7 +8,6 @@ class PasswordResetServiceProvider extends BasePasswordResetServiceProvider ...@@ -8,7 +8,6 @@ class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{ {
/** /**
* Register the token repository implementation. * Register the token repository implementation.
*
* @return void * @return void
*/ */
protected function registerTokenRepository() protected function registerTokenRepository()
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace Jenssegers\Mongodb\Auth; namespace Jenssegers\Mongodb\Auth;
use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
...@@ -15,5 +16,5 @@ class User extends Model implements ...@@ -15,5 +16,5 @@ class User extends Model implements
AuthorizableContract, AuthorizableContract,
CanResetPasswordContract CanResetPasswordContract
{ {
use Authenticatable, Authorizable, CanResetPassword; use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
} }
...@@ -10,14 +10,12 @@ class Collection ...@@ -10,14 +10,12 @@ class Collection
{ {
/** /**
* The connection instance. * The connection instance.
*
* @var Connection * @var Connection
*/ */
protected $connection; protected $connection;
/** /**
* The MongoCollection instance.. * The MongoCollection instance..
*
* @var MongoCollection * @var MongoCollection
*/ */
protected $collection; protected $collection;
...@@ -34,7 +32,6 @@ class Collection ...@@ -34,7 +32,6 @@ class Collection
/** /**
* Handle dynamic method calls. * Handle dynamic method calls.
*
* @param string $method * @param string $method
* @param array $parameters * @param array $parameters
* @return mixed * @return mixed
......
...@@ -10,21 +10,18 @@ class Connection extends BaseConnection ...@@ -10,21 +10,18 @@ class Connection extends BaseConnection
{ {
/** /**
* The MongoDB database handler. * The MongoDB database handler.
*
* @var \MongoDB\Database * @var \MongoDB\Database
*/ */
protected $db; protected $db;
/** /**
* The MongoDB connection handler. * The MongoDB connection handler.
*
* @var \MongoDB\Client * @var \MongoDB\Client
*/ */
protected $connection; protected $connection;
/** /**
* Create a new database connection instance. * Create a new database connection instance.
*
* @param array $config * @param array $config
*/ */
public function __construct(array $config) public function __construct(array $config)
...@@ -52,7 +49,6 @@ class Connection extends BaseConnection ...@@ -52,7 +49,6 @@ class Connection extends BaseConnection
/** /**
* Begin a fluent query against a database collection. * Begin a fluent query against a database collection.
*
* @param string $collection * @param string $collection
* @return Query\Builder * @return Query\Builder
*/ */
...@@ -65,18 +61,17 @@ class Connection extends BaseConnection ...@@ -65,18 +61,17 @@ class Connection extends BaseConnection
/** /**
* Begin a fluent query against a database collection. * Begin a fluent query against a database collection.
*
* @param string $table * @param string $table
* @param string|null $as
* @return Query\Builder * @return Query\Builder
*/ */
public function table($table) public function table($table, $as = null)
{ {
return $this->collection($table); return $this->collection($table);
} }
/** /**
* Get a MongoDB collection. * Get a MongoDB collection.
*
* @param string $name * @param string $name
* @return Collection * @return Collection
*/ */
...@@ -95,7 +90,6 @@ class Connection extends BaseConnection ...@@ -95,7 +90,6 @@ class Connection extends BaseConnection
/** /**
* Get the MongoDB database object. * Get the MongoDB database object.
*
* @return \MongoDB\Database * @return \MongoDB\Database
*/ */
public function getMongoDB() public function getMongoDB()
...@@ -105,7 +99,6 @@ class Connection extends BaseConnection ...@@ -105,7 +99,6 @@ class Connection extends BaseConnection
/** /**
* return MongoDB object. * return MongoDB object.
*
* @return \MongoDB\Client * @return \MongoDB\Client
*/ */
public function getMongoClient() public function getMongoClient()
...@@ -113,9 +106,16 @@ class Connection extends BaseConnection ...@@ -113,9 +106,16 @@ class Connection extends BaseConnection
return $this->connection; return $this->connection;
} }
/**
* {@inheritdoc}
*/
public function getDatabaseName()
{
return $this->getMongoDB()->getDatabaseName();
}
/** /**
* Create a new MongoDB connection. * Create a new MongoDB connection.
*
* @param string $dsn * @param string $dsn
* @param array $config * @param array $config
* @param array $options * @param array $options
...@@ -151,18 +151,16 @@ class Connection extends BaseConnection ...@@ -151,18 +151,16 @@ class Connection extends BaseConnection
/** /**
* Determine if the given configuration array has a dsn string. * Determine if the given configuration array has a dsn string.
*
* @param array $config * @param array $config
* @return bool * @return bool
*/ */
protected function hasDsnString(array $config) 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. * Get the DSN string form configuration.
*
* @param array $config * @param array $config
* @return string * @return string
*/ */
...@@ -173,7 +171,6 @@ class Connection extends BaseConnection ...@@ -173,7 +171,6 @@ class Connection extends BaseConnection
/** /**
* Get the DSN string for a host / port configuration. * Get the DSN string for a host / port configuration.
*
* @param array $config * @param array $config
* @return string * @return string
*/ */
...@@ -208,7 +205,6 @@ class Connection extends BaseConnection ...@@ -208,7 +205,6 @@ class Connection extends BaseConnection
/** /**
* Create a DSN string from a configuration. * Create a DSN string from a configuration.
*
* @param array $config * @param array $config
* @return string * @return string
*/ */
...@@ -261,7 +257,6 @@ class Connection extends BaseConnection ...@@ -261,7 +257,6 @@ class Connection extends BaseConnection
/** /**
* Dynamically pass methods to the connection. * Dynamically pass methods to the connection.
*
* @param string $method * @param string $method
* @param array $parameters * @param array $parameters
* @return mixed * @return mixed
......
...@@ -13,7 +13,6 @@ class Builder extends EloquentBuilder ...@@ -13,7 +13,6 @@ class Builder extends EloquentBuilder
/** /**
* The methods that should be returned from query builder. * The methods that should be returned from query builder.
*
* @var array * @var array
*/ */
protected $passthru = [ protected $passthru = [
...@@ -44,7 +43,7 @@ class Builder extends EloquentBuilder ...@@ -44,7 +43,7 @@ class Builder extends EloquentBuilder
return 1; 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 ...@@ -177,6 +176,29 @@ class Builder extends EloquentBuilder
return $results; 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 * @return \Illuminate\Database\ConnectionInterface
*/ */
......
...@@ -10,7 +10,6 @@ trait EmbedsRelations ...@@ -10,7 +10,6 @@ trait EmbedsRelations
{ {
/** /**
* Define an embedded one-to-many relationship. * Define an embedded one-to-many relationship.
*
* @param string $related * @param string $related
* @param string $localKey * @param string $localKey
* @param string $foreignKey * @param string $foreignKey
...@@ -22,17 +21,17 @@ trait EmbedsRelations ...@@ -22,17 +21,17 @@ trait EmbedsRelations
// If no relation name was given, we will use this debug backtrace to extract // 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 // 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. // 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); list(, $caller) = debug_backtrace(false);
$relation = $caller['function']; $relation = $caller['function'];
} }
if (is_null($localKey)) { if ($localKey === null) {
$localKey = $relation; $localKey = $relation;
} }
if (is_null($foreignKey)) { if ($foreignKey === null) {
$foreignKey = Str::snake(class_basename($this)); $foreignKey = Str::snake(class_basename($this));
} }
...@@ -45,7 +44,6 @@ trait EmbedsRelations ...@@ -45,7 +44,6 @@ trait EmbedsRelations
/** /**
* Define an embedded one-to-many relationship. * Define an embedded one-to-many relationship.
*
* @param string $related * @param string $related
* @param string $localKey * @param string $localKey
* @param string $foreignKey * @param string $foreignKey
...@@ -57,17 +55,17 @@ trait EmbedsRelations ...@@ -57,17 +55,17 @@ trait EmbedsRelations
// If no relation name was given, we will use this debug backtrace to extract // 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 // 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. // 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); list(, $caller) = debug_backtrace(false);
$relation = $caller['function']; $relation = $caller['function'];
} }
if (is_null($localKey)) { if ($localKey === null) {
$localKey = $relation; $localKey = $relation;
} }
if (is_null($foreignKey)) { if ($foreignKey === null) {
$foreignKey = Str::snake(class_basename($this)); $foreignKey = Str::snake(class_basename($this));
} }
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
namespace Jenssegers\Mongodb\Eloquent; namespace Jenssegers\Mongodb\Eloquent;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne; use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Helpers\EloquentBuilder; use Jenssegers\Mongodb\Helpers\EloquentBuilder;
...@@ -11,12 +10,12 @@ use Jenssegers\Mongodb\Relations\BelongsToMany; ...@@ -11,12 +10,12 @@ use Jenssegers\Mongodb\Relations\BelongsToMany;
use Jenssegers\Mongodb\Relations\HasMany; use Jenssegers\Mongodb\Relations\HasMany;
use Jenssegers\Mongodb\Relations\HasOne; use Jenssegers\Mongodb\Relations\HasOne;
use Jenssegers\Mongodb\Relations\MorphTo; use Jenssegers\Mongodb\Relations\MorphTo;
use Jenssegers\Mongodb\Relations\MorphMany;
trait HybridRelations trait HybridRelations
{ {
/** /**
* Define a one-to-one relationship. * Define a one-to-one relationship.
*
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $localKey * @param string $localKey
...@@ -40,7 +39,6 @@ trait HybridRelations ...@@ -40,7 +39,6 @@ trait HybridRelations
/** /**
* Define a polymorphic one-to-one relationship. * Define a polymorphic one-to-one relationship.
*
* @param string $related * @param string $related
* @param string $name * @param string $name
* @param string $type * @param string $type
...@@ -66,7 +64,6 @@ trait HybridRelations ...@@ -66,7 +64,6 @@ trait HybridRelations
/** /**
* Define a one-to-many relationship. * Define a one-to-many relationship.
*
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $localKey * @param string $localKey
...@@ -90,7 +87,6 @@ trait HybridRelations ...@@ -90,7 +87,6 @@ trait HybridRelations
/** /**
* Define a polymorphic one-to-many relationship. * Define a polymorphic one-to-many relationship.
*
* @param string $related * @param string $related
* @param string $name * @param string $name
* @param string $type * @param string $type
...@@ -121,7 +117,6 @@ trait HybridRelations ...@@ -121,7 +117,6 @@ trait HybridRelations
/** /**
* Define an inverse one-to-one or many relationship. * Define an inverse one-to-one or many relationship.
*
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $otherKey * @param string $otherKey
...@@ -133,7 +128,7 @@ trait HybridRelations ...@@ -133,7 +128,7 @@ trait HybridRelations
// If no relation name was given, we will use this debug backtrace to extract // 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 // 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. // 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); list($current, $caller) = debug_backtrace(false, 2);
$relation = $caller['function']; $relation = $caller['function'];
...@@ -147,7 +142,7 @@ trait HybridRelations ...@@ -147,7 +142,7 @@ trait HybridRelations
// If no foreign key was supplied, we can use a backtrace to guess the proper // 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 // foreign key name by using the name of the relationship function, which
// when combined with an "_id" should conventionally match the columns. // when combined with an "_id" should conventionally match the columns.
if (is_null($foreignKey)) { if ($foreignKey === null) {
$foreignKey = Str::snake($relation) . '_id'; $foreignKey = Str::snake($relation) . '_id';
} }
...@@ -165,7 +160,6 @@ trait HybridRelations ...@@ -165,7 +160,6 @@ trait HybridRelations
/** /**
* Define a polymorphic, inverse one-to-one or many relationship. * Define a polymorphic, inverse one-to-one or many relationship.
*
* @param string $name * @param string $name
* @param string $type * @param string $type
* @param string $id * @param string $id
...@@ -177,7 +171,7 @@ trait HybridRelations ...@@ -177,7 +171,7 @@ trait HybridRelations
// If no name is provided, we will use the backtrace to get the function name // 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 // 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. // 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); list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$name = Str::snake($caller['function']); $name = Str::snake($caller['function']);
...@@ -188,29 +182,28 @@ trait HybridRelations ...@@ -188,29 +182,28 @@ trait HybridRelations
// If the type value is null it is probably safe to assume we're eager loading // 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 // 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. // 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( return new MorphTo(
$this->newQuery(), $this, $id, null, $type, $name $this->newQuery(), $this, $id, $ownerKey, $type, $name
); );
} }
// If we are not eager loading the relationship we will essentially treat this // 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 // 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. // 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;
$ownerKey = $ownerKey ?? $instance->getKeyName();
return new MorphTo( return new MorphTo(
$instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name $instance->newQuery(), $this, $id, $ownerKey, $type, $name
); );
} }
}
/** /**
* Define a many-to-many relationship. * Define a many-to-many relationship.
*
* @param string $related * @param string $related
* @param string $collection * @param string $collection
* @param string $foreignKey * @param string $foreignKey
...@@ -232,7 +225,7 @@ trait HybridRelations ...@@ -232,7 +225,7 @@ trait HybridRelations
// If no relationship name was passed, we will pull backtraces to get the // 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 // 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. // title of this relation since that is a great convention to apply.
if (is_null($relation)) { if ($relation === null) {
$relation = $this->guessBelongsToManyRelation(); $relation = $this->guessBelongsToManyRelation();
} }
...@@ -261,7 +254,7 @@ trait HybridRelations ...@@ -261,7 +254,7 @@ trait HybridRelations
// If no table name was provided, we can guess it by concatenating the two // If no table name was provided, we can guess it by concatenating the two
// models using underscores in alphabetical order. The two model names // models using underscores in alphabetical order. The two model names
// are transformed to snake case from their default CamelCase also. // are transformed to snake case from their default CamelCase also.
if (is_null($collection)) { if ($collection === null) {
$collection = $instance->getTable(); $collection = $instance->getTable();
} }
...@@ -284,7 +277,6 @@ trait HybridRelations ...@@ -284,7 +277,6 @@ trait HybridRelations
/** /**
* Get the relationship name of the belongs to many. * Get the relationship name of the belongs to many.
*
* @return string * @return string
*/ */
protected function guessBelongsToManyRelation() protected function guessBelongsToManyRelation()
...@@ -303,8 +295,8 @@ trait HybridRelations ...@@ -303,8 +295,8 @@ trait HybridRelations
{ {
if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) { if (is_subclass_of($this, \Jenssegers\Mongodb\Eloquent\Model::class)) {
return new Builder($query); return new Builder($query);
} else {
return new EloquentBuilder($query);
} }
return new EloquentBuilder($query);
} }
} }
...@@ -4,11 +4,14 @@ namespace Jenssegers\Mongodb\Eloquent; ...@@ -4,11 +4,14 @@ namespace Jenssegers\Mongodb\Eloquent;
use Carbon\Carbon; use Carbon\Carbon;
use DateTime; use DateTime;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Database\Eloquent\Model as BaseModel; use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder; use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
...@@ -18,28 +21,30 @@ abstract class Model extends BaseModel ...@@ -18,28 +21,30 @@ abstract class Model extends BaseModel
/** /**
* The collection associated with the model. * The collection associated with the model.
*
* @var string * @var string
*/ */
protected $collection; protected $collection;
/** /**
* The primary key for the model. * The primary key for the model.
*
* @var string * @var string
*/ */
protected $primaryKey = '_id'; protected $primaryKey = '_id';
/**
* The primary key type.
* @var string
*/
protected $keyType = 'string';
/** /**
* The parent relation instance. * The parent relation instance.
*
* @var Relation * @var Relation
*/ */
protected $parentRelation; protected $parentRelation;
/** /**
* Custom accessor for the model's id. * Custom accessor for the model's id.
*
* @param mixed $value * @param mixed $value
* @return mixed * @return mixed
*/ */
...@@ -54,6 +59,8 @@ abstract class Model extends BaseModel ...@@ -54,6 +59,8 @@ abstract class Model extends BaseModel
// Convert ObjectID to string. // Convert ObjectID to string.
if ($value instanceof ObjectID) { if ($value instanceof ObjectID) {
return (string) $value; return (string) $value;
} elseif ($value instanceof Binary) {
return (string) $value->getData();
} }
return $value; return $value;
...@@ -111,7 +118,7 @@ abstract class Model extends BaseModel ...@@ -111,7 +118,7 @@ abstract class Model extends BaseModel
*/ */
public function freshTimestamp() public function freshTimestamp()
{ {
return new UTCDateTime(time() * 1000); return new UTCDateTime(Carbon::now());
} }
/** /**
...@@ -195,6 +202,8 @@ abstract class Model extends BaseModel ...@@ -195,6 +202,8 @@ abstract class Model extends BaseModel
foreach ($attributes as $key => &$value) { foreach ($attributes as $key => &$value) {
if ($value instanceof ObjectID) { if ($value instanceof ObjectID) {
$value = (string) $value; $value = (string) $value;
} elseif ($value instanceof Binary) {
$value = (string) $value->getData();
} }
} }
...@@ -219,7 +228,7 @@ abstract class Model extends BaseModel ...@@ -219,7 +228,7 @@ abstract class Model extends BaseModel
/** /**
* @inheritdoc * @inheritdoc
*/ */
protected function originalIsEquivalent($key, $current) public function originalIsEquivalent($key, $current)
{ {
if (!array_key_exists($key, $this->original)) { if (!array_key_exists($key, $this->original)) {
return false; return false;
...@@ -253,7 +262,6 @@ abstract class Model extends BaseModel ...@@ -253,7 +262,6 @@ abstract class Model extends BaseModel
/** /**
* Remove one or more fields. * Remove one or more fields.
*
* @param mixed $columns * @param mixed $columns
* @return int * @return int
*/ */
...@@ -299,7 +307,6 @@ abstract class Model extends BaseModel ...@@ -299,7 +307,6 @@ abstract class Model extends BaseModel
/** /**
* Remove one or more values from an array. * Remove one or more values from an array.
*
* @param string $column * @param string $column
* @param mixed $values * @param mixed $values
* @return mixed * @return mixed
...@@ -318,7 +325,6 @@ abstract class Model extends BaseModel ...@@ -318,7 +325,6 @@ abstract class Model extends BaseModel
/** /**
* Append one or more values to the underlying attribute value and sync with original. * Append one or more values to the underlying attribute value and sync with original.
*
* @param string $column * @param string $column
* @param array $values * @param array $values
* @param bool $unique * @param bool $unique
...@@ -343,7 +349,6 @@ abstract class Model extends BaseModel ...@@ -343,7 +349,6 @@ abstract class Model extends BaseModel
/** /**
* Remove one or more values to the underlying attribute value and sync with original. * Remove one or more values to the underlying attribute value and sync with original.
*
* @param string $column * @param string $column
* @param array $values * @param array $values
*/ */
...@@ -376,7 +381,6 @@ abstract class Model extends BaseModel ...@@ -376,7 +381,6 @@ abstract class Model extends BaseModel
/** /**
* Set the parent relation. * Set the parent relation.
*
* @param \Illuminate\Database\Eloquent\Relations\Relation $relation * @param \Illuminate\Database\Eloquent\Relations\Relation $relation
*/ */
public function setParentRelation(Relation $relation) public function setParentRelation(Relation $relation)
...@@ -386,7 +390,6 @@ abstract class Model extends BaseModel ...@@ -386,7 +390,6 @@ abstract class Model extends BaseModel
/** /**
* Get the parent relation. * Get the parent relation.
*
* @return \Illuminate\Database\Eloquent\Relations\Relation * @return \Illuminate\Database\Eloquent\Relations\Relation
*/ */
public function getParentRelation() public function getParentRelation()
...@@ -420,6 +423,50 @@ abstract class Model extends BaseModel ...@@ -420,6 +423,50 @@ abstract class Model extends BaseModel
return $key; return $key;
} }
/**
* Get the queueable relationships for the entity.
* @return array
*/
public function getQueueableRelations()
{
$relations = [];
foreach ($this->getRelationsWithoutParent() as $key => $relation) {
if (method_exists($this, $key)) {
$relations[] = $key;
}
if ($relation instanceof QueueableCollection) {
foreach ($relation->getQueueableRelations() as $collectionValue) {
$relations[] = $key . '.' . $collectionValue;
}
}
if ($relation instanceof QueueableEntity) {
foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) {
$relations[] = $key . '.' . $entityValue;
}
}
}
return array_unique($relations);
}
/**
* Get loaded relations for the instance without parent.
* @return array
*/
protected function getRelationsWithoutParent()
{
$relations = $this->getRelations();
if ($parentRelation = $this->getParentRelation()) {
unset($relations[$parentRelation->getQualifiedForeignKeyName()]);
}
return $relations;
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
......
...@@ -3,30 +3,34 @@ ...@@ -3,30 +3,34 @@
namespace Jenssegers\Mongodb\Helpers; namespace Jenssegers\Mongodb\Helpers;
use Closure; use Closure;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany; use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Jenssegers\Mongodb\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\Model;
trait QueriesRelationships trait QueriesRelationships
{ {
/** /**
* Add a relationship count / exists condition to the query. * Add a relationship count / exists condition to the query.
* * @param Relation|string $relation
* @param string $relation
* @param string $operator * @param string $operator
* @param int $count * @param int $count
* @param string $boolean * @param string $boolean
* @param \Closure|null $callback * @param Closure|null $callback
* @return \Illuminate\Database\Eloquent\Builder|static * @return Builder|static
*/ */
public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
{ {
if (is_string($relation)) {
if (strpos($relation, '.') !== false) { if (strpos($relation, '.') !== false) {
return $this->hasNested($relation, $operator, $count, $boolean, $callback); return $this->hasNested($relation, $operator, $count, $boolean, $callback);
} }
$relation = $this->getRelationWithoutConstraints($relation); $relation = $this->getRelationWithoutConstraints($relation);
}
// If this is a hybrid relation then we can not use a normal whereExists() query that relies on a subquery // If this is a hybrid relation then we can not use a normal whereExists() query that relies on a subquery
// We need to use a `whereIn` query // We need to use a `whereIn` query
...@@ -58,25 +62,25 @@ trait QueriesRelationships ...@@ -58,25 +62,25 @@ trait QueriesRelationships
} }
/** /**
* @param $relation * @param Relation $relation
* @return bool * @return bool
*/ */
protected function isAcrossConnections($relation) protected function isAcrossConnections(Relation $relation)
{ {
return $relation->getParent()->getConnectionName() !== $relation->getRelated()->getConnectionName(); return $relation->getParent()->getConnectionName() !== $relation->getRelated()->getConnectionName();
} }
/** /**
* Compare across databases * Compare across databases
* @param $relation * @param Relation $relation
* @param string $operator * @param string $operator
* @param int $count * @param int $count
* @param string $boolean * @param string $boolean
* @param Closure|null $callback * @param Closure|null $callback
* @return mixed * @return mixed
* @throws \Exception * @throws Exception
*/ */
public function addHybridHas($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) public function addHybridHas(Relation $relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
{ {
$hasQuery = $relation->getQuery(); $hasQuery = $relation->getQuery();
if ($callback) { if ($callback) {
...@@ -98,39 +102,16 @@ trait QueriesRelationships ...@@ -98,39 +102,16 @@ trait QueriesRelationships
} }
/** /**
* Returns key we are constraining this parent model's query with * @param Relation $relation
* @param $relation
* @return string * @return string
* @throws \Exception
*/ */
protected function getRelatedConstraintKey($relation) protected function getHasCompareKey(Relation $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
*/
protected function getHasCompareKey($relation)
{ {
if (method_exists($relation, 'getHasCompareKey')) { if (method_exists($relation, 'getHasCompareKey')) {
return $relation->getHasCompareKey(); return $relation->getHasCompareKey();
} }
return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKey(); return $relation instanceof HasOneOrMany ? $relation->getForeignKeyName() : $relation->getOwnerKeyName();
} }
/** /**
...@@ -166,4 +147,27 @@ trait QueriesRelationships ...@@ -166,4 +147,27 @@ trait QueriesRelationships
// All related ids. // All related ids.
return array_keys($relationCount); return array_keys($relationCount);
} }
/**
* Returns key we are constraining this parent model's query with
* @param Relation $relation
* @return string
* @throws Exception
*/
protected function getRelatedConstraintKey(Relation $relation)
{
if ($relation instanceof HasOneOrMany) {
return $relation->getLocalKeyName();
}
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 @@ ...@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb; namespace Jenssegers\Mongodb;
use DB;
use Illuminate\Queue\QueueServiceProvider; use Illuminate\Queue\QueueServiceProvider;
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider; use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
...@@ -13,7 +14,7 @@ class MongodbQueueServiceProvider extends QueueServiceProvider ...@@ -13,7 +14,7 @@ class MongodbQueueServiceProvider extends QueueServiceProvider
protected function registerFailedJobServices() protected function registerFailedJobServices()
{ {
// Add compatible queue failer if mongodb is configured. // 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) { $this->app->singleton('queue.failer', function ($app) {
return new MongoFailedJobProvider($app['db'], config('queue.failed.database'), config('queue.failed.table')); 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 ...@@ -9,11 +9,9 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
{ {
/** /**
* Log a failed job into storage. * Log a failed job into storage.
*
* @param string $connection * @param string $connection
* @param string $queue * @param string $queue
* @param string $payload * @param string $payload
*
* @return void * @return void
*/ */
public function log($connection, $queue, $payload, $exception) public function log($connection, $queue, $payload, $exception)
...@@ -25,7 +23,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -25,7 +23,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/** /**
* Get a list of all of the failed jobs. * Get a list of all of the failed jobs.
*
* @return object[] * @return object[]
*/ */
public function all() public function all()
...@@ -42,7 +39,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -42,7 +39,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/** /**
* Get a single failed job. * Get a single failed job.
*
* @param mixed $id * @param mixed $id
* @return object * @return object
*/ */
...@@ -50,6 +46,10 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -50,6 +46,10 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
{ {
$job = $this->getTable()->find($id); $job = $this->getTable()->find($id);
if (!$job) {
return;
}
$job['id'] = (string) $job['_id']; $job['id'] = (string) $job['_id'];
return (object) $job; return (object) $job;
...@@ -57,7 +57,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -57,7 +57,6 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
/** /**
* Delete a single failed job from storage. * Delete a single failed job from storage.
*
* @param mixed $id * @param mixed $id
* @return bool * @return bool
*/ */
......
...@@ -10,14 +10,12 @@ class MongoConnector implements ConnectorInterface ...@@ -10,14 +10,12 @@ class MongoConnector implements ConnectorInterface
{ {
/** /**
* Database connections. * Database connections.
*
* @var \Illuminate\Database\ConnectionResolverInterface * @var \Illuminate\Database\ConnectionResolverInterface
*/ */
protected $connections; protected $connections;
/** /**
* Create a new connector instance. * Create a new connector instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $connections * @param \Illuminate\Database\ConnectionResolverInterface $connections
*/ */
public function __construct(ConnectionResolverInterface $connections) public function __construct(ConnectionResolverInterface $connections)
...@@ -27,7 +25,6 @@ class MongoConnector implements ConnectorInterface ...@@ -27,7 +25,6 @@ class MongoConnector implements ConnectorInterface
/** /**
* Establish a queue connection. * Establish a queue connection.
*
* @param array $config * @param array $config
* @return \Illuminate\Contracts\Queue\Queue * @return \Illuminate\Contracts\Queue\Queue
*/ */
......
...@@ -8,7 +8,6 @@ class MongoJob extends DatabaseJob ...@@ -8,7 +8,6 @@ class MongoJob extends DatabaseJob
{ {
/** /**
* Indicates if the job has been reserved. * Indicates if the job has been reserved.
*
* @return bool * @return bool
*/ */
public function isReserved() public function isReserved()
......
...@@ -11,14 +11,12 @@ class MongoQueue extends DatabaseQueue ...@@ -11,14 +11,12 @@ class MongoQueue extends DatabaseQueue
{ {
/** /**
* The expiration time of a job. * The expiration time of a job.
*
* @var int|null * @var int|null
*/ */
protected $retryAfter = 60; protected $retryAfter = 60;
/** /**
* The connection name for the queue. * The connection name for the queue.
*
* @var string * @var string
*/ */
protected $connectionName; protected $connectionName;
...@@ -39,7 +37,7 @@ class MongoQueue extends DatabaseQueue ...@@ -39,7 +37,7 @@ class MongoQueue extends DatabaseQueue
{ {
$queue = $this->getQueue($queue); $queue = $this->getQueue($queue);
if (!is_null($this->retryAfter)) { if ($this->retryAfter !== null) {
$this->releaseJobsThatHaveBeenReservedTooLong($queue); $this->releaseJobsThatHaveBeenReservedTooLong($queue);
} }
...@@ -52,17 +50,13 @@ class MongoQueue extends DatabaseQueue ...@@ -52,17 +50,13 @@ class MongoQueue extends DatabaseQueue
/** /**
* Get the next available job for the queue and mark it as reserved. * Get the next available job for the queue and mark it as reserved.
*
* When using multiple daemon queue listeners to process jobs there * When using multiple daemon queue listeners to process jobs there
* is a possibility that multiple processes can end up reading the * is a possibility that multiple processes can end up reading the
* same record before one has flagged it as reserved. * same record before one has flagged it as reserved.
*
* This race condition can result in random jobs being run more then * This race condition can result in random jobs being run more then
* once. To solve this we use findOneAndUpdate to lock the next jobs * once. To solve this we use findOneAndUpdate to lock the next jobs
* record while flagging it as reserved at the same time. * record while flagging it as reserved at the same time.
*
* @param string|null $queue * @param string|null $queue
*
* @return \StdClass|null * @return \StdClass|null
*/ */
protected function getNextAvailableJobAndReserve($queue) protected function getNextAvailableJobAndReserve($queue)
...@@ -70,7 +64,7 @@ class MongoQueue extends DatabaseQueue ...@@ -70,7 +64,7 @@ class MongoQueue extends DatabaseQueue
$job = $this->database->getCollection($this->table)->findOneAndUpdate( $job = $this->database->getCollection($this->table)->findOneAndUpdate(
[ [
'queue' => $this->getQueue($queue), 'queue' => $this->getQueue($queue),
'reserved' => 0, 'reserved' => ['$ne' => 1],
'available_at' => ['$lte' => Carbon::now()->getTimestamp()], 'available_at' => ['$lte' => Carbon::now()->getTimestamp()],
], ],
[ [
...@@ -78,6 +72,9 @@ class MongoQueue extends DatabaseQueue ...@@ -78,6 +72,9 @@ class MongoQueue extends DatabaseQueue
'reserved' => 1, 'reserved' => 1,
'reserved_at' => Carbon::now()->getTimestamp(), 'reserved_at' => Carbon::now()->getTimestamp(),
], ],
'$inc' => [
'attempts' => 1,
],
], ],
[ [
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
...@@ -94,37 +91,26 @@ class MongoQueue extends DatabaseQueue ...@@ -94,37 +91,26 @@ class MongoQueue extends DatabaseQueue
/** /**
* Release the jobs that have been reserved for too long. * Release the jobs that have been reserved for too long.
*
* @param string $queue * @param string $queue
* @return void * @return void
*/ */
protected function releaseJobsThatHaveBeenReservedTooLong($queue) protected function releaseJobsThatHaveBeenReservedTooLong($queue)
{ {
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp(); $expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$now = time();
$reserved = $this->database->collection($this->table) $reserved = $this->database->collection($this->table)
->where('queue', $this->getQueue($queue)) ->where('queue', $this->getQueue($queue))
->where(function ($query) use ($expiration, $now) { ->whereNotNull('reserved_at')
// Check for available jobs ->where('reserved_at', '<=', $expiration)
$query->where(function ($query) use ($now) { ->get();
$query->whereNull('reserved_at');
$query->where('available_at', '<=', $now);
});
// Check for jobs that are reserved but have expired
$query->orWhere('reserved_at', '<=', $expiration);
})->get();
foreach ($reserved as $job) { foreach ($reserved as $job) {
$attempts = $job['attempts'] + 1; $this->releaseJob($job['_id'], $job['attempts']);
$this->releaseJob($job['_id'], $attempts);
} }
} }
/** /**
* Release the given job ID from reservation. * Release the given job ID from reservation.
*
* @param string $id * @param string $id
* @param int $attempts * @param int $attempts
* @return void * @return void
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo
{ {
/** /**
* Get the key for comparing against the parent key in "has" query. * Get the key for comparing against the parent key in "has" query.
*
* @return string * @return string
*/ */
public function getHasCompareKey() public function getHasCompareKey()
...@@ -52,11 +52,21 @@ class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo ...@@ -52,11 +52,21 @@ class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo
/** /**
* Get the owner key with backwards compatible support. * Get the owner key with backwards compatible support.
*
* @return string * @return string
*/ */
public function getOwnerKey() public function getOwnerKey()
{ {
return property_exists($this, 'ownerKey') ? $this->ownerKey : $this->otherKey; 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';
}
} }
...@@ -5,6 +5,7 @@ namespace Jenssegers\Mongodb\Relations; ...@@ -5,6 +5,7 @@ namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
...@@ -12,7 +13,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -12,7 +13,6 @@ class BelongsToMany extends EloquentBelongsToMany
{ {
/** /**
* Get the key for comparing against the parent key in "has" query. * Get the key for comparing against the parent key in "has" query.
*
* @return string * @return string
*/ */
public function getHasCompareKey() public function getHasCompareKey()
...@@ -38,7 +38,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -38,7 +38,6 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Set the select clause for the relation query. * Set the select clause for the relation query.
*
* @param array $columns * @param array $columns
* @return array * @return array
*/ */
...@@ -67,7 +66,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -67,7 +66,6 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Set the where clause for the relation query. * Set the where clause for the relation query.
*
* @return $this * @return $this
*/ */
protected function setWhere() protected function setWhere()
...@@ -274,7 +272,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -274,7 +272,6 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Create a new query builder for the related model. * Create a new query builder for the related model.
*
* @return \Illuminate\Database\Query\Builder * @return \Illuminate\Database\Query\Builder
*/ */
public function newRelatedQuery() public function newRelatedQuery()
...@@ -284,7 +281,6 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -284,7 +281,6 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Get the fully qualified foreign key for the relation. * Get the fully qualified foreign key for the relation.
*
* @return string * @return string
*/ */
public function getForeignKey() public function getForeignKey()
...@@ -311,10 +307,9 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -311,10 +307,9 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Format the sync list so that it is keyed by ID. (Legacy Support) * 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 * The original function has been renamed to formatRecordsList since Laravel 5.3
*
* @deprecated
* @param array $records * @param array $records
* @return array * @return array
* @deprecated
*/ */
protected function formatSyncList(array $records) protected function formatSyncList(array $records)
{ {
...@@ -330,11 +325,21 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -330,11 +325,21 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* Get the related key with backwards compatible support. * Get the related key with backwards compatible support.
*
* @return string * @return string
*/ */
public function getRelatedKey() public function getRelatedKey()
{ {
return property_exists($this, 'relatedPivotKey') ? $this->relatedPivotKey : $this->relatedKey; 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';
}
} }
...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb\Relations; ...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator; use Illuminate\Pagination\Paginator;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
...@@ -32,7 +33,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -32,7 +33,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Save a new model and attach it to the parent model. * Save a new model and attach it to the parent model.
*
* @param Model $model * @param Model $model
* @return Model|bool * @return Model|bool
*/ */
...@@ -62,7 +62,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -62,7 +62,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Save an existing model and attach it to the parent model. * Save an existing model and attach it to the parent model.
*
* @param Model $model * @param Model $model
* @return Model|bool * @return Model|bool
*/ */
...@@ -94,7 +93,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -94,7 +93,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Delete an existing model and detach it from the parent model. * Delete an existing model and detach it from the parent model.
*
* @param Model $model * @param Model $model
* @return int * @return int
*/ */
...@@ -121,7 +119,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -121,7 +119,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Associate the model instance to the given parent, without saving it to the database. * Associate the model instance to the given parent, without saving it to the database.
*
* @param Model $model * @param Model $model
* @return Model * @return Model
*/ */
...@@ -129,14 +126,13 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -129,14 +126,13 @@ class EmbedsMany extends EmbedsOneOrMany
{ {
if (!$this->contains($model)) { if (!$this->contains($model)) {
return $this->associateNew($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. * Dissociate the model instance from the given parent, without saving it to the database.
*
* @param mixed $ids * @param mixed $ids
* @return int * @return int
*/ */
...@@ -165,7 +161,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -165,7 +161,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Destroy the embedded models for the given IDs. * Destroy the embedded models for the given IDs.
*
* @param mixed $ids * @param mixed $ids
* @return int * @return int
*/ */
...@@ -190,7 +185,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -190,7 +185,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Delete all embedded models. * Delete all embedded models.
*
* @return int * @return int
*/ */
public function delete() public function delete()
...@@ -207,7 +201,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -207,7 +201,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Destroy alias. * Destroy alias.
*
* @param mixed $ids * @param mixed $ids
* @return int * @return int
*/ */
...@@ -218,7 +211,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -218,7 +211,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Save alias. * Save alias.
*
* @param Model $model * @param Model $model
* @return Model * @return Model
*/ */
...@@ -229,14 +221,13 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -229,14 +221,13 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Associate a new model instance to the given parent, without saving it to the database. * Associate a new model instance to the given parent, without saving it to the database.
*
* @param Model $model * @param Model $model
* @return Model * @return Model
*/ */
protected function associateNew($model) protected function associateNew($model)
{ {
// Create a new key if needed. // Create a new key if needed.
if (!$model->getAttribute('_id')) { if ($model->getKeyName() === '_id' && !$model->getAttribute('_id')) {
$model->setAttribute('_id', new ObjectID); $model->setAttribute('_id', new ObjectID);
} }
...@@ -250,7 +241,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -250,7 +241,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Associate an existing model instance to the given parent, without saving it to the database. * Associate an existing model instance to the given parent, without saving it to the database.
*
* @param Model $model * @param Model $model
* @return Model * @return Model
*/ */
...@@ -276,7 +266,6 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -276,7 +266,6 @@ class EmbedsMany extends EmbedsOneOrMany
/** /**
* Get a paginator for the "select" statement. * Get a paginator for the "select" statement.
*
* @param int $perPage * @param int $perPage
* @return \Illuminate\Pagination\AbstractPaginator * @return \Illuminate\Pagination\AbstractPaginator
*/ */
...@@ -328,4 +317,15 @@ class EmbedsMany extends EmbedsOneOrMany ...@@ -328,4 +317,15 @@ class EmbedsMany extends EmbedsOneOrMany
return parent::__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';
}
} }
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
class EmbedsOne extends EmbedsOneOrMany class EmbedsOne extends EmbedsOneOrMany
...@@ -29,7 +30,6 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -29,7 +30,6 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Save a new model and attach it to the parent model. * Save a new model and attach it to the parent model.
*
* @param Model $model * @param Model $model
* @return Model|bool * @return Model|bool
*/ */
...@@ -58,7 +58,6 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -58,7 +58,6 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Save an existing model and attach it to the parent model. * Save an existing model and attach it to the parent model.
*
* @param Model $model * @param Model $model
* @return Model|bool * @return Model|bool
*/ */
...@@ -84,7 +83,6 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -84,7 +83,6 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Delete an existing model and detach it from the parent model. * Delete an existing model and detach it from the parent model.
*
* @return int * @return int
*/ */
public function performDelete() public function performDelete()
...@@ -108,7 +106,6 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -108,7 +106,6 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Attach the model to its parent. * Attach the model to its parent.
*
* @param Model $model * @param Model $model
* @return Model * @return Model
*/ */
...@@ -119,7 +116,6 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -119,7 +116,6 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Detach the model from its parent. * Detach the model from its parent.
*
* @return Model * @return Model
*/ */
public function dissociate() public function dissociate()
...@@ -129,11 +125,21 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -129,11 +125,21 @@ class EmbedsOne extends EmbedsOneOrMany
/** /**
* Delete all embedded models. * Delete all embedded models.
*
* @return int * @return int
*/ */
public function delete() public function delete()
{ {
return $this->performDelete(); 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';
}
} }
...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb\Relations; ...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Jenssegers\Mongodb\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\Model;
...@@ -11,28 +12,24 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -11,28 +12,24 @@ abstract class EmbedsOneOrMany extends Relation
{ {
/** /**
* The local key of the parent model. * The local key of the parent model.
*
* @var string * @var string
*/ */
protected $localKey; protected $localKey;
/** /**
* The foreign key of the parent model. * The foreign key of the parent model.
*
* @var string * @var string
*/ */
protected $foreignKey; protected $foreignKey;
/** /**
* The "name" of the relationship. * The "name" of the relationship.
*
* @var string * @var string
*/ */
protected $relation; protected $relation;
/** /**
* Create a new embeds many relationship instance. * Create a new embeds many relationship instance.
*
* @param Builder $query * @param Builder $query
* @param Model $parent * @param Model $parent
* @param Model $related * @param Model $related
...@@ -93,9 +90,7 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -93,9 +90,7 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Shorthand to get the results of the relationship. * Shorthand to get the results of the relationship.
*
* @param array $columns * @param array $columns
*
* @return Collection * @return Collection
*/ */
public function get($columns = ['*']) public function get($columns = ['*'])
...@@ -105,7 +100,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -105,7 +100,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Get the number of embedded models. * Get the number of embedded models.
*
* @return int * @return int
*/ */
public function count() public function count()
...@@ -115,7 +109,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -115,7 +109,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Attach a model instance to the parent model. * Attach a model instance to the parent model.
*
* @param Model $model * @param Model $model
* @return Model|bool * @return Model|bool
*/ */
...@@ -128,7 +121,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -128,7 +121,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Attach a collection of models to the parent instance. * Attach a collection of models to the parent instance.
*
* @param Collection|array $models * @param Collection|array $models
* @return Collection|array * @return Collection|array
*/ */
...@@ -143,7 +135,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -143,7 +135,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Create a new instance of the related model. * Create a new instance of the related model.
*
* @param array $attributes * @param array $attributes
* @return Model * @return Model
*/ */
...@@ -163,7 +154,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -163,7 +154,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Create an array of new instances of the related model. * Create an array of new instances of the related model.
*
* @param array $records * @param array $records
* @return array * @return array
*/ */
...@@ -180,7 +170,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -180,7 +170,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Transform single ID, single Model or array of Models into an array of IDs. * Transform single ID, single Model or array of Models into an array of IDs.
*
* @param mixed $ids * @param mixed $ids
* @return array * @return array
*/ */
...@@ -235,7 +224,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -235,7 +224,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Get the foreign key value for the relation. * Get the foreign key value for the relation.
*
* @param mixed $id * @param mixed $id
* @return mixed * @return mixed
*/ */
...@@ -251,7 +239,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -251,7 +239,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Convert an array of records to a Collection. * Convert an array of records to a Collection.
*
* @param array $records * @param array $records
* @return Collection * @return Collection
*/ */
...@@ -272,13 +259,12 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -272,13 +259,12 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Create a related model instanced. * Create a related model instanced.
*
* @param array $attributes * @param array $attributes
* @return Model * @return Model
*/ */
protected function toModel($attributes = []) protected function toModel($attributes = [])
{ {
if (is_null($attributes)) { if ($attributes === null) {
return; return;
} }
...@@ -301,7 +287,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -301,7 +287,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Get the relation instance of the parent. * Get the relation instance of the parent.
*
* @return Relation * @return Relation
*/ */
protected function getParentRelation() protected function getParentRelation()
...@@ -331,7 +316,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -331,7 +316,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Check if this relation is nested in another relation. * Check if this relation is nested in another relation.
*
* @return bool * @return bool
*/ */
protected function isNested() protected function isNested()
...@@ -341,7 +325,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -341,7 +325,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Get the fully qualified local key name. * Get the fully qualified local key name.
*
* @param string $glue * @param string $glue
* @return string * @return string
*/ */
...@@ -368,7 +351,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -368,7 +351,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Get the primary key value of the parent. * Get the primary key value of the parent.
*
* @return string * @return string
*/ */
protected function getParentKey() protected function getParentKey()
...@@ -378,7 +360,6 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -378,7 +360,6 @@ abstract class EmbedsOneOrMany extends Relation
/** /**
* Return update values * Return update values
*
* @param $array * @param $array
* @param string $prepend * @param string $prepend
* @return array * @return array
...@@ -388,9 +369,29 @@ abstract class EmbedsOneOrMany extends Relation ...@@ -388,9 +369,29 @@ abstract class EmbedsOneOrMany extends Relation
$results = []; $results = [];
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$results[$prepend.$key] = $value; $results[$prepend . $key] = $value;
} }
return $results; return $results;
} }
/**
* 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';
}
} }
...@@ -3,13 +3,13 @@ ...@@ -3,13 +3,13 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany; use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany;
class HasMany extends EloquentHasMany class HasMany extends EloquentHasMany
{ {
/** /**
* Get the plain foreign key. * Get the plain foreign key.
*
* @return string * @return string
*/ */
public function getForeignKeyName() public function getForeignKeyName()
...@@ -19,7 +19,6 @@ class HasMany extends EloquentHasMany ...@@ -19,7 +19,6 @@ class HasMany extends EloquentHasMany
/** /**
* Get the plain foreign key. * Get the plain foreign key.
*
* @return string * @return string
*/ */
public function getPlainForeignKey() public function getPlainForeignKey()
...@@ -29,7 +28,6 @@ class HasMany extends EloquentHasMany ...@@ -29,7 +28,6 @@ class HasMany extends EloquentHasMany
/** /**
* Get the key for comparing against the parent key in "has" query. * Get the key for comparing against the parent key in "has" query.
*
* @return string * @return string
*/ */
public function getHasCompareKey() public function getHasCompareKey()
...@@ -49,7 +47,6 @@ class HasMany extends EloquentHasMany ...@@ -49,7 +47,6 @@ class HasMany extends EloquentHasMany
/** /**
* Add the constraints for a relationship count query. * Add the constraints for a relationship count query.
*
* @param Builder $query * @param Builder $query
* @param Builder $parent * @param Builder $parent
* @return Builder * @return Builder
...@@ -63,7 +60,6 @@ class HasMany extends EloquentHasMany ...@@ -63,7 +60,6 @@ class HasMany extends EloquentHasMany
/** /**
* Add the constraints for a relationship query. * Add the constraints for a relationship query.
*
* @param Builder $query * @param Builder $query
* @param Builder $parent * @param Builder $parent
* @param array|mixed $columns * @param array|mixed $columns
...@@ -77,4 +73,15 @@ class HasMany extends EloquentHasMany ...@@ -77,4 +73,15 @@ class HasMany extends EloquentHasMany
return $query->where($this->getHasCompareKey(), 'exists', true); 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';
}
} }
...@@ -3,13 +3,13 @@ ...@@ -3,13 +3,13 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne; use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne;
class HasOne extends EloquentHasOne class HasOne extends EloquentHasOne
{ {
/** /**
* Get the key for comparing against the parent key in "has" query. * Get the key for comparing against the parent key in "has" query.
*
* @return string * @return string
*/ */
public function getForeignKeyName() public function getForeignKeyName()
...@@ -19,7 +19,6 @@ class HasOne extends EloquentHasOne ...@@ -19,7 +19,6 @@ class HasOne extends EloquentHasOne
/** /**
* Get the key for comparing against the parent key in "has" query. * Get the key for comparing against the parent key in "has" query.
*
* @return string * @return string
*/ */
public function getHasCompareKey() public function getHasCompareKey()
...@@ -29,7 +28,6 @@ class HasOne extends EloquentHasOne ...@@ -29,7 +28,6 @@ class HasOne extends EloquentHasOne
/** /**
* Get the plain foreign key. * Get the plain foreign key.
*
* @return string * @return string
*/ */
public function getPlainForeignKey() public function getPlainForeignKey()
...@@ -49,7 +47,6 @@ class HasOne extends EloquentHasOne ...@@ -49,7 +47,6 @@ class HasOne extends EloquentHasOne
/** /**
* Add the constraints for a relationship count query. * Add the constraints for a relationship count query.
*
* @param Builder $query * @param Builder $query
* @param Builder $parent * @param Builder $parent
* @return Builder * @return Builder
...@@ -63,7 +60,6 @@ class HasOne extends EloquentHasOne ...@@ -63,7 +60,6 @@ class HasOne extends EloquentHasOne
/** /**
* Add the constraints for a relationship query. * Add the constraints for a relationship query.
*
* @param Builder $query * @param Builder $query
* @param Builder $parent * @param Builder $parent
* @param array|mixed $columns * @param array|mixed $columns
...@@ -77,4 +73,15 @@ class HasOne extends EloquentHasOne ...@@ -77,4 +73,15 @@ class HasOne extends EloquentHasOne
return $query->where($this->getForeignKeyName(), 'exists', true); 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';
}
} }
<?php
namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\MorphMany as EloquentMorphMany;
class MorphMany extends EloquentMorphMany
{
/**
* 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';
}
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace Jenssegers\Mongodb\Relations; namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo; use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo;
class MorphTo extends EloquentMorphTo class MorphTo extends EloquentMorphTo
...@@ -35,11 +36,21 @@ class MorphTo extends EloquentMorphTo ...@@ -35,11 +36,21 @@ class MorphTo extends EloquentMorphTo
/** /**
* Get the owner key with backwards compatible support. * Get the owner key with backwards compatible support.
*
* @return string * @return string
*/ */
public function getOwnerKey() public function getOwnerKey()
{ {
return property_exists($this, 'ownerKey') ? $this->ownerKey : $this->otherKey; 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';
}
} }
...@@ -8,21 +8,18 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -8,21 +8,18 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
{ {
/** /**
* The MongoConnection object for this blueprint. * The MongoConnection object for this blueprint.
*
* @var \Jenssegers\Mongodb\Connection * @var \Jenssegers\Mongodb\Connection
*/ */
protected $connection; protected $connection;
/** /**
* The MongoCollection object for this blueprint. * The MongoCollection object for this blueprint.
*
* @var \Jenssegers\Mongodb\Collection|\MongoDB\Collection * @var \Jenssegers\Mongodb\Collection|\MongoDB\Collection
*/ */
protected $collection; protected $collection;
/** /**
* Fluent columns. * Fluent columns.
*
* @var array * @var array
*/ */
protected $columns = []; protected $columns = [];
...@@ -77,6 +74,54 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -77,6 +74,54 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
* @inheritdoc * @inheritdoc
*/ */
public function dropIndex($indexOrColumns = null) 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)) { if (is_array($indexOrColumns)) {
$indexOrColumns = $this->fluent($indexOrColumns); $indexOrColumns = $this->fluent($indexOrColumns);
...@@ -84,16 +129,23 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -84,16 +129,23 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
// Transform the columns to the index name. // Transform the columns to the index name.
$transform = []; $transform = [];
foreach ($indexOrColumns as $column) { foreach ($indexOrColumns as $key => $value) {
$transform[$column] = $column . '_1'; if (is_int($key)) {
// There is no sorting order, use the default.
$column = $value;
$sorting = '1';
} else {
// This is a column with sorting order e.g 'my_column' => -1.
$column = $key;
$sorting = $value;
} }
$indexOrColumns = join('_', $transform); $transform[$column] = $column . "_" . $sorting;
} }
$this->collection->dropIndex($indexOrColumns); $indexOrColumns = implode('_', $transform);
}
return $this; return $indexOrColumns;
} }
/** /**
...@@ -112,7 +164,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -112,7 +164,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Specify a non blocking index for the collection. * Specify a non blocking index for the collection.
*
* @param string|array $columns * @param string|array $columns
* @return Blueprint * @return Blueprint
*/ */
...@@ -127,7 +178,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -127,7 +178,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Specify a sparse index for the collection. * Specify a sparse index for the collection.
*
* @param string|array $columns * @param string|array $columns
* @param array $options * @param array $options
* @return Blueprint * @return Blueprint
...@@ -145,7 +195,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -145,7 +195,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Specify a geospatial index for the collection. * Specify a geospatial index for the collection.
*
* @param string|array $columns * @param string|array $columns
* @param string $index * @param string $index
* @param array $options * @param array $options
...@@ -171,7 +220,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -171,7 +220,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Specify the number of seconds after wich a document should be considered expired based, * Specify the number of seconds after wich a document should be considered expired based,
* on the given single-field index containing a date. * on the given single-field index containing a date.
*
* @param string|array $columns * @param string|array $columns
* @param int $seconds * @param int $seconds
* @return Blueprint * @return Blueprint
...@@ -218,7 +266,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -218,7 +266,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Specify a sparse and unique index for the collection. * Specify a sparse and unique index for the collection.
*
* @param string|array $columns * @param string|array $columns
* @param array $options * @param array $options
* @return Blueprint * @return Blueprint
...@@ -237,13 +284,12 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -237,13 +284,12 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Allow fluent columns. * Allow fluent columns.
*
* @param string|array $columns * @param string|array $columns
* @return string|array * @return string|array
*/ */
protected function fluent($columns = null) protected function fluent($columns = null)
{ {
if (is_null($columns)) { if ($columns === null) {
return $this->columns; return $this->columns;
} elseif (is_string($columns)) { } elseif (is_string($columns)) {
return $this->columns = [$columns]; return $this->columns = [$columns];
...@@ -254,7 +300,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint ...@@ -254,7 +300,6 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint
/** /**
* Allows the use of unsupported schema methods. * Allows the use of unsupported schema methods.
*
* @param $method * @param $method
* @param $args * @param $args
* @return Blueprint * @return Blueprint
......
...@@ -33,7 +33,6 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -33,7 +33,6 @@ class Builder extends \Illuminate\Database\Schema\Builder
/** /**
* Determine if the given collection exists. * Determine if the given collection exists.
*
* @param string $collection * @param string $collection
* @return bool * @return bool
*/ */
...@@ -60,7 +59,6 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -60,7 +59,6 @@ class Builder extends \Illuminate\Database\Schema\Builder
/** /**
* Modify a collection on the schema. * Modify a collection on the schema.
*
* @param string $collection * @param string $collection
* @param Closure $callback * @param Closure $callback
* @return bool * @return bool
...@@ -85,11 +83,11 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -85,11 +83,11 @@ class Builder extends \Illuminate\Database\Schema\Builder
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function create($collection, Closure $callback = null) public function create($collection, Closure $callback = null, array $options = [])
{ {
$blueprint = $this->createBlueprint($collection); $blueprint = $this->createBlueprint($collection);
$blueprint->create(); $blueprint->create($options);
if ($callback) { if ($callback) {
$callback($blueprint); $callback($blueprint);
...@@ -138,7 +136,6 @@ class Builder extends \Illuminate\Database\Schema\Builder ...@@ -138,7 +136,6 @@ class Builder extends \Illuminate\Database\Schema\Builder
/** /**
* Get all of the collections names for the database. * Get all of the collections names for the database.
*
* @return array * @return array
*/ */
protected function getAllCollections() protected function getAllCollections()
......
...@@ -6,7 +6,6 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe ...@@ -6,7 +6,6 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe
{ {
/** /**
* Count the number of objects in a collection having the given value. * Count the number of objects in a collection having the given value.
*
* @param string $collection * @param string $collection
* @param string $column * @param string $column
* @param string $value * @param string $value
...@@ -19,7 +18,7 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe ...@@ -19,7 +18,7 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe
{ {
$query = $this->table($collection)->where($column, 'regex', "/$value/i"); $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); $query->where($idColumn ?: 'id', '<>', $excludeId);
} }
...@@ -32,7 +31,6 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe ...@@ -32,7 +31,6 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe
/** /**
* Count the number of objects in a collection with the given values. * Count the number of objects in a collection with the given values.
*
* @param string $collection * @param string $collection
* @param string $column * @param string $column
* @param array $values * @param array $values
......
...@@ -2,11 +2,13 @@ ...@@ -2,11 +2,13 @@
use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Auth\Passwords\PasswordBroker;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use MongoDB\BSON\UTCDateTime;
class AuthTest extends TestCase class AuthTest extends TestCase
{ {
public function tearDown() public function tearDown(): void
{ {
parent::setUp();
User::truncate(); User::truncate();
DB::collection('password_reminders')->truncate(); DB::collection('password_reminders')->truncate();
} }
...@@ -26,6 +28,7 @@ class AuthTest extends TestCase ...@@ -26,6 +28,7 @@ class AuthTest extends TestCase
public function testRemindOld() public function testRemindOld()
{ {
if (Application::VERSION >= '5.2') { if (Application::VERSION >= '5.2') {
$this->expectNotToPerformAssertions();
return; return;
} }
...@@ -48,7 +51,7 @@ class AuthTest extends TestCase ...@@ -48,7 +51,7 @@ class AuthTest extends TestCase
$reminder = DB::collection('password_resets')->first(); $reminder = DB::collection('password_resets')->first();
$this->assertEquals('john@doe.com', $reminder['email']); $this->assertEquals('john@doe.com', $reminder['email']);
$this->assertNotNull($reminder['token']); $this->assertNotNull($reminder['token']);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $reminder['created_at']); $this->assertInstanceOf(UTCDateTime::class, $reminder['created_at']);
$credentials = [ $credentials = [
'email' => 'john@doe.com', 'email' => 'john@doe.com',
......
<?php <?php
declare(strict_types=1);
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Collection; use Jenssegers\Mongodb\Collection;
use MongoDB\Collection as MongoCollection; use Jenssegers\Mongodb\Connection;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
use MongoDB\Collection as MongoCollection;
class CollectionTest extends TestCase class CollectionTest extends TestCase
{ {
......
<?php <?php
declare(strict_types=1);
use Illuminate\Support\Facades\DB;
class ConnectionTest extends TestCase class ConnectionTest extends TestCase
{ {
public function testConnection() public function testConnection()
{ {
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf('Jenssegers\Mongodb\Connection', $connection); $this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $connection);
} }
public function testReconnect() public function testReconnect()
...@@ -23,28 +26,28 @@ class ConnectionTest extends TestCase ...@@ -23,28 +26,28 @@ class ConnectionTest extends TestCase
public function testDb() public function testDb()
{ {
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf('MongoDB\Database', $connection->getMongoDB()); $this->assertInstanceOf(\MongoDB\Database::class, $connection->getMongoDB());
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf('MongoDB\Client', $connection->getMongoClient()); $this->assertInstanceOf(\MongoDB\Client::class, $connection->getMongoClient());
} }
public function testCollection() public function testCollection()
{ {
$collection = DB::connection('mongodb')->getCollection('unittest'); $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'); $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'); $collection = DB::connection('mongodb')->table('unittests');
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); $this->assertInstanceOf(Jenssegers\Mongodb\Query\Builder::class, $collection);
} }
// public function testDynamic() // public function testDynamic()
// { // {
// $dbs = DB::connection('mongodb')->listCollections(); // $dbs = DB::connection('mongodb')->listCollections();
// $this->assertInternalType('array', $dbs); // $this->assertIsArray($dbs);
// } // }
// public function testMultipleConnections() // public function testMultipleConnections()
...@@ -87,7 +90,7 @@ class ConnectionTest extends TestCase ...@@ -87,7 +90,7 @@ class ConnectionTest extends TestCase
public function testSchemaBuilder() public function testSchemaBuilder()
{ {
$schema = DB::connection('mongodb')->getSchemaBuilder(); $schema = DB::connection('mongodb')->getSchemaBuilder();
$this->assertInstanceOf('Jenssegers\Mongodb\Schema\Builder', $schema); $this->assertInstanceOf(\Jenssegers\Mongodb\Schema\Builder::class, $schema);
} }
public function testDriverName() public function testDriverName()
......
<?php <?php
declare(strict_types=1);
class DsnTest extends TestCase class DsnTest extends TestCase
{ {
......
This diff is collapsed.
<?php <?php
declare(strict_types=1);
class GeospatialTest extends TestCase class GeospatialTest extends TestCase
{ {
public function setUp() public function setUp(): void
{ {
parent::setUp(); parent::setUp();
...@@ -43,7 +44,7 @@ class GeospatialTest extends TestCase ...@@ -43,7 +44,7 @@ class GeospatialTest extends TestCase
]); ]);
} }
public function tearDown() public function tearDown(): void
{ {
Schema::drop('locations'); Schema::drop('locations');
} }
...@@ -53,7 +54,8 @@ class GeospatialTest extends TestCase ...@@ -53,7 +54,8 @@ class GeospatialTest extends TestCase
$locations = Location::where('location', 'geoWithin', [ $locations = Location::where('location', 'geoWithin', [
'$geometry' => [ '$geometry' => [
'type' => 'Polygon', 'type' => 'Polygon',
'coordinates' => [[ 'coordinates' => [
[
[ [
-0.1450383, -0.1450383,
51.5069158, 51.5069158,
...@@ -74,7 +76,8 @@ class GeospatialTest extends TestCase ...@@ -74,7 +76,8 @@ class GeospatialTest extends TestCase
-0.1450383, -0.1450383,
51.5069158, 51.5069158,
], ],
]], ],
],
], ],
]); ]);
...@@ -104,7 +107,7 @@ class GeospatialTest extends TestCase ...@@ -104,7 +107,7 @@ class GeospatialTest extends TestCase
51.5078646, 51.5078646,
], ],
], ],
] ],
]); ]);
$this->assertEquals(1, $locations->count()); $this->assertEquals(1, $locations->count());
......
<?php <?php
declare(strict_types=1);
use Illuminate\Database\MySqlConnection;
class HybridRelationsTest extends TestCase class HybridRelationsTest extends TestCase
{ {
public function setUp() public function setUp(): void
{ {
parent::setUp(); parent::setUp();
...@@ -11,7 +14,7 @@ class HybridRelationsTest extends TestCase ...@@ -11,7 +14,7 @@ class HybridRelationsTest extends TestCase
MysqlRole::executeSchema(); MysqlRole::executeSchema();
} }
public function tearDown() public function tearDown(): void
{ {
MysqlUser::truncate(); MysqlUser::truncate();
MysqlBook::truncate(); MysqlBook::truncate();
...@@ -21,13 +24,13 @@ class HybridRelationsTest extends TestCase ...@@ -21,13 +24,13 @@ class HybridRelationsTest extends TestCase
public function testMysqlRelations() public function testMysqlRelations()
{ {
$user = new MysqlUser; $user = new MysqlUser;
$this->assertInstanceOf('MysqlUser', $user); $this->assertInstanceOf(MysqlUser::class, $user);
$this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection());
// Mysql User // Mysql User
$user->name = "John Doe"; $user->name = "John Doe";
$user->save(); $user->save();
$this->assertInternalType('int', $user->id); $this->assertIsInt($user->id);
// SQL has many // SQL has many
$book = new Book(['title' => 'Game of Thrones']); $book = new Book(['title' => 'Game of Thrones']);
...@@ -79,10 +82,10 @@ class HybridRelationsTest extends TestCase ...@@ -79,10 +82,10 @@ class HybridRelationsTest extends TestCase
{ {
$user = new MysqlUser; $user = new MysqlUser;
$otherUser = new MysqlUser; $otherUser = new MysqlUser;
$this->assertInstanceOf('MysqlUser', $user); $this->assertInstanceOf(MysqlUser::class, $user);
$this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection());
$this->assertInstanceOf('MysqlUser', $otherUser); $this->assertInstanceOf(MysqlUser::class, $otherUser);
$this->assertInstanceOf('Illuminate\Database\MySqlConnection', $otherUser->getConnection()); $this->assertInstanceOf(MySqlConnection::class, $otherUser->getConnection());
//MySql User //MySql User
$user->name = "John Doe"; $user->name = "John Doe";
...@@ -93,8 +96,8 @@ class HybridRelationsTest extends TestCase ...@@ -93,8 +96,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3; $otherUser->id = 3;
$otherUser->save(); $otherUser->save();
// Make sure they are created // Make sure they are created
$this->assertInternalType('int', $user->id); $this->assertIsInt($user->id);
$this->assertInternalType('int', $otherUser->id); $this->assertIsInt($otherUser->id);
// Clear to start // Clear to start
$user->books()->truncate(); $user->books()->truncate();
$otherUser->books()->truncate(); $otherUser->books()->truncate();
...@@ -133,10 +136,10 @@ class HybridRelationsTest extends TestCase ...@@ -133,10 +136,10 @@ class HybridRelationsTest extends TestCase
{ {
$user = new MysqlUser; $user = new MysqlUser;
$otherUser = new MysqlUser; $otherUser = new MysqlUser;
$this->assertInstanceOf('MysqlUser', $user); $this->assertInstanceOf(MysqlUser::class, $user);
$this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection());
$this->assertInstanceOf('MysqlUser', $otherUser); $this->assertInstanceOf(MysqlUser::class, $otherUser);
$this->assertInstanceOf('Illuminate\Database\MySqlConnection', $otherUser->getConnection()); $this->assertInstanceOf(MySqlConnection::class, $otherUser->getConnection());
//MySql User //MySql User
$user->name = "John Doe"; $user->name = "John Doe";
...@@ -147,8 +150,8 @@ class HybridRelationsTest extends TestCase ...@@ -147,8 +150,8 @@ class HybridRelationsTest extends TestCase
$otherUser->id = 3; $otherUser->id = 3;
$otherUser->save(); $otherUser->save();
// Make sure they are created // Make sure they are created
$this->assertInternalType('int', $user->id); $this->assertIsInt($user->id);
$this->assertInternalType('int', $otherUser->id); $this->assertIsInt($otherUser->id);
// Clear to start // Clear to start
Book::truncate(); Book::truncate();
MysqlBook::truncate(); MysqlBook::truncate();
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?php <?php
declare(strict_types=1);
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
class QueueTest extends TestCase class QueueTest extends TestCase
{ {
public function setUp() public function setUp(): void
{ {
parent::setUp(); parent::setUp();
...@@ -11,7 +14,7 @@ class QueueTest extends TestCase ...@@ -11,7 +14,7 @@ class QueueTest extends TestCase
Queue::getDatabase()->table(Config::get('queue.failed.table'))->truncate(); Queue::getDatabase()->table(Config::get('queue.failed.table'))->truncate();
} }
public function testQueueJobLifeCycle() public function testQueueJobLifeCycle(): void
{ {
$id = Queue::push('test', ['action' => 'QueueJobLifeCycle'], 'test'); $id = Queue::push('test', ['action' => 'QueueJobLifeCycle'], 'test');
$this->assertNotNull($id); $this->assertNotNull($id);
...@@ -24,6 +27,7 @@ class QueueTest extends TestCase ...@@ -24,6 +27,7 @@ class QueueTest extends TestCase
'displayName' => 'test', 'displayName' => 'test',
'job' => 'test', 'job' => 'test',
'maxTries' => null, 'maxTries' => null,
'delay' => null,
'timeout' => null, 'timeout' => null,
'data' => ['action' => 'QueueJobLifeCycle'], 'data' => ['action' => 'QueueJobLifeCycle'],
]), $job->getRawBody()); ]), $job->getRawBody());
...@@ -33,7 +37,7 @@ class QueueTest extends TestCase ...@@ -33,7 +37,7 @@ class QueueTest extends TestCase
$this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count()); $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'); $id = Queue::push('test', ['action' => 'QueueJobExpired'], 'test');
$this->assertNotNull($id); $this->assertNotNull($id);
...@@ -53,4 +57,38 @@ class QueueTest extends TestCase ...@@ -53,4 +57,38 @@ class QueueTest extends TestCase
$job->delete(); $job->delete();
$this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count()); $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.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
return [ return [
'default' => 'database', 'default' => env('QUEUE_CONNECTION'),
'connections' => [ 'connections' => [
...@@ -16,7 +16,7 @@ return [ ...@@ -16,7 +16,7 @@ return [
], ],
'failed' => [ 'failed' => [
'database' => 'mongodb', 'database' => env('MONGO_DATABASE'),
'table' => 'failed_jobs', 'table' => 'failed_jobs',
], ],
......
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