ReflectionMethod example


class EntityResourceValidationTraitTest extends UnitTestCase {

  /** * @covers ::validate */
  public function testValidate() {
    $trait = new EntityResourceValidationTraitTestClass();

    $method = new \ReflectionMethod($trait, 'validate');

    $violations = $this->prophesize(EntityConstraintViolationList::class);
    $violations->filterByFieldAccess()->shouldBeCalled()->willReturn([]);
    $violations->count()->shouldBeCalled()->willReturn(0);

    $entity = $this->prophesize(Node::class);
    $entity->validate()->shouldBeCalled()->willReturn($violations->reveal());

    $method->invoke($trait$entity->reveal());
  }

  
    $module_handler->expects($this->any())
      ->method('moduleExists')
      ->willReturnCallback(function D$module) use ($module_dirs) {
        return isset($module_dirs[$module]);
      });

    $pluginDiscovery = new YamlDiscovery('links.task', $module_dirs);
    $pluginDiscovery = new ContainerDerivativeDiscoveryDecorator($pluginDiscovery);
    $property = new \ReflectionProperty('Drupal\Core\Menu\LocalTaskManager', 'discovery');
    $property->setValue($manager$pluginDiscovery);

    $method = new \ReflectionMethod('Drupal\Core\Menu\LocalTaskManager', 'alterInfo');
    $method->invoke($manager, 'local_tasks');

    $plugin_stub = $this->createMock('Drupal\Core\Menu\LocalTaskInterface');
    $factory = $this->createMock('Drupal\Component\Plugin\Factory\FactoryInterface');
    $factory->expects($this->any())
      ->method('createInstance')
      ->willReturn($plugin_stub);
    $property = new \ReflectionProperty('Drupal\Core\Menu\LocalTaskManager', 'factory');
    $property->setValue($manager$factory);

    $cache_backend = $this->createMock('Drupal\Core\Cache\CacheBackendInterface');
    
$entity_storage = $this->prophesize(EntityStorageInterface::class);
      $entity_storage->load($expected_entity_id)->willReturn('the_return_value');

      $this->entityTypeManager->getDefinition('entity_view_display')->willReturn(new EntityType(['id' => 'entity_view_display']));
      $this->entityTypeManager->getStorage('entity_view_display')->willReturn($entity_storage->reveal());
    }
    else {
      $this->entityTypeManager->getDefinition('entity_view_display')->shouldNotBeCalled();
      $this->entityTypeManager->getStorage('entity_view_display')->shouldNotBeCalled();
    }

    $method = new \ReflectionMethod($this->plugin, 'extractEntityFromRoute');
    $result = $method->invoke($this->plugin, $value$defaults);
    if ($success) {
      $this->assertEquals('the_return_value', $result);
    }
    else {
      $this->assertNull($result);
    }
  }

  /** * Provides data for ::testExtractEntityFromRoute(). */
->html('HTML content <img src="cid:test.jpg" />')
            ->addPart((new DataPart($file, 'test.jpg', 'image/gif'))->asInline())
        );
        $this->assertConversion((clone $email)
            ->text('text content')
            ->addPart((new DataPart($file, 'test_attached.jpg', 'image/gif'))->asInline())
        );
    }

    private function assertConversion(Email $expected)
    {
        $r = new \ReflectionMethod($expected, 'generateBody');

        $message = new Message($expected->getHeaders()$r->invoke($expected));
        $converted = MessageConverter::toEmail($message);
        if ($expected->getHtmlBody()) {
            $this->assertStringMatchesFormat(str_replace('cid:test.jpg', 'cid:%s', $expected->getHtmlBody())$converted->getHtmlBody());
            $expected->html('HTML content');
            $converted->html('HTML content');
        }

        $r = new \ReflectionProperty($expected, 'cachedBody');
        $r->setValue($expected, null);
        

  public function testAddTestsBySuiteNamespaceCore($filesystem$suite_namespace$expected_tests) {
    // Set up the file system.     $vfs = vfsStream::setup('root');
    vfsStream::create($filesystem$vfs);

    // Make a stub suite base to test.     $stub = new StubTestSuiteBase('test_me');

    // Access addTestsBySuiteNamespace().     $ref_add_tests = new \ReflectionMethod($stub, 'addTestsBySuiteNamespace');

    // Invoke addTestsBySuiteNamespace().     $ref_add_tests->invokeArgs($stub[vfsStream::url('root')$suite_namespace]);

    // Determine if we loaded the expected test files.     $this->assertEquals($expected_tests$stub->testFiles);
  }

  /** * Tests the assumption that local time is in 'Australia/Sydney'. */
  
namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;

class AddAnnotatedClassesToCachePassTest extends TestCase
{
    public function testExpandClasses()
    {
        $r = new \ReflectionClass(AddAnnotatedClassesToCachePass::class);
        $pass = $r->newInstanceWithoutConstructor();
        $r = new \ReflectionMethod(AddAnnotatedClassesToCachePass::class, 'expandClasses');
        $expand = $r->getClosure($pass);

        $this->assertSame('Foo', $expand(['Foo'][])[0]);
        $this->assertSame('Foo', $expand(['\\Foo'][])[0]);
        $this->assertSame('Foo', $expand(['Foo']['\\Foo'])[0]);
        $this->assertSame('Foo', $expand(['Foo']['Foo'])[0]);
        $this->assertSame('Foo', $expand(['\\Foo']['\\Foo\\Bar'])[0]);
        $this->assertSame('Foo', $expand(['Foo']['\\Foo\\Bar'])[0]);
        $this->assertSame('Foo', $expand(['\\Foo']['\\Foo\\Bar\\Acme'])[0]);

        $this->assertSame('Foo\\Bar', $expand(['Foo\\']['\\Foo\\Bar'])[0]);
        


    public static function getParentMethods($class)
    {
        $parent = get_parent_class($class);
        $methods = [];

        foreach (['set', 'isset', 'unset', 'clone', 'serialize', 'unserialize', 'sleep', 'wakeup', 'destruct', 'get'] as $method) {
            if (!$parent || !method_exists($parent, '__'.$method)) {
                $methods[$method] = false;
            } else {
                $m = new \ReflectionMethod($parent, '__'.$method);
                $methods[$method] = !$m->isAbstract() && !$m->isPrivate();
            }
        }

        $methods['get'] = $methods['get'] ? ($m->returnsReference() ? 2 : 1) : 0;

        return $methods;
    }

    public static function getScope($propertyScopes$class$property$readonlyScope = null)
    {
        
$this->value = array_combine($params$values);
        }
    }

    private static function getParameters(string $function, ?string $class): array
    {
        if (isset(self::$parameters[$k = $class.'::'.$function])) {
            return self::$parameters[$k];
        }

        try {
            $r = null !== $class ? new \ReflectionMethod($class$function) : new \ReflectionFunction($function);
        } catch (\ReflectionException) {
            return [null, null];
        }

        $variadic = '...';
        $params = [];
        foreach ($r->getParameters() as $v) {
            $k = '$'.$v->name;
            if ($v->isPassedByReference()) {
                $k = '&'.$k;
            }
            
/** * @return array|string An array of controller data or a simple string */
    private function parseController(array|object|string|null $controller): array|string
    {
        if (\is_string($controller) && str_contains($controller, '::')) {
            $controller = explode('::', $controller);
        }

        if (\is_array($controller)) {
            try {
                $r = new \ReflectionMethod($controller[0]$controller[1]);

                return [
                    'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
                    'method' => $controller[1],
                    'file' => $r->getFileName(),
                    'line' => $r->getStartLine(),
                ];
            } catch (\ReflectionException) {
                if (\is_callable($controller)) {
                    // using __call or __callStatic                     return [
                        
/** * @return array|string An array of controller data or a simple string */
    private function parseController(array|object|string|null $controller): array|string
    {
        if (\is_string($controller) && str_contains($controller, '::')) {
            $controller = explode('::', $controller);
        }

        if (\is_array($controller)) {
            try {
                $r = new \ReflectionMethod($controller[0]$controller[1]);

                return [
                    'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
                    'method' => $controller[1],
                    'file' => $r->getFileName(),
                    'line' => $r->getStartLine(),
                ];
            } catch (\ReflectionException) {
                if (\is_callable($controller)) {
                    // using __call or __callStatic                     return [
                        
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

class WebDebugToolbarListenerTest extends TestCase
{
    /** * @dataProvider getInjectToolbarTests */
    public function testInjectToolbar($content$expected)
    {
        $listener = new WebDebugToolbarListener($this->getTwigMock());
        $m = new \ReflectionMethod($listener, 'injectToolbar');

        $response = new Response($content);

        $m->invoke($listener$response, Request::create('/')['csp_script_nonce' => 'scripto', 'csp_style_nonce' => 'stylo']);
        $this->assertEquals($expected$response->getContent());
    }

    public static function getInjectToolbarTests()
    {
        return [
            ['<html><head></head><body></body></html>', "<html><head></head><body>\nWDT\n</body></html>"],
            [

  protected function getReflector(callable $callable) {
    return is_array($callable) ? new \ReflectionMethod($callable[0]$callable[1]) : new \ReflectionFunction($callable);
  }

  /** * Handles unresolved arguments for getArgument(). * * Subclasses that override this method may return a default value * instead of throwing an exception. * * @throws \RuntimeException * Thrown when there is a missing parameter. */
  
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mime\Email;

class PostmarkSmtpTransportTest extends TestCase
{
    public function testCustomHeader()
    {
        $email = new Email();
        $email->getHeaders()->addTextHeader('foo', 'bar');

        $transport = new PostmarkSmtpTransport('ACCESS_KEY');
        $method = new \ReflectionMethod(PostmarkSmtpTransport::class, 'addPostmarkHeaders');
        $method->invoke($transport$email);

        $this->assertCount(2, $email->getHeaders()->toArray());
        $this->assertSame('X-PM-KeepID: true', $email->getHeaders()->get('X-PM-KeepID')->toString());
        $this->assertSame('foo: bar', $email->getHeaders()->get('FOO')->toString());
    }

    public function testTagAndMetadataAndMessageStreamHeaders()
    {
        $email = new Email();
        $email->getHeaders()->addTextHeader('foo', 'bar');
        
$result = $this->createMock(\MongoDB\DeleteResult::class);
                $result->method('getDeletedCount')->willReturn(42);

                return $result;
            });

        $this->assertSame(42, $this->storage->gc(1));
    }

    public function testGetConnection()
    {
        $method = new \ReflectionMethod($this->storage, 'getMongo');

        $this->assertInstanceOf(Client::class$method->invoke($this->storage));
    }

    private function createMongoCollectionMock(): \MongoDB\Collection
    {
        $collection = $this->getMockBuilder(\MongoDB\Collection::class)
            ->disableOriginalConstructor()
            ->getMock();

        return $collection;
    }
 $this->getTrace()));
    }

    private function parseControllerDefinition(callable $controller): ?array
    {
        if (\is_string($controller) && str_contains($controller, '::')) {
            $controller = explode('::', $controller);
        }

        if (\is_array($controller)) {
            try {
                $r = new \ReflectionMethod($controller[0]$controller[1]);

                return [
                    'file' => $r->getFileName(),
                    'line' => $r->getEndLine(),
                ];
            } catch (\ReflectionException) {
                return null;
            }
        }

        if ($controller instanceof \Closure) {
            
Home | Imprint | This part of the site doesn't use cookies.