Skip to content

Commit

Permalink
Merge branch '4.2' into merge-4.1-into-4.2-1710254470287
Browse files Browse the repository at this point in the history
* 4.2:
  PHPORM-139 Implement `Model::createOrFirst()` using `findOneAndUpdate` operation (#2742)
  Test Laravel 10 and 11 (#2746)
  PHPORM-150 Run CI on Laravel 11 (#2735)
  PHPORM-152 Fix tests for Carbon 3 (#2733)
  • Loading branch information
alcaeus committed Mar 13, 2024
2 parents 74899f9 + 19fc801 commit 92efdda
Show file tree
Hide file tree
Showing 9 changed files with 157 additions and 18 deletions.
9 changes: 6 additions & 3 deletions .github/workflows/build-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,16 @@ jobs:
- "8.2"
- "8.3"
laravel:
- "10.*"
- "10.*"
- "11.*"
include:
- php: "8.1"
laravel: "10.*"
mongodb: "5.0"
mode: "low-deps"
exclude:
- php: "8.1"
laravel: "11.*"

steps:
- uses: "actions/checkout@v4"
Expand Down Expand Up @@ -76,8 +80,7 @@ jobs:
restore-keys: "${{ matrix.os }}-composer-"

- name: "Install dependencies"
run: composer update --no-interaction $([[ "${{ matrix.mode }}" == low-deps ]] && echo ' --prefer-lowest --prefer-stable')

run: composer update --no-interaction $([[ "${{ matrix.mode }}" == low-deps ]] && echo ' --prefer-lowest')
- name: "Run tests"
run: "./vendor/bin/phpunit --coverage-clover coverage.xml"
env:
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Changelog
All notable changes to this project will be documented in this file.

## [unreleased]

* Add support for Laravel 11 by @GromNaN in [#2735](https://github.com/mongodb/laravel-mongodb/pull/2735)
* Implement Model::createOrFirst() using findOneAndUpdate operation by @GromNaN in [#2742](https://github.com/mongodb/laravel-mongodb/pull/2742)

## [4.1.3] - 2024-03-05

* Fix the timezone of `datetime` fields when they are read from the database. By @GromNaN in [#2739](https://github.com/mongodb/laravel-mongodb/pull/2739)
Expand Down
14 changes: 6 additions & 8 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,21 @@
"require": {
"php": "^8.1",
"ext-mongodb": "^1.15",
"illuminate/support": "^10.0",
"illuminate/container": "^10.0",
"illuminate/database": "^10.30",
"illuminate/events": "^10.0",
"illuminate/support": "^10.0|^11",
"illuminate/container": "^10.0|^11",
"illuminate/database": "^10.30|^11",
"illuminate/events": "^10.0|^11",
"mongodb/mongodb": "^1.15"
},
"require-dev": {
"phpunit/phpunit": "^10.3",
"orchestra/testbench": "^8.0",
"orchestra/testbench": "^8.0|^9.0",
"mockery/mockery": "^1.4.4",
"doctrine/coding-standard": "12.0.x-dev",
"spatie/laravel-query-builder": "^5.6",
"phpstan/phpstan": "^1.10"
},
"minimum-stability": "dev",
"replace": {
"jenssegers/mongodb": "self.version"
},
Expand Down Expand Up @@ -66,9 +67,6 @@
"cs:fix": "phpcbf"
},
"config": {
"platform": {
"php": "8.1"
},
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
Expand Down
38 changes: 38 additions & 0 deletions src/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use MongoDB\Driver\Cursor;
use MongoDB\Laravel\Collection;
use MongoDB\Laravel\Helpers\QueriesRelationships;
use MongoDB\Laravel\Internal\FindAndModifyCommandSubscriber;
use MongoDB\Model\BSONDocument;

use function array_intersect_key;
use function array_key_exists;
use function array_merge;
use function collect;
Expand Down Expand Up @@ -183,6 +186,41 @@ public function raw($value = null)
return $results;
}

/**
* Attempt to create the record if it does not exist with the matching attributes.
* If the record exists, it will be returned.
*
* @param array $attributes The attributes to check for duplicate records
* @param array $values The attributes to insert if no matching record is found
*/
public function createOrFirst(array $attributes = [], array $values = []): Model
{
// Apply casting and default values to the attributes
$instance = $this->newModelInstance($values + $attributes);
$values = $instance->getAttributes();
$attributes = array_intersect_key($attributes, $values);

return $this->raw(function (Collection $collection) use ($attributes, $values) {
$listener = new FindAndModifyCommandSubscriber();
$collection->getManager()->addSubscriber($listener);

try {
$document = $collection->findOneAndUpdate(
$attributes,
['$setOnInsert' => $values],
['upsert' => true, 'new' => true, 'typeMap' => ['root' => 'array', 'document' => 'array']],
);
} finally {
$collection->getManager()->removeSubscriber($listener);
}

$model = $this->model->newFromBuilder($document);
$model->wasRecentlyCreated = $listener->created;

return $model;
});
}

/**
* Add the "updated at" column to an array of values.
* TODO Remove if https://github.com/laravel/framework/commit/6484744326531829341e1ff886cc9b628b20d73e
Expand Down
23 changes: 22 additions & 1 deletion src/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MongoDB\Laravel\Eloquent;

use BackedEnum;
use Carbon\CarbonInterface;
use DateTimeInterface;
use DateTimeZone;
Expand All @@ -23,6 +24,7 @@
use MongoDB\BSON\UTCDateTime;
use MongoDB\Laravel\Query\Builder as QueryBuilder;
use Stringable;
use ValueError;

use function array_key_exists;
use function array_keys;
Expand All @@ -40,10 +42,12 @@
use function is_string;
use function ltrim;
use function method_exists;
use function sprintf;
use function str_contains;
use function str_starts_with;
use function strcmp;
use function uniqid;
use function var_export;

abstract class Model extends BaseModel
{
Expand Down Expand Up @@ -695,7 +699,7 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
}

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

if ($castValue instanceof Arrayable) {
Expand All @@ -708,6 +712,23 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
return $attributes;
}

/**
* Duplicate of {@see HasAttributes::getStorableEnumValue()} for Laravel 11 as the signature of the method has
* changed in a non-backward compatible way.
*
* @todo Remove this method when support for Laravel 10 is dropped.
*/
private function getStorableEnumValueFromLaravel11($expectedEnum, $value)
{
if (! $value instanceof $expectedEnum) {
throw new ValueError(sprintf('Value [%s] is not of the expected enum type [%s].', var_export($value, true), $expectedEnum));
}

return $value instanceof BackedEnum
? $value->value
: $value->name;
}

/**
* Is a value a BSON type?
*
Expand Down
34 changes: 34 additions & 0 deletions src/Internal/FindAndModifyCommandSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace MongoDB\Laravel\Internal;

use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSubscriber;
use MongoDB\Driver\Monitoring\CommandSucceededEvent;

/**
* Track findAndModify command events to detect when a document is inserted or
* updated.
*
* @internal
*/
final class FindAndModifyCommandSubscriber implements CommandSubscriber
{
public bool $created;

public function commandFailed(CommandFailedEvent $event)
{
}

public function commandStarted(CommandStartedEvent $event)
{
}

public function commandSucceeded(CommandSucceededEvent $event)
{
$this->created = ! $event->getReply()->lastErrorObject->updatedExisting;
}
}
6 changes: 1 addition & 5 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -614,11 +614,7 @@ public function orderBy($column, $direction = 'asc')
return $this;
}

/**
* @param list{mixed, mixed}|CarbonPeriod $values
*
* @inheritdoc
*/
/** @inheritdoc */
public function whereBetween($column, iterable $values, $boolean = 'and', $not = false)
{
$type = 'between';
Expand Down
39 changes: 39 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1044,4 +1044,43 @@ public function testNumericFieldName(): void
$this->assertInstanceOf(User::class, $found);
$this->assertEquals([3 => 'two.three'], $found[2]);
}

public function testCreateOrFirst()
{
$user1 = User::createOrFirst(['email' => 'taylorotwell@gmail.com']);

$this->assertSame('taylorotwell@gmail.com', $user1->email);
$this->assertNull($user1->name);
$this->assertTrue($user1->wasRecentlyCreated);

$user2 = User::createOrFirst(
['email' => 'taylorotwell@gmail.com'],
['name' => 'Taylor Otwell', 'birthday' => new DateTime('1987-05-28')],
);

$this->assertEquals($user1->id, $user2->id);
$this->assertSame('taylorotwell@gmail.com', $user2->email);
$this->assertNull($user2->name);
$this->assertNull($user2->birthday);
$this->assertFalse($user2->wasRecentlyCreated);

$user3 = User::createOrFirst(
['email' => 'abigailotwell@gmail.com'],
['name' => 'Abigail Otwell', 'birthday' => new DateTime('1987-05-28')],
);

$this->assertNotEquals($user3->id, $user1->id);
$this->assertSame('abigailotwell@gmail.com', $user3->email);
$this->assertSame('Abigail Otwell', $user3->name);
$this->assertEquals(new DateTime('1987-05-28'), $user3->birthday);
$this->assertTrue($user3->wasRecentlyCreated);

$user4 = User::createOrFirst(
['name' => 'Dries Vints'],
['name' => 'Nuno Maduro', 'email' => 'nuno@laravel.com'],
);

$this->assertSame('Nuno Maduro', $user4->name);
$this->assertTrue($user4->wasRecentlyCreated);
}
}
7 changes: 6 additions & 1 deletion tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,12 @@ function (Builder $builder) {
yield 'whereBetween CarbonPeriod' => [
[
'find' => [
['created_at' => ['$gte' => new UTCDateTime($period->start), '$lte' => new UTCDateTime($period->end)]],
[
'created_at' => [
'$gte' => new UTCDateTime($period->getStartDate()),
'$lte' => new UTCDateTime($period->getEndDate()),
],
],
[], // options
],
],
Expand Down

0 comments on commit 92efdda

Please sign in to comment.