1

I have a function that looks like this

protected function getAllData(string $tableName, string $collectionKey): array
{
    // Some logic here to get records from database and store them in $records...
    $data = [
        'count' => count($records),
        $collectionKey => [],
    ];

    foreach ($records as $record) {
        $data[$collectionKey][] = [
            'name' => $record['name'],
            'value' => $record['value'],
        ];
    }

    return $data;
}

How can I define the array key $collectionKey which is passed in as a parameter`

    /**
     * @param string $tableName
     * @param string $collectionKey
     * @return array{
     *     count: int<0, max>,
     *     '?????': list<array{               <-- How?
     *         name: string,
     *         value: string,
     *     }>
     * }
     */
1
  • 1
    I don't have an answer to your question, but if you'll forgive the opinion, the return type feels like it is doing more than it needs to, both in returning count, which I, as the caller, can derive by myself, and also returning an indexed array using the key I gave it, something I also know. So instead of a simple array/list, I now have something much more complicated to work with, and it is easier as the caller to add this in then to remove it. Also, personally, if an array has magic keys, that screams DTO to me. Just my two cents, and I know you didn't ask for it. Commented Aug 26, 2024 at 12:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.