Skip to content

Laravel 10 compatibility #2506

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/build-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ jobs:
strategy:
matrix:
php:
- '8.0'
- '8.1'
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
Expand All @@ -41,8 +41,8 @@ jobs:
- '4.4'
- '5.0'
php:
- '8.0'
- '8.1'
- '8.2'
services:
mysql:
image: mysql:5.7
Expand All @@ -54,7 +54,7 @@ jobs:
MYSQL_ROOT_PASSWORD:

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Create MongoDB Replica Set
run: |
docker run --name mongodb -p 27017:27017 -e MONGO_INITDB_DATABASE=unittest --detach mongo:${{ matrix.mongodb }} mongod --replSet rs --setParameter transactionLifetimeLimitSeconds=5
Expand Down
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,6 @@ use Jenssegers\Mongodb\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;

protected $dates = ['deleted_at'];
}
```

Expand All @@ -279,7 +277,7 @@ use Jenssegers\Mongodb\Eloquent\Model;

class User extends Model
{
protected $dates = ['birthday'];
protected $casts = ['birthday' => 'datetime'];
}
```

Expand Down
20 changes: 10 additions & 10 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,16 @@
],
"license": "MIT",
"require": {
"illuminate/support": "^9.0",
"illuminate/container": "^9.0",
"illuminate/database": "^9.0",
"illuminate/events": "^9.0",
"mongodb/mongodb": "^1.11"
"illuminate/support": "^10.0",
"illuminate/container": "^10.0",
"illuminate/database": "^10.0",
"illuminate/events": "^10.0",
"mongodb/mongodb": "^1.15"
},
"require-dev": {
"phpunit/phpunit": "^9.5.8",
"orchestra/testbench": "^7.0",
"mockery/mockery": "^1.3.1",
"doctrine/dbal": "^2.13.3|^3.1.4"
"phpunit/phpunit": "^9.5.10",
"orchestra/testbench": "^8.0",
"mockery/mockery": "^1.4.4"
},
"autoload": {
"psr-4": {
Expand All @@ -54,5 +53,6 @@
"Jenssegers\\Mongodb\\MongodbQueueServiceProvider"
]
}
}
},
"minimum-stability": "dev"
}
3 changes: 2 additions & 1 deletion src/Auth/PasswordBrokerManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ protected function createTokenRepository(array $config)
$this->app['hash'],
$config['table'],
$this->app['config']['app.key'],
$config['expire']
$config['expire'],
$config['throttle'] ?? 0
);
}
}
23 changes: 0 additions & 23 deletions src/Auth/PasswordResetServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,6 @@

class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{
/**
* Register the token repository implementation.
*
* @return void
*/
protected function registerTokenRepository()
{
$this->app->singleton('auth.password.tokens', function ($app) {
$connection = $app['db']->connection();

// The database token repository is an implementation of the token repository
// interface, and is responsible for the actual storing of auth tokens and
// their e-mail addresses. We will inject this table and hash key to it.
$table = $app['config']['auth.password.table'];

$key = $app['config']['app.key'];

$expire = $app['config']->get('auth.password.expire', 60);

return new DatabaseTokenRepository($connection, $table, $key, $expire);
});
}

/**
* @inheritdoc
*/
Expand Down
81 changes: 67 additions & 14 deletions src/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@

namespace Jenssegers\Mongodb\Eloquent;

use function array_key_exists;
use DateTimeInterface;
use function explode;
use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use function in_array;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;
use function uniqid;

abstract class Model extends BaseModel
{
Expand Down Expand Up @@ -94,7 +99,7 @@ public function fromDateTime($value)
$value = parent::asDateTime($value);
}

return new UTCDateTime($value->format('Uv'));
return new UTCDateTime($value);
}

/**
Expand Down Expand Up @@ -182,7 +187,7 @@ protected function getAttributeFromArray($key)
/**
* @inheritdoc
*/
public function setAttribute($key, $value)
public function setAttribute($key, $value): static
{
// Convert _id to ObjectID.
if ($key == '_id' && is_string($value)) {
Expand All @@ -191,13 +196,14 @@ public function setAttribute($key, $value)
$value = $builder->convertKey($value);
} // Support keys in dot notation.
elseif (Str::contains($key, '.')) {
if (in_array($key, $this->getDates()) && $value) {
$value = $this->fromDateTime($value);
}
// Store to a temporary key, then move data to the actual key
$uniqueKey = uniqid($key);
parent::setAttribute($uniqueKey, $value);

Arr::set($this->attributes, $key, $value);
Arr::set($this->attributes, $key, $this->attributes[$uniqueKey] ?? null);
unset($this->attributes[$uniqueKey]);

return;
return $this;
}

return parent::setAttribute($key, $value);
Expand All @@ -222,13 +228,6 @@ public function attributesToArray()
}
}

// Convert dot-notation dates.
foreach ($this->getDates() as $key) {
if (Str::contains($key, '.') && Arr::has($attributes, $key)) {
Arr::set($attributes, $key, (string) $this->asDateTime(Arr::get($attributes, $key)));
}
}

return $attributes;
}

Expand Down Expand Up @@ -515,4 +514,58 @@ public function __call($method, $parameters)

return parent::__call($method, $parameters);
}

/**
* @inheritdoc
*/
protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes): array
{
foreach ($this->getCasts() as $key => $castType) {
if (! Arr::has($attributes, $key) || Arr::has($mutatedAttributes, $key)) {
continue;
}

$originalValue = Arr::get($attributes, $key);

// Here we will cast the attribute. Then, if the cast is a date or datetime cast
// then we will serialize the date for the array. This will convert the dates
// to strings based on the date format specified for these Eloquent models.
$castValue = $this->castAttribute(
$key, $originalValue
);

// If the attribute cast was a date or a datetime, we will serialize the date as
// a string. This allows the developers to customize how dates are serialized
// into an array without affecting how they are persisted into the storage.
if ($castValue !== null && in_array($castType, ['date', 'datetime', 'immutable_date', 'immutable_datetime'])) {
$castValue = $this->serializeDate($castValue);
}

if ($castValue !== null && ($this->isCustomDateTimeCast($castType) ||
$this->isImmutableCustomDateTimeCast($castType))) {
$castValue = $castValue->format(explode(':', $castType, 2)[1]);
}

if ($castValue instanceof DateTimeInterface &&
$this->isClassCastable($key)) {
$castValue = $this->serializeDate($castValue);
}

if ($castValue !== null && $this->isClassSerializable($key)) {
$castValue = $this->serializeClassCastableAttribute($key, $castValue);
}

if ($this->isEnumCastable($key) && (! $castValue instanceof Arrayable)) {
$castValue = $castValue !== null ? $this->getStorableEnumValue($attributes[$key]) : null;
}

if ($castValue instanceof Arrayable) {
$castValue = $castValue->toArray();
}

Arr::set($attributes, $key, $castValue);
}

return $attributes;
}
}
6 changes: 3 additions & 3 deletions src/Relations/EmbedsMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function performInsert(Model $model)
}

// Push the new model to the database.
$result = $this->getBaseQuery()->push($this->localKey, $model->getAttributes(), true);
$result = $this->toBase()->push($this->localKey, $model->getAttributes(), true);

// Attach the model to its parent.
if ($result) {
Expand Down Expand Up @@ -83,7 +83,7 @@ public function performUpdate(Model $model)
$values = $this->getUpdateValues($model->getDirty(), $this->localKey.'.$.');

// Update document in database.
$result = $this->getBaseQuery()->where($this->localKey.'.'.$model->getKeyName(), $foreignKey)
$result = $this->toBase()->where($this->localKey.'.'.$model->getKeyName(), $foreignKey)
->update($values);

// Attach the model to its parent.
Expand Down Expand Up @@ -112,7 +112,7 @@ public function performDelete(Model $model)
// Get the correct foreign key value.
$foreignKey = $this->getForeignKeyValue($model);

$result = $this->getBaseQuery()->pull($this->localKey, [$model->getKeyName() => $foreignKey]);
$result = $this->toBase()->pull($this->localKey, [$model->getKeyName() => $foreignKey]);

if ($result) {
$this->dissociate($model);
Expand Down
16 changes: 8 additions & 8 deletions src/Relations/EmbedsOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function getEager()
/**
* Save a new model and attach it to the parent model.
*
* @param Model $model
* @param Model $model
* @return Model|bool
*/
public function performInsert(Model $model)
Expand All @@ -50,7 +50,7 @@ public function performInsert(Model $model)
return $this->parent->save() ? $model : false;
}

$result = $this->getBaseQuery()->update([$this->localKey => $model->getAttributes()]);
$result = $this->toBase()->update([$this->localKey => $model->getAttributes()]);

// Attach the model to its parent.
if ($result) {
Expand All @@ -63,7 +63,7 @@ public function performInsert(Model $model)
/**
* Save an existing model and attach it to the parent model.
*
* @param Model $model
* @param Model $model
* @return Model|bool
*/
public function performUpdate(Model $model)
Expand All @@ -76,7 +76,7 @@ public function performUpdate(Model $model)

$values = $this->getUpdateValues($model->getDirty(), $this->localKey.'.');

$result = $this->getBaseQuery()->update($values);
$result = $this->toBase()->update($values);

// Attach the model to its parent.
if ($result) {
Expand All @@ -101,7 +101,7 @@ public function performDelete()
}

// Overwrite the local key with an empty array.
$result = $this->getBaseQuery()->update([$this->localKey => null]);
$result = $this->toBase()->update([$this->localKey => null]);

// Detach the model from its parent.
if ($result) {
Expand All @@ -114,7 +114,7 @@ public function performDelete()
/**
* Attach the model to its parent.
*
* @param Model $model
* @param Model $model
* @return Model
*/
public function associate(Model $model)
Expand Down Expand Up @@ -145,8 +145,8 @@ public function delete()
/**
* Get the name of the "where in" method for eager loading.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @return string
*/
protected function whereInMethod(EloquentModel $model, $key)
Expand Down
Loading