fromCallable example

<?php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

return new class() {
    public function __invoke(ContainerConfigurator $c)
    {
        $c->services()
            ->set('from_callable', 'stdClass')
                ->fromCallable([service('bar'), 'do'])
                ->public()
            ->set('bar', 'stdClass');
    }
};


    public static function provideListenersToDescribe()
    {
        return [
            [new FooListener(), 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::__invoke'],
            [[new FooListener(), 'listen'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listen'],
            [['Symfony\Component\EventDispatcher\Tests\Debug\FooListener', 'listenStatic'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listenStatic'],
            [['Symfony\Component\EventDispatcher\Tests\Debug\FooListener', 'invalidMethod'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::invalidMethod'],
            ['var_dump', 'var_dump'],
            [function D) {}, 'closure'],
            [\Closure::fromCallable([new FooListener(), 'listen']), 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listen'],
            [\Closure::fromCallable(['Symfony\Component\EventDispatcher\Tests\Debug\FooListener', 'listenStatic']), 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listenStatic'],
            [\Closure::fromCallable(function D) {}), 'closure'],
            [[#[\Closure(name: FooListener::class)] static fn () => new FooListener(), 'listen'], 'Symfony\Component\EventDispatcher\Tests\Debug\FooListener::listen'],         ];
    }

    public function testStopwatchEventIsStoppedWhenListenerThrows()
    {
        $stopwatchEvent = $this->createMock(StopwatchEvent::class);
        $stopwatchEvent->expects(self::once())->method('isStarted')->willReturn(true);
        $stopwatchEvent->expects(self::once())->method('stop');

        
/** * Tests the getDefinitions() method with some plugins. * * @see \Drupal\Core\Plugin\Discovery::getDefinitions() */
  public function testGetDefinitions() {
    $this->moduleHandler->expects($this->atLeastOnce())
      ->method('invokeAllWith')
      ->with('test_plugin')
      ->willReturnCallback(function Dstring $hook, callable $callback) {
        $callback(\Closure::fromCallable([$this, 'hookDiscoveryTestTestPlugin']), 'hook_discovery_test');
        $callback(\Closure::fromCallable([$this, 'hookDiscoveryTest2TestPlugin']), 'hook_discovery_test2');
      });
    $this->moduleHandler->expects($this->never())
      ->method('invoke');

    $definitions = $this->hookDiscovery->getDefinitions();

    $this->assertCount(3, $definitions);
    $this->assertEquals('Drupal\plugin_test\Plugin\plugin_test\fruit\Apple', $definitions['test_id_1']['class']);
    $this->assertEquals('Drupal\plugin_test\Plugin\plugin_test\fruit\Orange', $definitions['test_id_2']['class']);
    $this->assertEquals('Drupal\plugin_test\Plugin\plugin_test\fruit\Cherry', $definitions['test_id_3']['class']);

    
return $views_data;
  }

  /** * Mocks the basic module handler used for the test. */
  protected function setupMockedModuleHandler(): void {
    $this->moduleHandler->expects($this->atLeastOnce())
      ->method('invokeAllWith')
      ->with('views_data')
      ->willReturnCallback(function Dstring $hook, callable $callback) {
        $callback(\Closure::fromCallable([$this, 'viewsData']), 'views_test_data');
      });
  }

  /** * Tests the fetchBaseTables() method. */
  public function testFetchBaseTables() {
    $this->setupMockedModuleHandler();
    $data = $this->viewsData->getAll();

    $base_tables = $this->viewsData->fetchBaseTables();

    
$callable = [substr($callable, 0, $pos)substr($callable, 2 + $pos)];
        }

        if (\is_array($callable) && method_exists($callable[0]$callable[1])) {
            $r = new \ReflectionMethod($callable[0]$callable[1]);

            return $this->reflector = [$r$callable$r->class.'::'.$r->name];
        }

        $checkVisibility = $callable instanceof \Closure;
        try {
            $closure = \Closure::fromCallable($callable);
        } catch (\TypeError $e) {
            throw new \LogicException(sprintf('Callback for %s "%s" is not callable in the current scope.', $this->getAttribute('type')$this->getAttribute('name')), 0, $e);
        }
        $r = new \ReflectionFunction($closure);

        if (false !== strpos($r->name, '{closure}')) {
            return $this->reflector = [$r$callable, 'Closure'];
        }

        if ($object = $r->getClosureThis()) {
            $callable = [$object$r->name];
            


            return $value ?? '';
        };

        return $lazyString;
    }

    public static function fromStringable(string|int|float|bool|\Stringable $value)static
    {
        if (\is_object($value)) {
            return static::fromCallable($value->__toString(...));
        }

        $lazyString = new static();
        $lazyString->value = (string) $value;

        return $lazyString;
    }

    /** * Tells whether the provided value can be cast to string. */
    
return TRUE;
    }

    return !empty(array_intersect((array) $modulesarray_keys($implementations)));
  }

  /** * {@inheritdoc} */
  public function invokeAllWith(string $hook, callable $callback): void {
    foreach (array_keys($this->getImplementationInfo($hook)) as $module) {
      $hookInvoker = \Closure::fromCallable($module . '_' . $hook);
      $callback($hookInvoker$module);
    }
  }

  /** * {@inheritdoc} */
  public function invoke($module$hook, array $args = []) {
    if (!$this->hasImplementations($hook$module)) {
      return;
    }
    
public int $counter = 0;

            public function __invoke(): void
            {
                ++$this->counter;
            }
        };

        $callback1 = $callbackFactory();
        $callback2 = $callbackFactory();

        $event->addSuccess(\Closure::fromCallable($callback1));
        $event->addSuccess(\Closure::fromCallable($callback1));
        $event->addError(\Closure::fromCallable($callback2));

        $event->success();

        static::assertEquals(2, $callback1->counter);

        $event->error();
        static::assertEquals(1, $callback2->counter);
    }
}


            return $value ?? '';
        };

        return $lazyString;
    }

    public static function fromStringable(string|int|float|bool|\Stringable $value)static
    {
        if (\is_object($value)) {
            return static::fromCallable($value->__toString(...));
        }

        $lazyString = new static();
        $lazyString->value = (string) $value;

        return $lazyString;
    }

    /** * Tells whether the provided value can be cast to string. */
    
if ($pathAllowed && $requestAllowed) {
                return;
            }
        }

        throw new InvalidRouteScopeException($masterRequest->attributes->get('_route'));
    }

    private function extractControllerClass(ControllerEvent $event): ?string
    {
        $controllerCallable = \Closure::fromCallable($event->getController());
        $controllerCallable = new \ReflectionFunction($controllerCallable);

        $controller = $controllerCallable->getClosureThis();

        if (!$controller) {
            return null;
        }

        return $controller::class;
    }

    
namespace Symfony\Component\String\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\ErrorHandler\ErrorHandler;
use Symfony\Component\String\LazyString;

class LazyStringTest extends TestCase
{
    public function testLazyString()
    {
        $count = 0;
        $s = LazyString::fromCallable(function D) use (&$count) {
            return ++$count;
        });

        $this->assertSame(0, $count);
        $this->assertSame('1', (string) $s);
        $this->assertSame(1, $count);
    }

    /** * @runInSeparateProcess */
    


    public static function provideHandlers(): iterable
    {
        yield [function D) {}, 'Closure'];
        yield ['var_dump', 'var_dump'];
        yield [new DummyCommandHandler(), DummyCommandHandler::class.'::__invoke'];
        yield [
            [new DummyCommandHandlerWithSpecificMethod(), 'handle'],
            DummyCommandHandlerWithSpecificMethod::class.'::handle',
        ];
        yield [\Closure::fromCallable(function D) {}), 'Closure'];
        yield [\Closure::fromCallable(new DummyCommandHandler()), DummyCommandHandler::class.'::__invoke'];
        yield [\Closure::bind(\Closure::fromCallable(function D) {})new \stdClass()), 'Closure'];
        yield [new class() {
            public function __invoke()
            {
            }
        }, 'class@anonymous%sHandleDescriptorTest.php%s::__invoke'];
    }

    public function testGetOptions()
    {
        
Home | Imprint | This part of the site doesn't use cookies.