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 #246

Merged
merged 1 commit into from
Oct 9, 2024
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
7 changes: 6 additions & 1 deletion src/Cursor/CacheableCursor.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ class CacheableCursor extends Cursor
protected function getCursor(): Iterator
{
// Returns original (non-cached) cursor
if ($this->ignoreCache || $this->position >= self::DOCUMENT_LIMIT) {
if ($this->ignoreCache) {
return $this->getOriginalCursor();
}

// Returns original (non-cached) cursor
if ($this->position >= self::DOCUMENT_LIMIT) {
return $this->getOriginalCursor();
}

Expand Down
7 changes: 6 additions & 1 deletion src/Cursor/SchemaCacheableCursor.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@ class SchemaCacheableCursor extends SchemaCursor
protected function getCursor(): Iterator
{
// Returns original (non-cached) cursor
if ($this->ignoreCache || $this->position >= self::DOCUMENT_LIMIT) {
if ($this->ignoreCache) {
return $this->getOriginalCursor();
}

// Returns original (non-cached) cursor
if ($this->position >= self::DOCUMENT_LIMIT) {
return $this->getOriginalCursor();
}

Expand Down
10 changes: 7 additions & 3 deletions src/DataMapper/SchemaMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,14 @@ public function parseField(mixed $value, string $fieldType): mixed
if (method_exists($this->schema, $fieldType)) {
return $this->schema->$fieldType($value);
}

// Returns null or an empty array
if (null === $value) {
return $value;
}

// Returns null or an empty array
if (null === $value || is_array($value) && empty($value)) {
if (is_array($value) && empty($value)) {
return $value;
}

Expand All @@ -106,8 +112,6 @@ public function parseField(mixed $value, string $fieldType): mixed
*
* @param mixed $value value to be casted
* @param string $type type to which the $value should be casted to
*
* @return mixed
*/
protected function cast(mixed $value, string $type): mixed
{
Expand Down
56 changes: 20 additions & 36 deletions src/LegacyRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,27 +30,23 @@ class LegacyRecord implements ModelInterface, HasSchemaInterface
/**
* Name of the collection where this kind of Entity is going to be saved or
* retrieved from.
*
* @var string
*/
protected $collection = null;
protected ?string $collection = null;

/**
* @see https://docs.mongodb.com/manual/reference/write-concern/
*
* @var int
*/
protected $writeConcern = 1;
protected int $writeConcern = 1;

/**
* Describes the Schema fields of the model. Optionally you can set it to
* the name of a Schema class to be used.
*
* @see Mongolid\Schema\Schema::$fields
*
* @var string|string[]
*/
protected $fields = [
* @var string[] | string
*/
protected array | string $fields = [
'_id' => 'objectId',
'created_at' => 'createdAtTimestamp',
'updated_at' => 'updatedAtTimestamp',
Expand All @@ -61,21 +57,17 @@ class LegacyRecord implements ModelInterface, HasSchemaInterface
* that are not specified in the $fields property. This is useful if you
* does not have a strict document format or if you want to take full
* advantage of the "schemaless" nature of MongoDB.
*
* @var bool
*/
public $dynamic = true;
public bool $dynamic = true;

/**
* This attribute is used to eager load models for
* referenced ids. You can eager load any children
* models using this parameter. Every time this
* model is queried, it will load its referenced
* models together.
*
* @var array
*/
public $with = [];
public array $with = [];

/**
* Whether the model should manage the `created_at` and `updated_at`
Expand Down Expand Up @@ -220,26 +212,24 @@ public static function firstOrNew($id)
/**
* Handle dynamic method calls into the model.
*
* @param mixed $method name of the method that is being called
* @param mixed $parameters parameters of $method
* @param string $method name of the method that is being called
* @param array $parameters parameters of $method
*
* @throws BadMethodCallException in case of invalid methods be called
*
* @return mixed
*/
public function __call($method, $parameters)
public function __call(string $method, array $parameters): mixed
{
$value = $parameters[0] ?? null;

// Alias to attach
if ('attachTo' == substr($method, 0, 8)) {
if (str_starts_with($method, 'attachTo')) {
$field = lcfirst(substr($method, 8));

return $this->attach($field, $value);
}

// Alias to embed
if ('embedTo' == substr($method, 0, 7)) {
if (str_starts_with($method, 'embedTo')) {
$field = lcfirst(substr($method, 7));

return $this->embed($field, $value);
Expand All @@ -248,7 +238,7 @@ public function __call($method, $parameters)
throw new BadMethodCallException(
sprintf(
'The following method can not be reached or does not exist: %s@%s',
get_class($this),
static::class,
$method
)
);
Expand Down Expand Up @@ -277,7 +267,7 @@ public function getCollectionName(): string
throw new NoCollectionNameException();
}

return $this->collection ? $this->collection : $this->getSchema()->collection;
return $this->getSchema()->collection;
}

/**
Expand Down Expand Up @@ -308,7 +298,7 @@ public function getSchema(): Schema
}

$schema = new DynamicSchema();
$schema->entityClass = get_class($this);
$schema->entityClass = static::class;
$schema->fields = $this->fields;
$schema->dynamic = $this->dynamic;
$schema->collection = $this->collection;
Expand All @@ -319,26 +309,24 @@ public function getSchema(): Schema
/**
* Will check if the current value of $fields property is the name of a
* Schema class and instantiate it if possible.
*
* @return Schema|null
*/
protected function instantiateSchemaInFields()
protected function instantiateSchemaInFields(): ?Schema
{
if (is_string($this->fields)) {
if (is_subclass_of($instance = Container::make($this->fields), Schema::class)) {
return $instance;
}
}

return null;
}

/**
* Performs the given action into database.
*
* @param string $action datamapper function to execute
*
* @return bool
*/
protected function execute(string $action)
protected function execute(string $action): bool
{
if (!$this->getCollectionName()) {
return false;
Expand All @@ -364,7 +352,7 @@ protected function execute(string $action)
*/
protected static function getDataMapperInstance()
{
$instance = Container::make(get_called_class());
$instance = Container::make(static::class);

if (!$instance->getCollectionName()) {
throw new NoCollectionNameException();
Expand All @@ -389,10 +377,6 @@ public function bsonSerialize(): object|array
->map($this, array_merge($this->fillable, $this->guarded), $this->dynamic, $this->timestamps);
}

/**
* @param array $data
* @return void
*/
public function bsonUnserialize(array $data): void
{
$this->fill($data, true);
Expand Down
3 changes: 1 addition & 2 deletions src/Model/AbstractModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,10 @@ public function delete(): bool

/**
* Query model on database to retrieve an updated version of its attributes.
* @return self
*/
public function fresh(): self
{
return $this->first($this->_id);
return static::first($this->_id);
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/Model/AttributesService.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
<?php
namespace Mongolid\Model;

use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Str;
use JsonException;
use Mongolid\Container\Container;
use stdClass;

class AttributesService
{
Expand Down Expand Up @@ -53,6 +56,7 @@ class AttributesService

/**
* {@inheritdoc}
* @throws JsonException|BindingResolutionException
*/
public static function fill(
array $input,
Expand Down Expand Up @@ -80,7 +84,7 @@ public static function fill(
if ($force
|| ((!$object->fillable || in_array($key, $object->fillable)) && !in_array($key, $object->guarded))) {
if ($value instanceof stdClass) {
$value = json_decode(json_encode($value), true); // cast to array
$value = json_decode(json_encode($value, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); // cast to array
}

$object->setDocumentAttribute($key, $value);
Expand Down
6 changes: 0 additions & 6 deletions src/Model/Casts/DateTime/BaseDateTimeCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,8 @@

abstract class BaseDateTimeCast implements CastInterface
{
/**
* @param UTCDateTime|null $value
*/
abstract public function get(mixed $value): ?DateTimeInterface;

/**
* @param DateTimeInterface|UTCDateTimeInterface|null $value
*/
public function set(mixed $value): UTCDateTime|null
{
if (is_null($value)) {
Expand Down
3 changes: 0 additions & 3 deletions src/Model/Casts/DateTime/DateTimeCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@

class DateTimeCast extends BaseDateTimeCast
{
/**
* @param UTCDateTime|null $value
*/
public function get(mixed $value): ?DateTime
{
if (is_null($value)) {
Expand Down
3 changes: 0 additions & 3 deletions src/Model/Casts/DateTime/ImmutableDateTimeCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@

class ImmutableDateTimeCast extends BaseDateTimeCast
{
/**
* @param UTCDateTime|null $value
*/
public function get(mixed $value): ?DateTimeImmutable
{
if (is_null($value)) {
Expand Down
1 change: 1 addition & 0 deletions src/Model/Exception/InvalidFieldNameException.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Mongolid\Model\Exception;

use LogicException;
Expand Down
1 change: 1 addition & 0 deletions src/Model/Exception/ModelNotFoundException.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Mongolid\Model\Exception;

use RuntimeException;
Expand Down
5 changes: 4 additions & 1 deletion src/Model/HasAttributesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
namespace Mongolid\Model;

use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Str;
use JsonException;
use Mongolid\Container\Container;
use Mongolid\Model\Casts\CastResolver;
use stdClass;
Expand Down Expand Up @@ -71,6 +73,7 @@ trait HasAttributesTrait

/**
* {@inheritdoc}
* @throws JsonException|BindingResolutionException
*/
public static function fill(
array $input,
Expand Down Expand Up @@ -98,7 +101,7 @@ public static function fill(
if ($force
|| ((!$object->fillable || in_array($key, $object->fillable)) && !in_array($key, $object->guarded))) {
if ($value instanceof stdClass) {
$value = json_decode(json_encode($value), true); // cast to array
$value = json_decode(json_encode($value, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); // cast to array
}

$object->setDocumentAttribute($key, $value);
Expand Down
10 changes: 8 additions & 2 deletions src/Model/HasLegacyAttributesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,15 @@ public function fill(array $input, bool $force = false): HasAttributesInterface
continue;
}

if ((empty($this->fillable) || in_array($key, $this->fillable)) && !in_array($key, $this->guarded)) {
$this->setAttribute($key, $value);
if (!(empty($this->fillable) || in_array($key, $this->fillable))) {
continue;
}

if (in_array($key, $this->guarded)) {
continue;
}

$this->setAttribute($key, $value);
}

return $this;
Expand Down
Loading
Loading