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

feat/add-support-for-key_by #8

Merged
merged 3 commits into from
Oct 29, 2024
Merged

Conversation

zero-to-prod
Copy link
Owner

Description

KeyBy

Key an array by an element value by using the key_by argument.

This also supports deep mapping.

class User
{
    use \Zerotoprod\DataModel\DataModel;
    use \Zerotoprod\DataModelHelper\DataModelHelper;
    
    /** @var Alias[] $Aliases */
    #[Describe([
        'cast' => [self::class, 'mapOf'],   
        'type' => Alias::class,             
        'key_by' => 'id',
    ])]
    public array $Aliases;
}

class Alias
{
    use \Zerotoprod\DataModel\DataModel;
    
    public string $id;
    public string $name;
}

$User = User::from([
    'Aliases' => [
        [
            'id' => 'jd1',
            'name' => 'John Doe',
        ],
        [
            'id' => 'js1',
            'name' => 'John Smith'
        ],
    ]
]);

echo $User->Aliases['jd1']->name;  // 'John Doe'
echo $User->Aliases['js1']->name); // 'John Smith'

@zero-to-prod zero-to-prod self-assigned this Oct 29, 2024
@zero-to-prod zero-to-prod added the enhancement New feature or request label Oct 29, 2024
@zero-to-prod zero-to-prod merged commit 867c11c into main Oct 29, 2024
3 checks passed
@zero-to-prod zero-to-prod deleted the feat/add-support-for-key_by branch November 19, 2024 13:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant