Skip to content

Commit

Permalink
To builder and model added unsetField method; Updated events; Fixed b…
Browse files Browse the repository at this point in the history
…ug in casts to id; #3;
  • Loading branch information
DenchikBY committed Jan 16, 2016
1 parent e0e467d commit 284f1f5
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 25 deletions.
37 changes: 37 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,25 @@ or init and save in db
$user = User::create(['name' => 'DenchikBY']);
```

Methods
---------

To array:

```php
$ad = Ads::init()->first();
var_dump($ad->toArray()); // array of all fields
var_dump($ad->toArray(['include' => ['id', 'name']])); // array of specified fields
var_dump($ad->toArray(['exclude' => ['user_id']])); // array of all fields except specified
```

Unset field:

```php
$ad = Ads::init()->first();
$ad->unsetField('counters.views');
```

Attributes Casting
-------------

Expand Down Expand Up @@ -243,6 +262,22 @@ class User extends Model {
}
```

Events
-------------

Existed events before/after for actions save, create, update, delete.

```php
class User extends Model {

public function afterCreate()
{
Email::send($this->email, 'emails.succeddfull_registration', ['user' => $this]);
}

}
```

Query Builder
-------------

Expand Down Expand Up @@ -307,6 +342,8 @@ $age = $builder->min('age');
$age = $builder->avg('age');

$total = $builder->sum('age');

$builder->unsetField('counters.views');
```

Advanced Wheres
Expand Down
138 changes: 113 additions & 25 deletions src/MongoDB/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
namespace DenchikBY\MongoDB;

use DenchikBY\MongoDB\Query\Builder;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime;
use Phalcon\Di;
use Phalcon\Text;

abstract class Model extends \MongoDB\Collection
class Model extends \MongoDB\Collection
{

protected $_id, $_attributes = [], $_relations = [];
Expand All @@ -30,12 +32,15 @@ public static function init($attributes = [])

public static function create(array $attributes)
{
return static::init($attributes)->save();
$model = static::init($attributes)->save();
$model->event('afterCreate');
$model->event('afterSave');
return $model;
}

public static function findById($id)
{
$result = static::init()->findOne(['_id' => new \MongoDB\BSON\ObjectId($id)]);
$result = static::init()->findOne(['_id' => new ObjectID($id)]);
return $result ? static::init((array)$result) : null;
}

Expand All @@ -46,7 +51,7 @@ public static function findFirst(array $params = [])

public static function destroy($id)
{
return static::init()->deleteOne(['_id' => new \MongoDB\BSON\ObjectId($id)]);
return static::init()->deleteOne(['_id' => new ObjectID($id)]);
}

public static function getSource()
Expand All @@ -62,6 +67,11 @@ public static function getDbName()
return self::$_db;
}

public static function mongoTime()
{
return new UTCDateTime(round(microtime(true) * 1000) . '');
}

public function find($filter = [], array $options = [], $fillModels = true)
{
return $this->getQueryResult(parent::find($filter, $options), $fillModels);
Expand Down Expand Up @@ -121,24 +131,28 @@ public function save(array $attributes = null)
if ($attributes != null) {
$this->fill($attributes);
}
$this->beforeSave();
$this->event('beforeSave');
if (isset($this->_id)) {
$this->beforeUpdate();
$this->event('beforeUpdate');
$this->updateOne(['_id' => $this->_id], ['$set' => $this->_attributes]);
$this->event('afterUpdate');
} else {
$this->beforeCreate();
$result = $this->insertOne($this->_attributes);
return $this->fill($result);
$this->event('beforeCreate');
$this->fill($this->insertOne($this->_attributes));
$this->event('afterCreate');
}
$this->event('afterSave');
return $this;
}

public function update(array $attributes)
{
$this->beforeSave();
$this->beforeUpdate();
$this->event('beforeSave');
$this->event('beforeUpdate');
$this->fill($attributes);
$this->updateOne(['_id' => $this->_id], ['$set' => $attributes]);
$this->event('afterUpdate');
$this->event('afterSave');
return $this;
}

Expand All @@ -158,21 +172,44 @@ public function decrement($argument, $value = 1)

public function delete()
{
return $this->deleteOne(['_id' => $this->getId(false)]);
$this->event('beforeDelete');
$this->deleteOne(['_id' => $this->getId(false)]);
$this->event('afterDelete');
return $this;
}

public function beforeCreate()
public function unsetField($field)
{
$this->created_at = new \MongoDB\BSON\UTCDateTime(round(microtime(true) * 1000) . '');
$path = explode('.', $field);
$lastPart = end($path);
if (count($path) > 1) {
$ref = $this->getAttrRef($field, 1);
} else {
$ref = &$this->_attributes;
}
if ($ref != false) {
$type = gettype($ref);
if ($type == 'object' && isset($ref->{$lastPart})) {
unset($ref->{$lastPart});
} else if ($type == 'array' && isset($ref[$lastPart])) {
unset($ref[$lastPart]);
} else {
return false;
}
$this->updateOne(['_id' => $this->_id], ['$unset' => [$field => '']]);
return true;
}
return false;
}

public function beforeUpdate()
public function beforeCreate()
{
$this->updated_at = new \MongoDB\BSON\UTCDateTime(round(microtime(true) * 1000) . '');
$this->created_at = self::mongoTime();
}

public function beforeSave()
public function beforeUpdate()
{
$this->updated_at = self::mongoTime();
}

protected function castArrayAttributes(array $data)
Expand All @@ -189,7 +226,14 @@ public function castAttribute($param, $value)
if (isset(static::$casts[$param])) {
$type = static::$casts[$param];
if ($type == 'id') {
return ($value instanceof \MongoDB\BSON\ObjectId) ? $value : new \MongoDB\BSON\ObjectId((string)$value);
if (!($value instanceof ObjectID)) {
try {
return new ObjectID((string)$value);
} catch (\Exception $e) {
return null;
}
}
return $value;
} else if (in_array($type, ['integer', 'float', 'boolean', 'string', 'array', 'object'])) {
settype($value, $type);
}
Expand Down Expand Up @@ -241,15 +285,28 @@ protected function getIdFieldName($model)
return $className . '_id';
}

public function toArray()
public function toArray($params = [])
{
$this->_attributes = array_map(function ($item) {
$attributes = array_merge(['id' => (string)$this->_id], $this->_attributes);
if (isset($params['include']) || isset($params['exclude'])) {
$attributes = array_filter($attributes, function ($value, $key) use ($params) {
if (isset($params['include'])) {
return in_array($key, $params['include']);
}
return !in_array($key, $params['exclude']);
}, ARRAY_FILTER_USE_BOTH);
}
$attributes = array_map(function ($item) {
if (gettype($item) == 'object') {
return (string)$item;
if ($item instanceof ObjectID) {
return (string)$item;
} else {
return (array)$item;
}
}
return $item;
}, $this->_attributes);
$this->_relations = array_map(function ($item) {
}, $attributes);
$relations = array_map(function ($item) {
if (gettype($item) == 'object') {
return $item->toArray();
} else if (gettype($item) == 'array') {
Expand All @@ -259,11 +316,42 @@ public function toArray()
}
return $item;
}, $this->_relations);
$result = array_merge($this->_attributes, $this->_relations);
$result['id'] = (string)$this->_id;
$result = array_merge($attributes, $relations);
return $result;
}

protected function event($name)
{
if (method_exists($this, $name)) {
$this->{$name}();
}
}

protected function getAttrRef($path, $rightOffset = 0)
{
$path = explode('.', $path);
$length = count($path) - $rightOffset;
$return = &$this->_attributes;
for ($i = 0; $i <= $length - 1; ++$i) {
if (isset($return->{$path[$i]})) {
if ($i == $length - 1) {
return $return->{$path[$i]};
} else {
$return = &$return->{$path[$i]};
}
} else if (isset($return[$path[$i]])) {
if ($i == $length - 1) {
return $return[$path[$i]];
} else {
$return = &$return[$path[$i]];
}
} else {
return false;
}
}
return $return;
}

public static function query()
{
return new Builder(static::class);
Expand Down
5 changes: 5 additions & 0 deletions src/MongoDB/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,11 @@ public function sum($field)
return $this->_modelObject->aggregate($this->getQuery(), [], false)[0]->result;
}

public function unsetField($field)
{
return $this->_modelObject->updateMany($this->_match, ['$unset' => [$field => '']]);
}

protected function getOptions()
{
$result = [];
Expand Down

0 comments on commit 284f1f5

Please sign in to comment.