Skip to content
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

Migrate to LM 4 #40

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ You can see the new article on the category page because the package synchronize
```bash
composer require offlineagency/laravel-mongo-auto-sync
```
### Laravel version Compatibility

| Laravel | Package |
| ----------- | ----------- |
| 5.8.x | 1.x |
| 6.x | 1.x |
| 7.x | <Badge text="TO BE TEST" type="warning"/> 2.0-alpha.1 (Pre-release) |

## Documentation
You can find the documentation [here](https://docs.offlineagency.com/laravel-mongo-auto-sync/)
Expand Down
22 changes: 11 additions & 11 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@
"type": "library",
"keywords": ["laravel","database","mongodb","eloquent", "relationships"],
"require": {
"php": ">=7.1",
"php": ">=7.2",
"ext-json": "*",
"ext-mongodb": "*",
"illuminate/support": "^5.8|^6.0",
"illuminate/container": "^5.8|^6.0",
"illuminate/database": "^5.8|^6.0",
"illuminate/events": "^5.8|^6.0",
"jenssegers/mongodb": "3.6.4"
"illuminate/support": "^7.0",
"illuminate/container": "^7.0",
"illuminate/database": "^7.0",
"illuminate/events": "^7.0",
"mongodb/mongodb": "^1.6",
"jenssegers/mongodb": "4.0.0-alpha.1"
},
"require-dev": {
"phpunit/phpunit": "^6.0|^7.0|^8.0",
"orchestra/testbench": "^3.1|^4.0",
"mockery/mockery": "^1.0",
"doctrine/dbal": "^2.5",
"phpunit/phpcov": "^6.0",
"phpunit/phpunit": "^8.4",
"orchestra/testbench": "^5.0",
"mockery/mockery": "^1.3.1",
"doctrine/dbal": "^2.6",
"cedx/coveralls": "^11.2"
},
"license": "MIT",
Expand Down
178 changes: 178 additions & 0 deletions src/Eloquent/Builder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
<?php

namespace OfflineAgency\MongoAutoSync\Eloquent;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Jenssegers\Mongodb\Eloquent\Builder as MongoDbEloquentBuilder;

class Builder extends MongoDbEloquentBuilder
{
/**
* {@inheritdoc}
*/
public function update(array $values, array $options = [])
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$relation->performUpdate($this->model, $values);

return 1;
}

return $this->toBase()->update($this->addUpdatedAtColumn($values), $options);
}

/**
* {@inheritdoc}
*/
public function insert(array $values)
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$relation->performInsert($this->model, $values);

return true;
}

return EloquentBuilder::insert($values);
}

/**
* {@inheritdoc}
*/
public function insertGetId(array $values, $sequence = null)
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$relation->performInsert($this->model, $values);

return $this->model->getKey();
}

return EloquentBuilder::insertGetId($values, $sequence);
}

/**
* {@inheritdoc}
*/
public function delete()
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$relation->performDelete($this->model);

return $this->model->getKey();
}

return EloquentBuilder::delete();
}

/**
* {@inheritdoc}
*/
public function increment($column, $amount = 1, array $extra = [])
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$value = $this->model->{$column};

// When doing increment and decrements, Eloquent will automatically
// sync the original attributes. We need to change the attribute
// temporary in order to trigger an update query.
$this->model->{$column} = null;

$this->model->syncOriginalAttribute($column);

$result = $this->model->update([$column => $value]);

return $result;
}

return EloquentBuilder::increment($column, $amount, $extra);
}

/**
* {@inheritdoc}
*/
public function decrement($column, $amount = 1, array $extra = [])
{
// Intercept operations on embedded models and delegate logic
// to the parent relation instance.
if ($relation = $this->model->getParentRelation()) {
$value = $this->model->{$column};

// When doing increment and decrements, Eloquent will automatically
// sync the original attributes. We need to change the attribute
// temporary in order to trigger an update query.
$this->model->{$column} = null;

$this->model->syncOriginalAttribute($column);

return $this->model->update([$column => $value]);
}

return EloquentBuilder::decrement($column, $amount, $extra);
}

/**
* {@inheritdoc}
*/
public function chunkById($count, callable $callback, $column = '_id', $alias = null)
{
return EloquentBuilder::chunkById($count, $callback, $column, $alias);
}

/**
* {@inheritdoc}
*/
public function raw($expression = null)
{
// Get raw results from the query builder.
$results = $this->query->raw($expression);

// Convert MongoCursor results to a collection of models.
if ($results instanceof Cursor) {
$results = iterator_to_array($results, false);

return $this->model->hydrate($results);
} // Convert Mongo BSONDocument to a single object.
elseif ($results instanceof BSONDocument) {
$results = $results->getArrayCopy();

return $this->model->newFromBuilder((array) $results);
} // The result is a single object.
elseif (is_array($results) && array_key_exists('_id', $results)) {
return $this->model->newFromBuilder((array) $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;
}
}
78 changes: 78 additions & 0 deletions src/Eloquent/EmbedsRelationships.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace OfflineAgency\MongoAutoSync\Eloquent;

use Illuminate\Support\Str;
use OfflineAgency\MongoAutoSync\Relationships\EmbedsMany;
use OfflineAgency\MongoAutoSync\Relationships\EmbedsOne;

trait EmbedsRelationships
{
/**
* Define an embedded one-to-many relationship.
* @param string $related
* @param string $localKey
* @param string $foreignKey
* @param string $relation
* @return EmbedsMany
*/
protected function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null)
{
// If no relation name was given, we will use this debug backtrace to extract
// the calling method's name and use that as the relationship name as most
// of the time this will be what we desire to use for the relationships.
if ($relation === null) {
[, $caller] = debug_backtrace(false);

$relation = $caller['function'];
}

if ($localKey === null) {
$localKey = $relation;
}

if ($foreignKey === null) {
$foreignKey = Str::snake(class_basename($this));
}

$query = $this->newQuery();

$instance = new $related;

return new EmbedsMany($query, $this, $instance, $localKey, $foreignKey, $relation);
}

/**
* Define an embedded one-to-many relationship.
* @param string $related
* @param string $localKey
* @param string $foreignKey
* @param string $relation
* @return EmbedsOne
*/
protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null)
{
// If no relation name was given, we will use this debug backtrace to extract
// the calling method's name and use that as the relationship name as most
// of the time this will be what we desire to use for the relationships.
if ($relation === null) {
[, $caller] = debug_backtrace(false);

$relation = $caller['function'];
}

if ($localKey === null) {
$localKey = $relation;
}

if ($foreignKey === null) {
$foreignKey = Str::snake(class_basename($this));
}

$query = $this->newQuery();

$instance = new $related;

return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation);
}
}
58 changes: 58 additions & 0 deletions src/Eloquent/Model.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace OfflineAgency\MongoAutoSync\Eloquent;

use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Eloquent\Model as MongoDbModel;

class Model extends MongoDbModel
{
use EmbedsRelationships;

/**
* {@inheritdoc}
*/
public function setAttribute($key, $value)
{
// Convert _id to ObjectID.
if ($key == '_id' && is_string($value)) {
$builder = $this->newBaseQueryBuilder();

$value = $builder->convertKey($value);
} // Support keys in dot notation.
elseif (Str::contains($key, '.')) {
if (in_array($key, $this->getDates()) && $value) {
$value = $this->fromDateTime($value);
}

Arr::set($this->attributes, $key, $value);

return;
}

return BaseModel::setAttribute($key, $value);
}

/**
* {@inheritdoc}
*/
public function getAttribute($key)
{
// This checks for embedded relation support.
if (method_exists($this, $key) && ! method_exists(self::class, $key)) {
return $this->getRelationValue($key);
}

return BaseModel::getAttribute($key);
}

/**
* {@inheritdoc}
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
}
2 changes: 1 addition & 1 deletion src/Http/Models/MDModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace OfflineAgency\MongoAutoSync\Http\Models;

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use OfflineAgency\MongoAutoSync\Eloquent\Model as Eloquent;
use OfflineAgency\MongoAutoSync\Traits\Helper;
use OfflineAgency\MongoAutoSync\Traits\MainMongoTrait;
use OfflineAgency\MongoAutoSync\Traits\ModelAdditionalMethod;
Expand Down
Loading