0

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.

Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84

1 Answers1

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