diff --git a/composer.json b/composer.json index 54118d3..c374a24 100644 --- a/composer.json +++ b/composer.json @@ -15,25 +15,25 @@ "pull-request": "https://github.com/hyperf/hyperf/pulls" }, "require": { - "php": ">=8.1", - "hyperf/code-parser": "~3.1.0", - "hyperf/collection": "~3.1.23", - "hyperf/conditionable": "~3.1.0", - "hyperf/context": "~3.1.0", - "hyperf/contract": "~3.1.0", + "php": ">=8.2", + "hyperf/code-parser": "~3.2.0", + "hyperf/collection": "~3.2.0", + "hyperf/conditionable": "~3.2.0", + "hyperf/context": "~3.2.0", + "hyperf/contract": "~3.2.0", "hyperf/engine": "^2.0", - "hyperf/macroable": "~3.1.0", - "hyperf/stringable": "~3.1.0", - "hyperf/support": "~3.1.0", - "hyperf/tappable": "~3.1.0", - "nesbot/carbon": "^2.0", + "hyperf/macroable": "~3.2.0", + "hyperf/stringable": "~3.2.0", + "hyperf/support": "~3.2.0", + "hyperf/tappable": "~3.2.0", + "nesbot/carbon": "^2.0 || ^3.0", "psr/container": "^1.0 || ^2.0", "psr/event-dispatcher": "^1.0" }, "suggest": { "doctrine/dbal": "Required to rename columns (^3.0).", - "hyperf/paginator": "Required to paginate the result set (~3.1.0).", - "nikic/php-parser": "Required to use ModelCommand. (^4.0)", + "hyperf/paginator": "Required to paginate the result set (~3.2.0).", + "nikic/php-parser": "Required to use ModelCommand. (^5.0)", "php-di/phpdoc-reader": "Required to use ModelCommand. (^2.2)" }, "autoload": { @@ -51,7 +51,7 @@ }, "extra": { "branch-alias": { - "dev-master": "3.1-dev" + "dev-master": "3.2-dev" } } } diff --git a/src/Commands/Ast/GenerateModelIDEVisitor.php b/src/Commands/Ast/GenerateModelIDEVisitor.php index 29f74af..7c5f031 100644 --- a/src/Commands/Ast/GenerateModelIDEVisitor.php +++ b/src/Commands/Ast/GenerateModelIDEVisitor.php @@ -113,10 +113,10 @@ public function afterTraverse(array $nodes) } $argType = new Node\UnionType($unionTypeIdentifier); } else { - $argType = $argumentType->getName(); - if ($argumentType->allowsNull()) { - $argType = new Node\NullableType($argType); - } + $argType = PhpParser::getInstance()->getNodeByTypeString( + $argumentType->getName(), + $argumentType->allowsNull() + ); } } if ($argument->isDefaultValueAvailable()) { diff --git a/src/Commands/Ast/ModelRewriteInheritanceVisitor.php b/src/Commands/Ast/ModelRewriteInheritanceVisitor.php index 962b19c..3bfa7be 100644 --- a/src/Commands/Ast/ModelRewriteInheritanceVisitor.php +++ b/src/Commands/Ast/ModelRewriteInheritanceVisitor.php @@ -65,16 +65,16 @@ public function leaveNode(Node $node) case $node instanceof Node\Stmt\Class_: $inheritance = $this->option->getInheritance(); if (is_object($node->extends) && ! empty($inheritance)) { - $node->extends->parts = [$inheritance]; + $node->extends->name = $inheritance; } return $node; case $node instanceof Node\Stmt\UseUse: - $class = implode('\\', $node->name->parts); + $class = implode('\\', $node->name->getParts()); $alias = is_object($node->alias) ? $node->alias->name : null; if ($class == $this->parentClass) { // The parent class is exists. $this->shouldAddUseUse = false; - if (end($node->name->parts) !== $this->option->getInheritance() && $alias !== $this->option->getInheritance()) { + if ($node->name->getLast() !== $this->option->getInheritance() && $alias !== $this->option->getInheritance()) { // Rewrite the alias, if the class is not equal with inheritance. $node->alias = new Identifier($this->option->getInheritance()); } diff --git a/src/Commands/Ast/ModelUpdateVisitor.php b/src/Commands/Ast/ModelUpdateVisitor.php index 8adb28b..4e4f988 100644 --- a/src/Commands/Ast/ModelUpdateVisitor.php +++ b/src/Commands/Ast/ModelUpdateVisitor.php @@ -86,13 +86,13 @@ public function beforeTraverse(array $nodes) public function leaveNode(Node $node) { switch ($node) { - case $node instanceof Node\Stmt\UseUse: + case $node instanceof Node\UseItem: $parts = $node->name->getParts(); - $class = implode('\\', $parts); + $class = $node->name->toString(); $alias = $node->alias?->name ?? array_pop($parts); $this->uses[$class] = $alias; return $node; - case $node instanceof Node\Stmt\PropertyProperty: + case $node instanceof Node\PropertyItem: if ((string) $node->name === 'fillable' && $this->option->isRefreshFillable()) { $node = $this->rewriteFillable($node); } elseif ((string) $node->name === 'casts') { @@ -107,11 +107,11 @@ public function leaveNode(Node $node) return null; } - protected function rewriteFillable(Node\Stmt\PropertyProperty $node): Node\Stmt\PropertyProperty + protected function rewriteFillable(Node\PropertyItem $node): Node\PropertyItem { $items = []; foreach ($this->columns as $column) { - $items[] = new Node\Expr\ArrayItem(new Node\Scalar\String_($column['column_name'])); + $items[] = new Node\ArrayItem(new Node\Scalar\String_($column['column_name'])); } $node->default = new Node\Expr\Array_($items, [ @@ -120,7 +120,7 @@ protected function rewriteFillable(Node\Stmt\PropertyProperty $node): Node\Stmt\ return $node; } - protected function rewriteCasts(Node\Stmt\PropertyProperty $node): Node\Stmt\PropertyProperty + protected function rewriteCasts(Node\PropertyItem $node): Node\PropertyItem { $items = []; $keys = []; @@ -150,7 +150,7 @@ protected function rewriteCasts(Node\Stmt\PropertyProperty $node): Node\Stmt\Pro continue; } if ($type || $type = $this->formatDatabaseType($column['data_type'])) { - $items[] = new Node\Expr\ArrayItem( + $items[] = new Node\ArrayItem( new Node\Scalar\String_($type), new Node\Scalar\String_($name) ); @@ -387,6 +387,9 @@ protected function getProperty($column): array $name = $this->option->isCamelCase() ? Str::camel($column['column_name']) : $column['column_name']; $type = $this->formatPropertyType($column['data_type'], $column['cast'] ?? null); + if ($this->option->isPropertyNullable()) { + $type = '?' . $type; + } $comment = $this->option->isWithComments() ? $column['column_comment'] ?? '' : ''; @@ -420,7 +423,7 @@ protected function formatPropertyType(string $type, ?string $cast): ?string return match ($cast) { 'integer' => 'int', - 'date', 'datetime' => $this->uses['Carbon\Carbon'] ?? '\Carbon\Carbon', + 'date', 'datetime' => ($this->uses['Carbon\Carbon'] ?? '\Carbon\Carbon'), 'json' => 'array', default => $cast, }; diff --git a/src/Commands/ModelCommand.php b/src/Commands/ModelCommand.php index 91e3118..b929563 100644 --- a/src/Commands/ModelCommand.php +++ b/src/Commands/ModelCommand.php @@ -22,8 +22,6 @@ use Hyperf\Database\Model\Model; use Hyperf\Database\Schema\Builder; use Hyperf\Stringable\Str; -use PhpParser\Lexer; -use PhpParser\Lexer\Emulative; use PhpParser\NodeTraverser; use PhpParser\NodeVisitor\CloningVisitor; use PhpParser\Parser; @@ -44,8 +42,6 @@ class ModelCommand extends Command protected ?ConfigInterface $config = null; - protected ?Lexer $lexer = null; - protected ?Parser $astParser = null; protected ?PrettyPrinterAbstract $printer = null; @@ -60,14 +56,7 @@ public function run(InputInterface $input, OutputInterface $output): int { $this->resolver = $this->container->get(ConnectionResolverInterface::class); $this->config = $this->container->get(ConfigInterface::class); - $this->lexer = new Emulative([ - 'usedAttributes' => [ - 'comments', - 'startLine', 'endLine', - 'startTokenPos', 'endTokenPos', - ], - ]); - $this->astParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7, $this->lexer); + $this->astParser = (new ParserFactory())->createForNewestSupportedVersion(); $this->printer = new Standard(); return parent::run($input, $output); @@ -91,7 +80,8 @@ public function handle() ->setWithComments($this->getOption('with-comments', 'commands.gen:model.with_comments', $pool, false)) ->setWithIde($this->getOption('with-ide', 'commands.gen:model.with_ide', $pool, false)) ->setVisitors($this->getOption('visitors', 'commands.gen:model.visitors', $pool, [])) - ->setPropertyCase($this->getOption('property-case', 'commands.gen:model.property_case', $pool)); + ->setPropertyCase($this->getOption('property-case', 'commands.gen:model.property_case', $pool)) + ->setPropertyNullable($this->getOption('property-nullable', 'commands.gen:model.property_nullable', $pool, false)); if ($table) { $this->createModel($table, $option); @@ -117,6 +107,7 @@ protected function configure() $this->addOption('with-ide', null, InputOption::VALUE_NONE, 'Whether generate the ide file for model.'); $this->addOption('visitors', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Custom visitors for ast traverser.'); $this->addOption('property-case', null, InputOption::VALUE_OPTIONAL, 'Which property case you want use, 0: snake case, 1: camel case.'); + $this->addOption('property-nullable', null, InputOption::VALUE_NONE, 'Which property is nullable for model.'); } protected function getSchemaBuilder(string $poolName): Builder @@ -197,7 +188,7 @@ protected function createModel(string $table, ModelOption $option): void $traverser->addVisitor(new CloningVisitor()); $originStmts = $this->astParser->parse(file_get_contents($path)); - $originTokens = $this->lexer->getTokens(); + $originTokens = $this->astParser->getTokens(); $newStmts = $traverser->traverse($originStmts); $code = $this->printer->printFormatPreserving($newStmts, $originStmts, $originTokens); @@ -268,7 +259,7 @@ protected function getOption(string $name, string $key, string $pool = 'default' { $result = $this->input->getOption($name); $nonInput = null; - if (in_array($name, ['force-casts', 'refresh-fillable', 'with-comments', 'with-ide'])) { + if (in_array($name, ['property-nullable', 'force-casts', 'refresh-fillable', 'with-comments', 'with-ide'])) { $nonInput = false; } if (in_array($name, ['table-mapping', 'ignore-tables', 'visitors'])) { diff --git a/src/Commands/ModelOption.php b/src/Commands/ModelOption.php index 453add2..1c20211 100644 --- a/src/Commands/ModelOption.php +++ b/src/Commands/ModelOption.php @@ -36,6 +36,8 @@ class ModelOption protected ?bool $withIde = null; + protected ?bool $propertyNullable = null; + protected array $tableMapping = []; protected array $ignoreTables = []; @@ -190,4 +192,15 @@ public function setPropertyCase($propertyCase): static $this->propertyCase = (int) $propertyCase; return $this; } + + public function isPropertyNullable(): ?bool + { + return $this->propertyNullable; + } + + public function setPropertyNullable(?bool $propertyNullable): static + { + $this->propertyNullable = $propertyNullable; + return $this; + } } diff --git a/src/Commands/stubs/Model.stub b/src/Commands/stubs/Model.stub index ca705fd..305bad5 100644 --- a/src/Commands/stubs/Model.stub +++ b/src/Commands/stubs/Model.stub @@ -20,11 +20,13 @@ class %CLASS% extends %INHERITANCE% /** * The attributes that are mass assignable. + * @var list */ protected array $fillable = []; /** * The attributes that should be cast to native types. + * @var array */ protected array $casts = []; } diff --git a/src/Connection.php b/src/Connection.php index bd564bf..1ba7824 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -977,6 +977,9 @@ public function setTablePrefix(string $prefix): static /** * Set the table prefix and return the grammar. + * @template T of Grammar + * @param T $grammar + * @return T */ public function withTablePrefix(Grammar $grammar): Grammar { @@ -1186,13 +1189,15 @@ protected function runQueryCallback(string $query, array $bindings, Closure $cal throw new UniqueConstraintViolationException( $query, $this->prepareBindings($bindings), - $e + $e, + $this->getName(), ); } throw new QueryException( $query, $this->prepareBindings($bindings), - $e + $e, + $this->getName() ); } catch (Throwable $throwable) { ++$this->errorCount; diff --git a/src/Connectors/Connector.php b/src/Connectors/Connector.php index 7b424d2..5f151cc 100755 --- a/src/Connectors/Connector.php +++ b/src/Connectors/Connector.php @@ -104,7 +104,9 @@ public function setDefaultOptions(array $options) */ protected function createPdoConnection($dsn, $username, $password, $options) { - return new PDO($dsn, $username, $password, $options); + return PHP_VERSION_ID < 80400 + ? new PDO($dsn, $username, $password, $options) + : PDO::connect($dsn, $username, $password, $options); /* @phpstan-ignore staticMethod.notFound (PHP 8.4) */ } /** diff --git a/src/Exception/QueryException.php b/src/Exception/QueryException.php index cfb936c..9766b14 100644 --- a/src/Exception/QueryException.php +++ b/src/Exception/QueryException.php @@ -26,8 +26,12 @@ class QueryException extends PDOException * @param string $sql the SQL for the query * @param array $bindings the bindings for the query */ - public function __construct(protected string $sql, protected array $bindings, Exception $previous) - { + public function __construct( + protected string $sql, + protected array $bindings, + Exception $previous, + public ?string $connectionName = null, + ) { parent::__construct('', 0, $previous); $this->code = $previous->getCode(); diff --git a/src/Model/Builder.php b/src/Model/Builder.php index 55332ff..646712b 100755 --- a/src/Model/Builder.php +++ b/src/Model/Builder.php @@ -124,45 +124,42 @@ public function __construct(QueryBuilder $query) /** * Dynamically handle calls into the query instance. - * - * @param string $method - * @param array $parameters */ - public function __call($method, $parameters) + public function __call(string $name, array $arguments): mixed { - if ($method === 'macro') { - $this->localMacros[$parameters[0]] = $parameters[1]; + if ($name === 'macro') { + $this->localMacros[$arguments[0]] = $arguments[1]; - return; + return null; } - if ($method === 'mixin') { - return static::registerMixin($parameters[0], $parameters[1] ?? true); + if ($name === 'mixin') { + return static::registerMixin($arguments[0], $arguments[1] ?? true); } - if ($this->hasMacro($method)) { - array_unshift($parameters, $this); + if ($this->hasMacro($name)) { + array_unshift($arguments, $this); - return $this->localMacros[$method](...$parameters); + return $this->localMacros[$name](...$arguments); } - if (static::hasGlobalMacro($method)) { - if (static::$macros[$method] instanceof Closure) { - return call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $parameters); + if (static::hasGlobalMacro($name)) { + if (static::$macros[$name] instanceof Closure) { + return call_user_func_array(static::$macros[$name]->bindTo($this, static::class), $arguments); } - return call_user_func_array(static::$macros[$method], $parameters); + return call_user_func_array(static::$macros[$name], $arguments); } - if (isset($this->model) && method_exists($this->model, $scope = 'scope' . ucfirst($method))) { - return $this->callScope([$this->model, $scope], $parameters); + if (isset($this->model) && method_exists($this->model, $scope = 'scope' . ucfirst($name))) { + return $this->callScope([$this->model, $scope], $arguments); } - if (in_array($method, $this->passthru)) { - return $this->toBase()->{$method}(...$parameters); + if (in_array($name, $this->passthru)) { + return $this->toBase()->{$name}(...$arguments); } - $this->query->{$method}(...$parameters); + $this->query->{$name}(...$arguments); return $this; } @@ -344,7 +341,7 @@ public function except(iterable|Model $models): static * @param string $boolean * @param null|mixed $operator * @param null|mixed $value - * @return $this + * @return static */ public function where($column, $operator = null, $value = null, $boolean = 'and') { @@ -365,7 +362,7 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' * @param array|Closure|string $column * @param null|mixed $operator * @param null|mixed $value - * @return $this + * @return static */ public function orWhere($column, $operator = null, $value = null) { @@ -382,7 +379,7 @@ public function orWhere($column, $operator = null, $value = null) * Add an "order by" clause for a timestamp to the query. * * @param string $column - * @return $this + * @return static */ public function latest($column = null) { @@ -399,7 +396,7 @@ public function latest($column = null) * Add an "order by" clause for a timestamp to the query. * * @param string $column - * @return $this + * @return static */ public function oldest($column = null) { @@ -1096,7 +1093,7 @@ public function sole(array|string $columns = ['*']) * Set the relationships that should be eager loaded. * * @param mixed $relations - * @return $this + * @return static */ public function with($relations) { @@ -1111,7 +1108,7 @@ public function with($relations) * Prevent the specified relations from being eager loaded. * * @param mixed $relations - * @return $this + * @return static */ public function without($relations) { @@ -1159,7 +1156,7 @@ public function getQuery() * Set the underlying query builder instance. * * @param QueryBuilder $query - * @return $this + * @return static */ public function setQuery($query) { @@ -1191,7 +1188,7 @@ public function getEagerLoads() /** * Set the relationships being eagerly loaded. * - * @return $this + * @return static */ public function setEagerLoads(array $eagerLoad) { diff --git a/src/Model/Concerns/HasAttributes.php b/src/Model/Concerns/HasAttributes.php index 7fba994..2a2d23e 100644 --- a/src/Model/Concerns/HasAttributes.php +++ b/src/Model/Concerns/HasAttributes.php @@ -566,36 +566,41 @@ public function syncChanges(?array $columns = null): static * Determine if the model or given attribute(s) have been modified. * * @param null|array|string $attributes + * @param string ...$extra */ - public function isDirty($attributes = null): bool + public function isDirty($attributes = null, ...$extra): bool { - return $this->hasChanges( - $this->getDirty(), - is_array($attributes) ? $attributes : func_get_args() - ); + if (! is_array($attributes)) { + $attributes = is_null($attributes) && $extra === [] ? [] : [$attributes, ...$extra]; + } + + return $this->hasChanges($this->getDirty(), $attributes); } /** * Determine if the model or given attribute(s) have remained the same. * * @param null|array|string $attributes + * @param string ...$extra */ - public function isClean($attributes = null): bool + public function isClean($attributes = null, ...$extra): bool { - return ! $this->isDirty(...func_get_args()); + return ! $this->isDirty($attributes, ...$extra); } /** * Determine if the model or given attribute(s) have been modified. * * @param null|array|string $attributes + * @param string ...$extra */ - public function wasChanged($attributes = null): bool + public function wasChanged($attributes = null, ...$extra): bool { - return $this->hasChanges( - $this->getChanges(), - is_array($attributes) ? $attributes : func_get_args() - ); + if (! is_array($attributes)) { + $attributes = is_null($attributes) && $extra === [] ? [] : [$attributes, ...$extra]; + } + + return $this->hasChanges($this->getChanges(), $attributes); } /** @@ -1220,7 +1225,7 @@ protected function asDateTime(mixed $value): CarbonInterface // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { - return Carbon::createFromTimestamp($value); + return Carbon::createFromTimestamp($value, date_default_timezone_get()); } // If the value is in simply year, month, day format, we will instantiate the diff --git a/src/Model/Concerns/HasRelationships.php b/src/Model/Concerns/HasRelationships.php index 315693e..0c55f63 100644 --- a/src/Model/Concerns/HasRelationships.php +++ b/src/Model/Concerns/HasRelationships.php @@ -106,7 +106,7 @@ public static function resolveRelationUsing($name, Closure $callback) * @param class-string $related * @param string $foreignKey * @param string $localKey - * @return HasOne + * @return HasOne */ public function hasOne($related, $foreignKey = null, $localKey = null) { @@ -131,7 +131,7 @@ public function hasOne($related, $foreignKey = null, $localKey = null) * @param null|string $secondKey * @param null|string $localKey * @param null|string $secondLocalKey - * @return HasOneThrough + * @return HasOneThrough */ public function hasOneThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) { @@ -162,7 +162,7 @@ public function hasOneThrough($related, $through, $firstKey = null, $secondKey = * @param string $type * @param string $id * @param string $localKey - * @return MorphOne + * @return MorphOne */ public function morphOne($related, $name, $type = null, $id = null, $localKey = null) { @@ -186,7 +186,7 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey = * @param string $foreignKey * @param string $ownerKey * @param string $relation - * @return BelongsTo + * @return BelongsTo */ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null) { @@ -227,7 +227,7 @@ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relat * @param string $type * @param string $id * @param string $ownerKey - * @return MorphTo + * @return MorphTo */ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null) { @@ -269,7 +269,7 @@ public static function getActualClassNameForMorph($class) * @param class-string $related * @param string $foreignKey * @param string $localKey - * @return HasMany + * @return HasMany */ public function hasMany($related, $foreignKey = null, $localKey = null) { @@ -299,7 +299,7 @@ public function hasMany($related, $foreignKey = null, $localKey = null) * @param null|string $secondKey * @param null|string $localKey * @param null|string $secondLocalKey - * @return HasManyThrough + * @return HasManyThrough */ public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) { @@ -330,7 +330,7 @@ public function hasManyThrough($related, $through, $firstKey = null, $secondKey * @param string $type * @param string $id * @param string $localKey - * @return MorphMany + * @return MorphMany */ public function morphMany($related, $name, $type = null, $id = null, $localKey = null) { @@ -361,7 +361,7 @@ public function morphMany($related, $name, $type = null, $id = null, $localKey = * @param string $relatedKey * @param string $relation * - * @return BelongsToMany + * @return BelongsToMany */ public function belongsToMany( $related, @@ -420,7 +420,7 @@ public function belongsToMany( * @param string $parentKey * @param string $relatedKey * @param bool $inverse - * @return MorphToMany + * @return MorphToMany */ public function morphToMany( $related, @@ -480,7 +480,7 @@ public function morphToMany( * @param string $relatedPivotKey * @param string $parentKey * @param string $relatedKey - * @return MorphToMany + * @return MorphToMany */ public function morphedByMany( $related, @@ -751,7 +751,7 @@ protected function newMorphOne(Builder $query, Model $parent, $type, $id, $local * @param string $foreignKey * @param string $ownerKey * @param string $relation - * @return BelongsTo + * @return BelongsTo */ protected function newBelongsTo(Builder $query, Model $child, $foreignKey, $ownerKey, $relation) { @@ -765,7 +765,7 @@ protected function newBelongsTo(Builder $query, Model $child, $foreignKey, $owne * @param string $type * @param string $id * @param string $ownerKey - * @return MorphTo + * @return MorphTo */ protected function morphEagerTo($name, $type, $id, $ownerKey) { @@ -787,7 +787,7 @@ protected function morphEagerTo($name, $type, $id, $ownerKey) * @param string $type * @param string $id * @param string $ownerKey - * @return MorphTo + * @return MorphTo */ protected function morphInstanceTo($target, $name, $type, $id, $ownerKey) { diff --git a/src/Model/Concerns/HasUlids.php b/src/Model/Concerns/HasUlids.php index c6b067c..531b96e 100644 --- a/src/Model/Concerns/HasUlids.php +++ b/src/Model/Concerns/HasUlids.php @@ -16,6 +16,8 @@ trait HasUlids { + use HasUniqueStringIds; + /** * Generate a new ULID for the model. * @@ -27,40 +29,12 @@ public function newUniqueId() } /** - * Get the columns that should receive a unique identifier. - * - * @return array - */ - public function uniqueIds() - { - return [$this->getKeyName()]; - } - - /** - * Get the auto-incrementing key type. - * - * @return string - */ - public function getKeyType() - { - if (in_array($this->getKeyName(), $this->uniqueIds())) { - return 'string'; - } - - return $this->keyType; - } - - /** - * Get the value indicating whether the IDs are incrementing. + * Determine if given key is valid. * - * @return bool + * @param mixed $value */ - public function getIncrementing() + protected function isValidUniqueId($value): bool { - if (in_array($this->getKeyName(), $this->uniqueIds())) { - return false; - } - - return $this->incrementing; + return Str::isUlid($value); } } diff --git a/src/Model/Concerns/HasUniqueStringIds.php b/src/Model/Concerns/HasUniqueStringIds.php new file mode 100644 index 0000000..86b4de7 --- /dev/null +++ b/src/Model/Concerns/HasUniqueStringIds.php @@ -0,0 +1,108 @@ +getKeyName()]; + } + + /** + * Retrieve the model for a bound value. + * + * @param \Hyperf\Database\Model\Model|\Hyperf\Database\Model\Relations\Relation<*, *, *> $query + * @param mixed $value + * @param null|string $field + * @return Builder + * + * @throws ModelNotFoundException + */ + public function resolveRouteBindingQuery($query, $value, $field = null) + { + if ($field && in_array($field, $this->uniqueIds()) && ! $this->isValidUniqueId($value)) { + $this->handleInvalidUniqueId($value, $field); + } + + if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! $this->isValidUniqueId($value)) { + $this->handleInvalidUniqueId($value, $field); + } + + return parent::resolveRouteBindingQuery($query, $value, $field); + } + + /** + * Get the auto-incrementing key type. + * + * @return string + */ + public function getKeyType() + { + if (in_array($this->getKeyName(), $this->uniqueIds())) { + return 'string'; + } + + return $this->keyType; + } + + /** + * Get the value indicating whether the IDs are incrementing. + * + * @return bool + */ + public function getIncrementing() + { + if (in_array($this->getKeyName(), $this->uniqueIds())) { + return false; + } + + return $this->incrementing; + } + + /** + * Throw an exception for the given invalid unique ID. + * + * @param mixed $value + * @param null|string $field + * @return never + * + * @throws ModelNotFoundException + */ + protected function handleInvalidUniqueId($value, $field) + { + throw (new ModelNotFoundException())->setModel(get_class($this), $value); + } + + /** + * Determine if given key is valid. + * + * @param mixed $value + */ + abstract protected function isValidUniqueId($value): bool; +} diff --git a/src/Model/Concerns/HasUuids.php b/src/Model/Concerns/HasUuids.php index 5d27dbe..6a8215f 100644 --- a/src/Model/Concerns/HasUuids.php +++ b/src/Model/Concerns/HasUuids.php @@ -16,6 +16,8 @@ trait HasUuids { + use HasUniqueStringIds; + /** * Generate a new UUID for the model. * @@ -27,40 +29,12 @@ public function newUniqueId() } /** - * Get the columns that should receive a unique identifier. - * - * @return array - */ - public function uniqueIds() - { - return [$this->getKeyName()]; - } - - /** - * Get the auto-incrementing key type. - * - * @return string - */ - public function getKeyType() - { - if (in_array($this->getKeyName(), $this->uniqueIds())) { - return 'string'; - } - - return $this->keyType; - } - - /** - * Get the value indicating whether the IDs are incrementing. + * Determine if given key is valid. * - * @return bool + * @param mixed $value */ - public function getIncrementing() + protected function isValidUniqueId($value): bool { - if (in_array($this->getKeyName(), $this->uniqueIds())) { - return false; - } - - return $this->incrementing; + return Str::isUuid($value); } } diff --git a/src/Model/Model.php b/src/Model/Model.php index 742b9e0..d3bb9cf 100644 --- a/src/Model/Model.php +++ b/src/Model/Model.php @@ -180,21 +180,18 @@ public function __unset($key) /** * Handle dynamic method calls into the model. - * - * @param string $method - * @param array $parameters */ - public function __call($method, $parameters) + public function __call(string $name, array $arguments): mixed { - if (in_array($method, ['increment', 'decrement'])) { - return $this->{$method}(...$parameters); + if (in_array($name, ['increment', 'decrement'])) { + return $this->{$name}(...$arguments); } - if ($resolver = $this->relationResolver(static::class, $method)) { + if ($resolver = $this->relationResolver(static::class, $name)) { return $resolver($this); } - return $this->newQuery()->{$method}(...$parameters); + return $this->newQuery()->{$name}(...$arguments); } /** @@ -886,10 +883,9 @@ public function toArray(): array * Convert the model instance to JSON. * * @param int $options - * @return string * @throws JsonEncodingException */ - public function toJson($options = 0) + public function toJson($options = 0): string { try { $json = json_encode($this->jsonSerialize(), $options | JSON_THROW_ON_ERROR); diff --git a/src/Model/Relations/BelongsTo.php b/src/Model/Relations/BelongsTo.php index 67c6c6a..5ae3416 100755 --- a/src/Model/Relations/BelongsTo.php +++ b/src/Model/Relations/BelongsTo.php @@ -152,15 +152,23 @@ public function match(array $models, Collection $results, $relation) $dictionary = []; foreach ($results as $result) { - $dictionary[$result->getAttribute($owner)] = $result; + // The owner key can be null when not selected; null as an array offset is deprecated since PHP 8.1 + $key = $result->getAttribute($owner); + + if ($key !== null) { + $dictionary[$key] = $result; + } } // Once we have the dictionary constructed, we can loop through all the parents // and match back onto their children using these keys of the dictionary and // the primary key of the children to map them onto the correct instances. foreach ($models as $model) { - if (isset($dictionary[$model->{$foreign}])) { - $model->setRelation($relation, $dictionary[$model->{$foreign}]); + // The foreign key is nullable, and using null as an array offset is deprecated since PHP 8.1 + $key = $model->{$foreign}; + + if ($key !== null && isset($dictionary[$key])) { + $model->setRelation($relation, $dictionary[$key]); } } diff --git a/src/Model/Relations/MorphTo.php b/src/Model/Relations/MorphTo.php index 0269453..1a2cae2 100644 --- a/src/Model/Relations/MorphTo.php +++ b/src/Model/Relations/MorphTo.php @@ -80,17 +80,14 @@ public function __construct(Builder $query, Model $parent, $foreignKey, $ownerKe /** * Handle dynamic method calls to the relationship. - * - * @param string $method - * @param array $parameters */ - public function __call($method, $parameters) + public function __call(string $name, array $arguments): mixed { try { - $result = parent::__call($method, $parameters); + $result = parent::__call($name, $arguments); - if (in_array($method, ['select', 'selectRaw', 'selectSub', 'addSelect', 'withoutGlobalScopes'])) { - $this->macroBuffer[] = compact('method', 'parameters'); + if (in_array($name, ['select', 'selectRaw', 'selectSub', 'addSelect', 'withoutGlobalScopes'])) { + $this->macroBuffer[] = compact('name', 'arguments'); } return $result; @@ -100,7 +97,7 @@ public function __call($method, $parameters) // we'll assume that we want to call a query macro (e.g. withTrashed) that only // exists on related models. We will just store the call and replay it later. catch (BadMethodCallException $e) { - $this->macroBuffer[] = compact('method', 'parameters'); + $this->macroBuffer[] = compact('name', 'arguments'); return $this; } @@ -248,9 +245,15 @@ public function morphWith(array $with) protected function buildDictionary(Collection $models) { foreach ($models as $model) { - if ($model->{$this->morphType}) { - $this->dictionary[$model->{$this->morphType}][$model->{$this->foreignKey}][] = $model; + // Both are nullable, and using null as an array offset is deprecated since PHP 8.1 + $type = $model->{$this->morphType}; + $key = $model->{$this->foreignKey}; + + if (empty($type) || $key === null) { + continue; } + + $this->dictionary[$type][$key][] = $model; } } @@ -320,7 +323,7 @@ protected function matchToMorphParents($type, Collection $results) protected function replayMacros(Builder $query) { foreach ($this->macroBuffer as $macro) { - $query->{$macro['method']}(...$macro['parameters']); + $query->{$macro['name']}(...$macro['arguments']); } return $query; diff --git a/src/Model/Relations/Relation.php b/src/Model/Relations/Relation.php index 16ff7a8..5fac89d 100755 --- a/src/Model/Relations/Relation.php +++ b/src/Model/Relations/Relation.php @@ -84,17 +84,14 @@ public function __construct(Builder $query, Model $parent) /** * Handle dynamic method calls to the relationship. - * - * @param string $method - * @param array $parameters */ - public function __call($method, $parameters) + public function __call(string $name, array $arguments): mixed { - if (static::hasMacro($method)) { - return $this->macroCall($method, $parameters); + if (static::hasMacro($name)) { + return $this->macroCall($name, $arguments); } - $result = $this->forwardCallTo($this->query, $method, $parameters); + $result = $this->forwardCallTo($this->query, $name, $arguments); if ($result === $this->query) { return $this; diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 6e61138..087153f 100755 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -124,10 +124,8 @@ class Builder /** * The table joins for the query. - * - * @var array */ - public $joins; + public ?array $joins = null; /** * The where constraints for the query. @@ -267,20 +265,19 @@ public function __construct( /** * Handle dynamic method calls into the method. * - * @param string $method - * @param array $parameters * @throws BadMethodCallException */ - public function __call($method, $parameters) + public function __call(string $name, array $arguments): mixed { - if (static::hasMacro($method)) { - return $this->macroCall($method, $parameters); + if (static::hasMacro($name)) { + return $this->macroCall($name, $arguments); } - if (Str::startsWith($method, 'where')) { - return $this->dynamicWhere($method, $parameters); + if (Str::startsWith($name, 'where')) { + return $this->dynamicWhere($name, $arguments); } - static::throwBadMethodCallException($method); + static::throwBadMethodCallException($name); + return null; } /** @@ -413,22 +410,6 @@ public function from($table) return $this; } - /** - * Set the force indexes which the query should be used. - * @deprecated It will be removed in v3.1, please use `forceIndex` instead - */ - public function forceIndexes(array $forceIndexes): static - { - $values = []; - foreach ($forceIndexes as $forceIndex) { - $values[] = '`' . str_replace('`', '``', $forceIndex) . '`'; - } - - $this->indexHint = new IndexHint('force', implode(',', $values)); - - return $this; - } - /** * Add an index hint to suggest a query index. */ @@ -1274,7 +1255,7 @@ public function orWhereYear($column, $operator, $value = null) * Add a nested where statement to the query. * * @param string $boolean - * @return Builder|static + * @return static */ public function whereNested(Closure $callback, $boolean = 'and') { @@ -2137,11 +2118,14 @@ public function take($value) public function limit($value) { $property = $this->unions ? 'unionLimit' : 'limit'; + $value = (int) $value; - if ($value >= 0) { - $this->{$property} = $value; + if ($value < 0) { + throw new InvalidArgumentException('Limit cannot be negative.'); } + $this->{$property} = $value; + return $this; } diff --git a/src/Schema/Blueprint.php b/src/Schema/Blueprint.php index cb54c3b..40477f3 100755 --- a/src/Schema/Blueprint.php +++ b/src/Schema/Blueprint.php @@ -1000,7 +1000,7 @@ public function datetimes($precision = 0) } /** - * Add a "deleted at" timestamp for the table. + * Add a "deleted at" dateTime for the table. * * @param string $column * @param int $precision @@ -1008,11 +1008,11 @@ public function datetimes($precision = 0) */ public function softDeletes($column = 'deleted_at', $precision = 0) { - return $this->timestamp($column, $precision)->nullable(); + return $this->dateTime($column, $precision)->nullable(); } /** - * Add a "deleted at" timestampTz for the table. + * Add a "deleted at" dateTimeTz for the table. * * @param string $column * @param int $precision @@ -1020,7 +1020,7 @@ public function softDeletes($column = 'deleted_at', $precision = 0) */ public function softDeletesTz($column = 'deleted_at', $precision = 0) { - return $this->timestampTz($column, $precision)->nullable(); + return $this->dateTimeTz($column, $precision)->nullable(); } /** diff --git a/src/Schema/Schema.php b/src/Schema/Schema.php index fe301ee..d01f51a 100644 --- a/src/Schema/Schema.php +++ b/src/Schema/Schema.php @@ -60,7 +60,7 @@ public static function __callStatic($name, $arguments) return $connection->getSchemaBuilder()->{$name}(...$arguments); } - public function __call($name, $arguments) + public function __call(string $name, array $arguments): mixed { return self::__callStatic($name, $arguments); } diff --git a/tests/DatabaseQueryBuilderTest.php b/tests/DatabaseQueryBuilderTest.php index 209b7e0..79c4a1c 100644 --- a/tests/DatabaseQueryBuilderTest.php +++ b/tests/DatabaseQueryBuilderTest.php @@ -252,24 +252,15 @@ public function testForceIndex(): void { $builder = $this->getMySqlBuilder(); $builder1 = (clone $builder)->select('*')->from('users')->where('username', 'xxx')->forceIndex('index1'); - $foeceses = (clone $builder)->select('*')->from('users')->where('username', 'xxx')->forceIndexes(['index1']); - $this->assertSame('select * from `users` force index (index1) where `username` = ?', $builder1->toSql()); - $this->assertSame('select * from `users` force index (`index1`) where `username` = ?', $foeceses->toSql()); $builder2 = (clone $builder); $builder2->select('*')->from('users')->where('username', 'xxx')->forceIndex('index2'); - $foeceses = (clone $builder); - $foeceses->select('*')->from('users')->where('username', 'xxx')->forceIndexes(['index2']); $this->assertSame('select * from `users` force index (index2) where `username` = ?', $builder2->toSql()); - $this->assertSame('select * from `users` force index (`index2`) where `username` = ?', $foeceses->toSql()); $builder3 = (clone $builder); - $foeceses = (clone $builder); $builder3->select('*')->from('users')->where('username', 'xxx')->forceIndex('index1,index2'); - $foeceses->select('*')->from('users')->where('username', 'xxx')->forceIndexes(['index1', 'index2']); $this->assertSame('select * from `users` force index (index1,index2) where `username` = ?', $builder3->toSql()); - $this->assertSame('select * from `users` force index (`index1`,`index2`) where `username` = ?', $foeceses->toSql()); } public function testIgnoreIndex(): void diff --git a/tests/GenModelTest.php b/tests/GenModelTest.php index 6053585..862a74b 100644 --- a/tests/GenModelTest.php +++ b/tests/GenModelTest.php @@ -21,7 +21,6 @@ use HyperfTest\Database\Stubs\Model\UserExtEmpty; use HyperfTest\Database\Stubs\Model\UserExtWithTrait; use Mockery; -use PhpParser\Lexer\Emulative; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; use PhpParser\PrettyPrinter\Standard; @@ -71,10 +70,10 @@ public function testDatabaseFormat() } } - $astParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7); + $astParser = (new ParserFactory())->createForNewestSupportedVersion(); $stms = $astParser->parse(file_get_contents(__DIR__ . '/Stubs/Model/UserExtEmpty.php')); $traverser = new NodeTraverser(); - $visitor = new ModelUpdateVisitor(UserExtEmpty::class, $columns, ContainerStub::getModelOption()); + $visitor = new ModelUpdateVisitor(UserExtEmpty::class, $columns, ContainerStub::getModelOption()->setPropertyNullable(true)); $traverser->addVisitor($visitor); $stms = $traverser->traverse($stms); $code = (new Standard())->prettyPrintFile($stms); @@ -82,13 +81,13 @@ public function testDatabaseFormat() namespace HyperfTest\Database\Stubs\Model; /** - * @property int $id - * @property int $count - * @property string $float_num - * @property string $str - * @property string $json - * @property \Carbon\Carbon $created_at - * @property string $updated_at + * @property ?int $id + * @property ?int $count + * @property ?string $float_num + * @property ?string $str + * @property ?string $json + * @property ?\Carbon\Carbon $created_at + * @property ?string $updated_at */ class UserExtEmpty extends Model { @@ -127,7 +126,7 @@ public function testGenModelWithEnum() $columns[$i]['cast'] = 'datetime'; } } - $astParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7); + $astParser = (new ParserFactory())->createForNewestSupportedVersion(); $stms = $astParser->parse(file_get_contents(__DIR__ . '/Stubs/Model/UserEnum.php')); $traverser = new NodeTraverser(); $visitor = new ModelUpdateVisitor(UserEnum::class, $columns, ContainerStub::getModelOption()->setForceCasts(false)); @@ -177,25 +176,18 @@ public function testGenModelWithTrait() $dispatcher->shouldReceive('dispatch')->withAnyArgs()->andReturn(null); return $dispatcher; }); - $lexer = new Emulative([ - 'usedAttributes' => [ - 'comments', - 'startLine', 'endLine', - 'startTokenPos', 'endTokenPos', - ], - ]); $connection = $container->get(ConnectionResolverInterface::class)->connection(); /** @var MySqlBuilder $builder */ $builder = $connection->getSchemaBuilder('default'); $columns = $this->formatColumns($builder->getColumnTypeListing('user_ext')); $columns = []; - $astParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7, $lexer); + $astParser = (new ParserFactory())->createForNewestSupportedVersion(); $originStmts = $astParser->parse(file_get_contents(__DIR__ . '/Stubs/Model/UserExtWithTrait.php')); $traverser = new NodeTraverser(); $visitor = new ModelUpdateVisitor(UserExtWithTrait::class, $columns, ContainerStub::getModelOption()->setWithComments(true)->setForceCasts(false)); $traverser->addVisitor($visitor); $newStmts = $traverser->traverse($originStmts); - $code = (new Standard())->printFormatPreserving($newStmts, $originStmts, $lexer->getTokens()); + $code = (new Standard())->printFormatPreserving($newStmts, $originStmts, $astParser->getTokens()); $this->assertTrue(str_contains($code, '@property-read string $count_string')); $this->assertTrue(str_contains($code, '@property-read null|User $user')); } diff --git a/tests/Model/NullableForeignKeyTest.php b/tests/Model/NullableForeignKeyTest.php new file mode 100644 index 0000000..c6695a0 --- /dev/null +++ b/tests/Model/NullableForeignKeyTest.php @@ -0,0 +1,221 @@ + 1]); + $result = new ModelStub(['id' => 1, 'name' => 'hyperf']); + + $deprecations = $this->captureDeprecations(function () use ($associated, $result): void { + $this->belongsTo()->match( + [$associated], + new Collection([$result]), + 'user' + ); + }); + + $this->assertSame([], $deprecations); + $this->assertTrue($associated->relationLoaded('user')); + $this->assertSame($result, $associated->getRelation('user')); + } + + public function testBelongsToMatchSkipsNullForeignKey(): void + { + $unassociated = new ModelStub(['user_id' => null]); + $associated = new ModelStub(['user_id' => 1]); + + $deprecations = $this->captureDeprecations(function () use ($unassociated, $associated): void { + $this->belongsTo()->match( + [$unassociated, $associated], + new Collection([new ModelStub(['id' => 1, 'name' => 'hyperf'])]), + 'user' + ); + }); + + $this->assertSame([], $deprecations); + $this->assertFalse($unassociated->relationLoaded('user')); + $this->assertTrue($associated->relationLoaded('user')); + $this->assertSame('hyperf', $associated->getRelation('user')->name); + } + + public function testBelongsToMatchDoesNotMatchNullForeignKeyAgainstNullOwnerKey(): void + { + // Both the foreign key and the owner key are null. They used to end up + // under the same "" array key, which made the unassociated model match + // a result that shouldn't be associated with it at all. + $unassociated = new ModelStub(['user_id' => null]); + + $deprecations = $this->captureDeprecations(function () use ($unassociated): void { + $this->belongsTo()->match( + [$unassociated], + new Collection([new ModelStub(['name' => 'hyperf'])]), + 'user' + ); + }); + + $this->assertSame([], $deprecations); + $this->assertFalse($unassociated->relationLoaded('user')); + } + + public function testBelongsToMatchSkipsNullOwnerKey(): void + { + // The owner key is missing here, just like the rows fetched by `with('user:name')` + $associated = new ModelStub(['user_id' => 1]); + + $deprecations = $this->captureDeprecations(function () use ($associated): void { + $this->belongsTo()->match( + [$associated], + new Collection([new ModelStub(['name' => 'hyperf'])]), + 'user' + ); + }); + + $this->assertSame([], $deprecations); + $this->assertFalse($associated->relationLoaded('user')); + } + + public function testBelongsToMatchLeavesRelationUnloadedWhenOwnerKeyIsUnknown(): void + { + $associated = new ModelStub(['user_id' => 2]); + + $deprecations = $this->captureDeprecations(function () use ($associated): void { + $this->belongsTo()->match( + [$associated], + new Collection([new ModelStub(['id' => 1, 'name' => 'hyperf'])]), + 'user' + ); + }); + + $this->assertSame([], $deprecations); + $this->assertFalse($associated->relationLoaded('user')); + } + + public function testMorphToBuildDictionarySkipsUnassociatedModels(): void + { + $morphTo = $this->morphTo(); + $associated = new ModelStub(['imageable_type' => ModelStub::class, 'imageable_id' => 1]); + + $deprecations = $this->captureDeprecations(function () use ($morphTo, $associated): void { + $morphTo->addEagerConstraints([ + $associated, + new ModelStub(['imageable_type' => ModelStub::class, 'imageable_id' => null]), + new ModelStub(['imageable_type' => null, 'imageable_id' => 2]), + ]); + }); + + $this->assertSame([], $deprecations); + $this->assertSame([ModelStub::class => [1 => [$associated]]], $morphTo->getDictionary()); + } + + public function testMorphToBuildDictionarySkipsEmptyMorphType(): void + { + $morphTo = $this->morphTo(); + + $deprecations = $this->captureDeprecations(function () use ($morphTo): void { + $morphTo->addEagerConstraints([ + new ModelStub(['imageable_type' => '', 'imageable_id' => 1]), + ]); + }); + + $this->assertSame([], $deprecations); + $this->assertSame([], $morphTo->getDictionary()); + } + + public function testMorphToBuildDictionaryGroupsModelsByTypeAndKey(): void + { + $morphTo = $this->morphTo(); + $first = new ModelStub(['imageable_type' => ModelStub::class, 'imageable_id' => 1]); + $second = new ModelStub(['imageable_type' => ModelStub::class, 'imageable_id' => 1]); + + $deprecations = $this->captureDeprecations(function () use ($morphTo, $first, $second): void { + $morphTo->addEagerConstraints([$first, $second]); + }); + + $this->assertSame([], $deprecations); + $this->assertSame([ModelStub::class => [1 => [$first, $second]]], $morphTo->getDictionary()); + } + + private function belongsTo(): BelongsTo + { + return new BelongsTo($this->mockBuilder(), new ModelStub(), 'user_id', 'id', 'user'); + } + + private function morphTo(): MorphTo + { + return new MorphTo($this->mockBuilder(), new ModelStub(), 'imageable_id', 'id', 'imageable_type', 'imageable'); + } + + private function mockBuilder(): Builder + { + $builder = Mockery::mock(Builder::class); + $builder->shouldReceive('getModel')->andReturn(new ModelStub()); + $builder->shouldReceive('where')->andReturnSelf(); + + return $builder; + } + + /** + * Run the given callback and collect the deprecations it triggers. + * + * @return string[] + */ + private function captureDeprecations(callable $callback): array + { + $deprecations = []; + + set_error_handler(static function (int $errno, string $errstr) use (&$deprecations): bool { + if (str_contains($errstr, 'array offset')) { + $deprecations[] = $errstr; + } + + // Swallow the deprecations to keep the suite output clean, but let + // warnings and notices bubble up to the standard error handling. + return ($errno & (E_DEPRECATED | E_USER_DEPRECATED)) !== 0; + }, E_ALL); + + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; + } +} diff --git a/tests/ModelGenerateTest.php b/tests/ModelGenerateTest.php index 6ff4127..6628e10 100644 --- a/tests/ModelGenerateTest.php +++ b/tests/ModelGenerateTest.php @@ -30,14 +30,8 @@ class ModelGenerateTest extends TestCase { public function setUp(): void { - $this->lexer = new Emulative([ - 'usedAttributes' => [ - 'comments', - 'startLine', 'endLine', - 'startTokenPos', 'endTokenPos', - ], - ]); - $this->astParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7, $this->lexer); + $this->lexer = new Emulative(); + $this->astParser = (new ParserFactory())->createForNewestSupportedVersion(); $this->printer = new Standard(); } diff --git a/tests/ModelMorphEagerLoadingTest.php b/tests/ModelMorphEagerLoadingTest.php index 49351a2..921754f 100644 --- a/tests/ModelMorphEagerLoadingTest.php +++ b/tests/ModelMorphEagerLoadingTest.php @@ -101,6 +101,25 @@ public function testMorphWith() } } + public function testMorphEagerLoadWithColumns() + { + $this->getContainer(); + $images = Image::query()->with(['imageable:id,name'])->where('imageable_type', 'user')->get(); + + $this->assertInstanceOf(User::class, $images[1]->imageable); + $this->assertSame(2, $images[1]->imageable->id); + + $sqls = [ + 'select * from `images` where `imageable_type` = ?', + 'select `id`, `name` from `user` where `user`.`id` in (1, 2)', + ]; + while ($event = $this->channel->pop(0.001)) { + if ($event instanceof QueryExecuted) { + $this->assertSame($event->sql, array_shift($sqls)); + } + } + } + public function testMorphAssociationEmpty() { $this->getContainer(); diff --git a/tests/ModelRealBuilderTest.php b/tests/ModelRealBuilderTest.php index 66c2cbc..9a1508b 100644 --- a/tests/ModelRealBuilderTest.php +++ b/tests/ModelRealBuilderTest.php @@ -243,24 +243,6 @@ public function testUserWhereBit() } } - public function testForceIndexes() - { - $this->getContainer(); - - User::query()->get(); - User::query()->forceIndexes(['PRIMARY'])->where('id', '>', 1)->get(); - - $sqls = [ - ['select * from `user`', []], - ['select * from `user` force index (`PRIMARY`) where `id` > ?', [1]], - ]; - while ($event = $this->channel->pop(0.001)) { - if ($event instanceof QueryExecuted) { - $this->assertSame([$event->sql, $event->bindings], array_shift($sqls)); - } - } - } - public function testIncrement() { $this->getContainer(); diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 1b5f723..2622449 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -178,6 +178,36 @@ public function testCleanAttributes() $this->assertFalse($model->isClean(['foo', 'bar'])); } + public function testWasChangedAttributes() + { + $model = new ModelStub(['foo' => '1', 'bar' => 2, 'baz' => 3]); + $model->syncOriginal(); + $model->foo = 1; + $model->bar = 20; + $model->baz = 30; + + // Changes have not been synced yet, so no attribute was changed. + $this->assertFalse($model->wasChanged()); + $this->assertFalse($model->wasChanged('bar')); + + $model->syncChanges(); + + $this->assertTrue($model->wasChanged()); + $this->assertFalse($model->wasChanged('foo')); + $this->assertTrue($model->wasChanged('bar')); + $this->assertTrue($model->wasChanged('foo', 'bar')); + $this->assertTrue($model->wasChanged(['foo', 'bar'])); + + // All attributes are equivalent to their original values. + $model->syncOriginal(); + $model->syncChanges(); + + $this->assertFalse($model->wasChanged()); + $this->assertFalse($model->wasChanged('bar')); + $this->assertFalse($model->wasChanged('foo', 'bar')); + $this->assertFalse($model->wasChanged(['foo', 'bar'])); + } + public function testCalculatedAttributes() { $model = new ModelStub(); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index ed310f6..7453013 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -13,6 +13,7 @@ namespace HyperfTest\Database; use BadMethodCallException; +use Exception; use Hyperf\Collection\Collection; use Hyperf\Context\ApplicationContext; use Hyperf\Context\Context; @@ -1007,9 +1008,14 @@ public function testLimitsAndOffsets() $builder->select('*')->from('users')->skip(0)->take(0); $this->assertEquals('select * from "users" limit 0 offset 0', $builder->toSql()); - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->skip(-5)->take(-10); - $this->assertEquals('select * from "users" offset 0', $builder->toSql()); + try { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->skip(-5)->take(-10); + // $this->assertEquals('select * from "users" offset 0', $builder->toSql()); + } catch (Exception $e) { + $this->assertInstanceOf(InvalidArgumentException::class, $e); + $this->assertStringContainsString('Limit cannot be negative.', $e->getMessage()); + } } public function testForPage() diff --git a/types/Model/Builder.php b/types/Model/Builder.php index 02b16b7..f419aa8 100644 --- a/types/Model/Builder.php +++ b/types/Model/Builder.php @@ -48,11 +48,11 @@ function test( assertType('Hyperf\Database\Model\Collection', $query->findOr([1], callback: fn () => 42)); assertType('Hyperf\Types\Builder\User', $query->findOrFail(1)); assertType('Hyperf\Types\Builder\User|null', $query->find(1)); - assertType('Hyperf\Types\Builder\User|int', $query->findOr(1, fn () => 42)); - assertType('Hyperf\Types\Builder\User|int', $query->findOr(1, callback: fn () => 42)); + assertType('42|Hyperf\Types\Builder\User', $query->findOr(1, fn () => 42)); + assertType('42|Hyperf\Types\Builder\User', $query->findOr(1, callback: fn () => 42)); assertType('Hyperf\Types\Builder\User|null', $query->first()); - assertType('Hyperf\Types\Builder\User|int', $query->firstOr(fn () => 42)); - assertType('Hyperf\Types\Builder\User|int', $query->firstOr(callback: fn () => 42)); + assertType('42|Hyperf\Types\Builder\User', $query->firstOr(fn () => 42)); + assertType('42|Hyperf\Types\Builder\User', $query->firstOr(callback: fn () => 42)); assertType('Hyperf\Types\Builder\User', $query->firstOrNew(['id' => 1])); assertType('Hyperf\Types\Builder\User', $query->findOrNew(1)); assertType('Hyperf\Types\Builder\User', $query->firstOrCreate(['id' => 1])); @@ -196,7 +196,7 @@ function test( class User extends Model { - /** @return HasMany */ + /** @return HasMany */ public function posts(): HasMany { return $this->hasMany(Post::class); @@ -205,13 +205,13 @@ public function posts(): HasMany class Post extends Model { - /** @return BelongsTo */ + /** @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class); } - /** @return MorphTo */ + /** @return MorphTo */ public function taggable(): MorphTo { return $this->morphTo(); diff --git a/types/Model/Collection.php b/types/Model/Collection.php index 8716589..f96af31 100644 --- a/types/Model/Collection.php +++ b/types/Model/Collection.php @@ -15,7 +15,7 @@ assertType('Hyperf\Database\Model\Collection', $collection); assertType('User|null', $collection->find(1)); -assertType('string|User', $collection->find(1, 'string')); +assertType('\'string\'|User', $collection->find(1, 'string')); assertType('Hyperf\Database\Model\Collection', $collection->find([1])); assertType('Hyperf\Database\Model\Collection', $collection->load('string')); diff --git a/types/Model/Relations.php b/types/Model/Relations.php index cc1c45c..6843eca 100644 --- a/types/Model/Relations.php +++ b/types/Model/Relations.php @@ -114,59 +114,59 @@ function test(User $user, Post $post, Comment $comment, ChildUser $child): void class User extends Model { - /** @return HasOne */ + /** @return HasOne */ public function address(): HasOne { $hasOne = $this->hasOne(Address::class); - assertType('Hyperf\Database\Model\Relations\HasOne', $hasOne); + assertType('Hyperf\Database\Model\Relations\HasOne', $hasOne); return $hasOne; } - /** @return HasMany */ + /** @return HasMany */ public function posts(): HasMany { $hasMany = $this->hasMany(Post::class); - assertType('Hyperf\Database\Model\Relations\HasMany', $hasMany); + assertType('Hyperf\Database\Model\Relations\HasMany', $hasMany); return $hasMany; } - /** @return BelongsToMany */ + /** @return BelongsToMany */ public function roles(): BelongsToMany { $belongsToMany = $this->belongsToMany(Role::class); - assertType('Hyperf\Database\Model\Relations\BelongsToMany', $belongsToMany); + assertType('Hyperf\Database\Model\Relations\BelongsToMany', $belongsToMany); return $belongsToMany; } - /** @return HasOne */ + /** @return HasOne */ public function mechanic(): HasOne { return $this->hasOne(Mechanic::class); } - /** @return HasMany */ + /** @return HasMany */ public function mechanics(): HasMany { return $this->hasMany(Mechanic::class); } - /** @return HasOneThrough */ + /** @return HasOneThrough */ public function car(): HasOneThrough { $hasOneThrough = $this->hasOneThrough(Car::class, Mechanic::class); - assertType('Hyperf\Database\Model\Relations\HasOneThrough', $hasOneThrough); + assertType('Hyperf\Database\Model\Relations\HasOneThrough', $hasOneThrough); return $hasOneThrough; } - /** @return HasManyThrough */ + /** @return HasManyThrough */ public function parts(): HasManyThrough { $hasManyThrough = $this->hasManyThrough(Part::class, Mechanic::class); - assertType('Hyperf\Database\Model\Relations\HasManyThrough', $hasManyThrough); + assertType('Hyperf\Database\Model\Relations\HasManyThrough', $hasManyThrough); return $hasManyThrough; } @@ -174,38 +174,38 @@ public function parts(): HasManyThrough class Post extends Model { - /** @return BelongsTo */ + /** @return BelongsTo */ public function user(): BelongsTo { $belongsTo = $this->belongsTo(User::class); - assertType('Hyperf\Database\Model\Relations\BelongsTo', $belongsTo); + assertType('Hyperf\Database\Model\Relations\BelongsTo', $belongsTo); return $belongsTo; } - /** @return MorphOne */ + /** @return MorphOne */ public function image(): MorphOne { $morphOne = $this->morphOne(Image::class, 'imageable'); - assertType('Hyperf\Database\Model\Relations\MorphOne', $morphOne); + assertType('Hyperf\Database\Model\Relations\MorphOne', $morphOne); return $morphOne; } - /** @return MorphMany */ + /** @return MorphMany */ public function comments(): MorphMany { $morphMany = $this->morphMany(Comment::class, 'commentable'); - assertType('Hyperf\Database\Model\Relations\MorphMany', $morphMany); + assertType('Hyperf\Database\Model\Relations\MorphMany', $morphMany); return $morphMany; } - /** @return MorphToMany */ + /** @return MorphToMany */ public function tags(): MorphToMany { $morphToMany = $this->morphedByMany(Tag::class, 'taggable'); - assertType('Hyperf\Database\Model\Relations\MorphToMany', $morphToMany); + assertType('Hyperf\Database\Model\Relations\MorphToMany', $morphToMany); return $morphToMany; } @@ -213,11 +213,11 @@ public function tags(): MorphToMany class Comment extends Model { - /** @return MorphTo */ + /** @return MorphTo */ public function commentable(): MorphTo { $morphTo = $this->morphTo(); - assertType('Hyperf\Database\Model\Relations\MorphTo', $morphTo); + assertType('Hyperf\Database\Model\Relations\MorphTo', $morphTo); return $morphTo; } @@ -225,11 +225,11 @@ public function commentable(): MorphTo class Tag extends Model { - /** @return MorphToMany */ + /** @return MorphToMany */ public function posts(): MorphToMany { $morphToMany = $this->morphToMany(Post::class, 'taggable'); - assertType('Hyperf\Database\Model\Relations\MorphToMany', $morphToMany); + assertType('Hyperf\Database\Model\Relations\MorphToMany', $morphToMany); return $morphToMany; } @@ -237,13 +237,13 @@ public function posts(): MorphToMany class Mechanic extends Model { - /** @return HasOne */ + /** @return HasOne */ public function car(): HasOne { return $this->hasOne(Car::class); } - /** @return HasMany */ + /** @return HasMany */ public function parts(): HasMany { return $this->hasMany(Part::class);