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: Improve ClonableTrait readability #57

Merged
merged 1 commit into from
Dec 28, 2023
Merged
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
15 changes: 8 additions & 7 deletions src/Internal/ClonableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use ReflectionProperty;

use function array_column;
use function array_diff;
use function array_filter;
use function BenTools\ETL\array_fill_from;
use function get_object_vars;
Expand All @@ -27,17 +26,19 @@ trait ClonableTrait
*/
public function cloneWith(array $cloneArgs = []): static
{
static $refl, $writableProps, $writablePropNames, $constructorParamNames;
static $refl, $notPromotedWritablePropNames, $constructorParamNames;
$refl ??= new ReflectionClass($this);
$constructorParamNames ??= array_column($refl->getConstructor()->getParameters(), 'name');
$writableProps ??= array_filter(
$refl->getProperties(),
fn (ReflectionProperty $property) => !$property->isReadOnly(),
$notPromotedWritablePropNames ??= array_column(
array_filter(
$refl->getProperties(),
fn (ReflectionProperty $property) => !$property->isReadOnly() && !$property->isPromoted(),
),
'name'
);
$writablePropNames ??= array_diff(array_column($writableProps, 'name'), $constructorParamNames);

$clone = new static(...array_fill_from($constructorParamNames, get_object_vars($this), $cloneArgs));
$notPromotedProps = array_fill_from($writablePropNames, get_object_vars($this), $cloneArgs);
$notPromotedProps = array_fill_from($notPromotedWritablePropNames, get_object_vars($this), $cloneArgs);
foreach ($notPromotedProps as $prop => $value) {
$clone->{$prop} = $value;
}
Expand Down
Loading