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

method injection only passes the first parameter if the method uses a splat for its parameter #881

Open
joachim-n opened this issue Feb 25, 2024 · 3 comments

Comments

@joachim-n
Copy link

joachim-n commented Feb 25, 2024

If I do:

  'letters' => DI\create(Letters::class)
    ->method(
      'setLetters',
      DI\get('alpha'),
      DI\get('beta'),
    ),

and

  public function setLetters($alpha, $beta) {

then both services are passed in. But if I change the method signature to this:

  public function setLetters(...$letters) {

Then $letters is an array with only the first service.

Full test code:

<?php

require 'vendor/autoload.php';

$container = new DI\Container([
  'alpha'   => DI\create(Alpha::class),
  'beta'    => DI\create(Beta::class),
  'letters' => DI\create(Letters::class)
    ->method(
      'setLettersList',
      DI\get('alpha'),
      DI\get('beta'),
    )
    ->method(
      'setLettersSplat',
      DI\get('alpha'),
      DI\get('beta'),
    ),
]);

class Alpha {}
class Beta {}

class Letters {
  public function setLettersList($alpha, $beta) {
    dump(__METHOD__);
    dump(func_get_args());
  }

  public function setLettersSplat(...$letters) {
    // Should also get all the letters, but only gets the first one.
    dump(__METHOD__);
    dump(func_get_args());
  }
}

$letters = $container->get('letters');
@joachim-n
Copy link
Author

ObjectCreator::injectMethodsAndProperties() seems to be correctly getting $args in both cases, which makes it look like the problem is when the method is invoked here:

            $methodReflection->invokeArgs($object, $args);

But doing that directly on the objects works properly:

$letters = new Letters();
$methodReflection = new \ReflectionMethod($letters, 'setLettersSplat');
$args = [1, 2];
$methodReflection->invokeArgs($letters, $args);

@joachim-n
Copy link
Author

My mistake -- I got confused with $args in the loop.

This line doesn't get the complete array but only the first item:

            $args = $this->parameterResolver->resolveParameters($methodInjection, $methodReflection);

serge-kvashnin added a commit to serge-kvashnin/PHP-DI that referenced this issue Apr 16, 2024
@serge-kvashnin
Copy link

@joachim-n The PR I created should fix the issue you mentioned: #883

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants