Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,17 @@ public static function create(array $attributes): static
return $model;
}

/**
* Create a new model instance from another model and save it to the database.
*
* @param Model $model
* @return static
*/
public static function createFromModel(Model $model): static
{
return self::create($model->getAttributes());
}

/**
* Get the attributes that are allowed to be mass-assigned.
*
Expand Down
20 changes: 20 additions & 0 deletions src/Phaseolies/Support/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Ramsey\Collection\Collection;
use Phaseolies\Utilities\Attributes\Resolver;
use Phaseolies\Utilities\Attributes\Middleware;
use Phaseolies\Utilities\Attributes\BindPayload;
use Phaseolies\Support\Router\InteractsWithCurrentRouter;
use Phaseolies\Support\Router\InteractsWithBundleRouter;
use Phaseolies\Middleware\Contracts\Middleware as ContractsMiddleware;
Expand Down Expand Up @@ -1265,6 +1266,25 @@ private function resolveParameters(array $parameters, Application $app, array $r
$paramName = $parameter->getName();
$paramType = $parameter->getType();

// Handle DTO binding when parameter is marked with BindPayload attribute
$mapAttributes = $parameter->getAttributes(BindPayload::class);
if (!empty($mapAttributes)) {
if ($paramType && !$paramType->isBuiltin()) {
$dtoClass = $paramType->getName();
if (!class_exists($dtoClass)) {
throw new \Exception("Cannot resolve DTO class '$dtoClass' for parameter '$paramName'");
}

$dto = new $dtoClass();
/** @var Request $request */
$request = $app->make('request');
$attributeInstance = $mapAttributes[0]->newInstance();
$dependencies[] = $request->bindTo($dto, (bool)($attributeInstance->strict ?? true));
continue;
}
throw new \Exception("Parameter '$paramName' must be a class-typed DTO when using Payload");
}

if ($paramType && !$paramType->isBuiltin()) {
$resolvedClass = $paramType->getName();
$resolvedInstance = $this->resolveFormRequestValidationClass($app, $resolvedClass);
Expand Down
11 changes: 11 additions & 0 deletions src/Phaseolies/Utilities/Attributes/BindPayload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Phaseolies\Utilities\Attributes;

#[\Attribute(\Attribute::TARGET_PARAMETER)]
class BindPayload
{
public function __construct(
public bool $strict = true,
) {}
}
Loading