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

refactor: changed types and annotations 3 #247

Open
wants to merge 2 commits into
base: v3.x
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
123 changes: 75 additions & 48 deletions src/DataMapper/DataMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
*/
class DataMapper implements HasSchemaInterface
{
private bool $ignoreSoftDelete = false;

/**
* Name of the schema class to be used.
*/
Expand All @@ -46,6 +44,8 @@ class DataMapper implements HasSchemaInterface
*/
protected ?EventTriggerService $eventService = null;

private bool $ignoreSoftDelete = false;

/**
* @var array<string,null>
*/
Expand Down Expand Up @@ -114,7 +114,13 @@ public function save(ModelInterface $entity, array $options = []): bool
*/
public function insert(mixed $entity, array $options = [], bool $fireEvents = true): bool
{
if ($fireEvents && false === $this->fireEvent('inserting', $entity, true)) {
if (
$fireEvents && false === $this->fireEvent(
'inserting',
$entity,
true
)
) {
return false;
}

Expand Down Expand Up @@ -176,7 +182,11 @@ public function update(mixed $entity, array $options = []): bool
$filter = ['_id' => $data['_id']];
$updateOptions = $this->mergeOptions($options);

$queryResult = $collection->updateOne($filter, $updateData, $updateOptions);
$queryResult = $collection->updateOne(
$filter,
$updateData,
$updateOptions
);

if ($this->pullNullValues) {
$collection->updateOne(
Expand Down Expand Up @@ -220,7 +230,8 @@ public function delete(mixed $entity, array $options = []): bool
$this->mergeOptions($options)
);

if ($queryResult->isAcknowledged() &&
if (
$queryResult->isAcknowledged() &&
$queryResult->getDeletedCount()
) {
$this->fireEvent('deleted', $entity);
Expand All @@ -244,9 +255,11 @@ public function where(
array $projection = [],
bool $cacheable = false
): CursorInterface {
$cursorClass = $cacheable ? SchemaCacheableCursor::class : SchemaCursor::class;
$cursorClass = $cacheable
? SchemaCacheableCursor::class
: SchemaCursor::class;

$model = new $this->schema->entityClass;
$model = new $this->schema->entityClass();

$query = Resolver::resolveQuery(
$query,
Expand Down Expand Up @@ -296,7 +309,7 @@ public function first(
return $this->where($query, $projection, true)->first();
}

$model = new $this->schema->entityClass;
$model = new $this->schema->entityClass();

$query = Resolver::resolveQuery(
$query,
Expand Down Expand Up @@ -336,7 +349,9 @@ public function firstOrFail(
return $result;
}

throw (new ModelNotFoundException())->setModel($this->schema->entityClass);
throw (new ModelNotFoundException())->setModel(
$this->schema->entityClass
);
}

public function withoutSoftDelete(): self
Expand All @@ -346,6 +361,39 @@ public function withoutSoftDelete(): self
return $this;
}

/**
* Retrieves the Collection object.
*/
public function getCollection(): Collection
{
$database = $this->connection->defaultDatabase;
$collectionName = $this->schema->collection;
$options = [
'typeMap' => ['array' => 'array', 'document' => 'array'],
];

return $this->connection
->getClient()
->selectDatabase($database, $options)
->selectCollection($collectionName);
}

/**
* {@inheritdoc}
*/
public function getSchema(): Schema
{
return $this->schema;
}

/**
* Set a Schema object that describes an Entity in MongoDB.
*/
public function setSchema(Schema $schema): void
{
$this->schema = $schema;
}

/**
* Parses an object with SchemaMapper and the given Schema.
*
Expand Down Expand Up @@ -376,24 +424,10 @@ protected function getSchemaMapper(): SchemaMapper
$this->schema = Container::make($this->schemaClass);
}

return Container::make(SchemaMapper::class, ['schema' => $this->schema]);
}

/**
* Retrieves the Collection object.
*/
public function getCollection(): Collection
{
$database = $this->connection->defaultDatabase;
$collectionName = $this->schema->collection;
$options = [
'typeMap' => ['array' => 'array', 'document' => 'array']
];

return $this->connection
->getClient()
->selectDatabase($database, $options)
->selectCollection($collectionName);
return Container::make(
SchemaMapper::class,
['schema' => $this->schema]
);
}

/**
Expand All @@ -419,7 +453,7 @@ protected function getAssembler(): EntityAssembler
*/
protected function fireEvent(string $event, mixed $entity, bool $halt = false): mixed
{
$event = "mongolid.{$event}: ".$entity::class;
$event = "mongolid.{$event}: " . $entity::class;

if (!$this->eventService) {
$this->eventService = Container::make(EventTriggerService::class);
Expand Down Expand Up @@ -515,22 +549,6 @@ private function afterSuccess(mixed $entity): void
}
}

/**
* {@inheritdoc}
*/
public function getSchema(): Schema
{
return $this->schema;
}

/**
* Set a Schema object that describes an Entity in MongoDB.
*/
public function setSchema(Schema $schema): void
{
$this->schema = $schema;
}

private function getUpdateData($model, array $data): array
{
$this->pullNullValues = [];
Expand Down Expand Up @@ -564,9 +582,18 @@ private function calculateChanges(array &$changes, array $newData, array $oldDat

if (!isset($oldData[$k])) { // new field
$changes['$set']["{$keyfix}{$k}"] = $v;
} elseif ($oldData[$k] != $v) { // changed value
if (is_array($v) && is_array($oldData[$k]) && $v && $oldData[$k] !== []) { // check array recursively for changes
$this->calculateChanges($changes, $v, $oldData[$k], "{$keyfix}{$k}.");
} elseif ($oldData[$k] != $v) { // changed value
if (
is_array($v) && is_array(
$oldData[$k]
) && $v && [] !== $oldData[$k]
) { // check array recursively for changes
$this->calculateChanges(
$changes,
$v,
$oldData[$k],
"{$keyfix}{$k}."
);
} else {
if (is_array($v)) {
$v = $this->filterNullValues($v);
Expand All @@ -593,7 +620,7 @@ private function filterNullValues(array $data): array
{
$filtered = array_filter(
$data,
fn($value): bool => !is_null($value)
fn ($value): bool => !is_null($value)
);

if ($data == array_values($data)) {
Expand Down
5 changes: 4 additions & 1 deletion src/DataMapper/EntityAssembler.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ public function assemble(array|object $document, Schema $schema): mixed
$fieldType = $schema->fields[$field] ?? null;

if ($fieldType && str_starts_with($fieldType, 'schema.')) {
$value = $this->assembleDocumentsRecursively($value, substr($fieldType, 7));
$value = $this->assembleDocumentsRecursively(
$value,
substr($fieldType, 7)
);
}

$model->$field = $value;
Expand Down
25 changes: 12 additions & 13 deletions src/DataMapper/SchemaMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Mongolid\DataMapper;

use Mongolid\Container\Container;
use Mongolid\Container\Ioc;
use Mongolid\Schema\Schema;

/**
Expand Down Expand Up @@ -55,18 +54,6 @@ public function map(array|object $data): array
return $data;
}

/**
* If the schema is not dynamic, remove all non specified fields.
*
* @param array $data Reference of the fields. The passed array will be modified.
*/
protected function clearDynamic(array &$data): void
{
if (!$this->schema->dynamic) {
$data = array_intersect_key($data, $this->schema->fields);
}
}

/**
* Parse a value based on a field type of the schema.
*
Expand Down Expand Up @@ -105,6 +92,18 @@ public function parseField(mixed $value, string $fieldType): mixed
return $value;
}

/**
* If the schema is not dynamic, remove all non specified fields.
*
* @param array $data Reference of the fields. The passed array will be modified.
*/
protected function clearDynamic(array &$data): void
{
if (!$this->schema->dynamic) {
$data = array_intersect_key($data, $this->schema->fields);
}
}

/**
* Uses PHP's set type to cast a value to a type.
*
Expand Down
Loading
Loading