-1

I am blocked with some phpstan validation, I have this array:

   /** @var array<string, string|array<string>> $normalizedImage */
   $normalizedImage = $this->normalizer->normalize($data);
   $normalizedImage['@id'] = $this->iriConverter->getIriFromItem($data);
   $normalizedImage['property']['@id'] = $this->iriConverter->getIriFromItem($object);

The error is:

phpstan: Cannot assign offset '@id' to array|string.

I tried most of combinations in the comment, but I can't figure out what to put here.

2
  • Does pipe is authorized here ? Does getIriFromItem return a string ? Commented Jan 6, 2023 at 15:04
  • Yes sorry, it returns a string not nullable, and not sure about the pipe, gonna try on simpler cases Commented Jan 6, 2023 at 15:11

1 Answer 1

0

Looking at the phpdoc

@psalm-return array{_labels?: array<string>}&array<int|string>
@phpstan-return array<int|string|array<string>>

I would say it's not surprising, since phpstan doesn't support a type similar to set both specific keys types and generics ones. But this would be great.

Can be fixed this way :

<?php declare(strict_types = 1);

$result = [
    '@id' => [],
];

$labels = [];
foreach ([1, 2, 3] as $id) {
    $result[] = $id;
    $labels[] = 'asda';
}

$result['@id'] = $labels;

You can try it here: https://phpstan.org/try There is no errors anymore

Sign up to request clarification or add additional context in comments.

Comments

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.