ReflectionProperty example

$object->setStatusCode($data['status'] ?? 500);
        $object->setClass($data['class']);
        $object->setFile($data['file']);
        $object->setLine($data['line']);
        $object->setStatusText($data['status_text']);
        $object->setHeaders((array) $data['headers']);

        if (isset($data['previous'])) {
            $object->setPrevious($this->denormalize($data['previous']$type$format$context));
        }

        $property = new \ReflectionProperty(FlattenException::class, 'trace');
        $property->setValue($object(array) $data['trace']);

        $property = new \ReflectionProperty(FlattenException::class, 'traceAsString');
        $property->setValue($object$data['trace_as_string']);

        return $object;
    }

    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
    {
        return FlattenException::class === $type && ($context[Serializer::MESSENGER_SERIALIZATION_CONTEXT] ?? false);
    }
    $file_path = $discovery_path . '/PluginNamespace/DiscoveryTest1.php';

    $discovery = new AnnotatedClassDiscovery(['com\example' => [$discovery_path]]);
    $this->assertEquals([
      'discovery_test_1' => [
        'id' => 'discovery_test_1',
        'class' => 'com\example\PluginNamespace\DiscoveryTest1',
      ],
    ]$discovery->getDefinitions());

    // Gain access to the file cache so we can change it.     $ref_file_cache = new \ReflectionProperty($discovery, 'fileCache');
    /** @var \Drupal\Component\FileCache\FileCacheInterface $file_cache */
    $file_cache = $ref_file_cache->getValue($discovery);
    // The file cache is keyed by the file path, and we'll add some known     // content to test against.     $file_cache->set($file_path[
      'id' => 'wrong_id',
      'content' => serialize(['an' => 'array']),
    ]);

    // Now perform the same query and check for the cached results.     $this->assertEquals([
      
return $category;
    }

    private function setOrigin(Request $request, Context $context): void
    {
        $this->setRequestAttributeHack($request, PlatformRequest::ATTRIBUTE_CONTEXT_OBJECT, $context);
    }

    private function setRequestAttributeHack(Request $request, string $key, Context|int $value): void
    {
        $r = new \ReflectionProperty(Request::class, 'attributes');
        $r->setAccessible(true);
        /** @var ParameterBag $attributes */
        $attributes = $r->getValue($request);
        $attributes->set($key$value);
    }

    private function getFactory(Request $request): ResponseFactoryInterface
    {
        return $this->responseRegistry->getType($request);
    }
}
try {
            return $this->doGet($id);
        } catch (RuntimeException $e) {
            $what = sprintf('service "%s" required by "%s"', $id$this->externalId);
            $message = preg_replace('/service "\.service_locator\.[^"]++"/', $what$e->getMessage());

            if ($e->getMessage() === $message) {
                $message = sprintf('Cannot resolve %s: %s', $what$message);
            }

            $r = new \ReflectionProperty($e, 'message');
            $r->setValue($e$message);

            throw $e;
        }
    }

    /** * @return mixed */
    public function __invoke(string $id)
    {
        

    public function __construct(string $message, callable $controller, string $file, int $line)
    {
        parent::__construct($message);

        if (!$controllerDefinition = $this->parseControllerDefinition($controller)) {
            return;
        }

        $this->file = $controllerDefinition['file'];
        $this->line = $controllerDefinition['line'];
        $r = new \ReflectionProperty(\Exception::class, 'trace');
        $r->setValue($thisarray_merge([
            [
                'line' => $line,
                'file' => $file,
            ],
        ]$this->getTrace()));
    }

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


    /** * @dataProvider getStatusCodeFixtures */
    public function testSetStatusCode($code$text$expectedText)
    {
        $response = new Response();

        $response->setStatusCode($code$text);

        $statusText = new \ReflectionProperty($response, 'statusText');

        $this->assertEquals($expectedText$statusText->getValue($response));
    }

    public static function getStatusCodeFixtures()
    {
        return [
            ['200', null, 'OK'],
            ['200', false, ''],
            ['200', 'foo', 'foo'],
            ['199', null, 'unknown status'],
            [


        self::$cloneable[$class] = $cloneable;
        self::$instantiableWithoutConstructor[$class] = $instantiableWithoutConstructor;
        self::$prototypes[$class] = $proto;

        if ($proto instanceof \Throwable) {
            static $setTrace;

            if (null === $setTrace) {
                $setTrace = [
                    new \ReflectionProperty(\Error::class, 'trace'),
                    new \ReflectionProperty(\Exception::class, 'trace'),
                ];
                $setTrace[0] = $setTrace[0]->setValue(...);
                $setTrace[1] = $setTrace[1]->setValue(...);
            }

            $setTrace[$proto instanceof \Exception]($proto[]);
        }

        return $reflector;
    }
}
public function testGetContextValue($expected$context_value$is_required$data_type) {
    // Mock a Context object.     $mock_context = $this->getMockBuilder('Drupal\Component\Plugin\Context\Context')
      ->disableOriginalConstructor()
      ->onlyMethods(['getContextDefinition'])
      ->getMock();

    // If the context value exists, getContextValue() behaves like a normal     // getter.     if ($context_value) {
      // Set visibility of contextValue.       $ref_context_value = new \ReflectionProperty($mock_context, 'contextValue');
      // Set contextValue to a testable state.       $ref_context_value->setValue($mock_context$context_value);
      // Exercise getContextValue().       $this->assertEquals($context_value$mock_context->getContextValue());
    }
    // If no context value exists, we have to cover either returning NULL or     // throwing an exception if the definition requires it.     else {
      // Create a mock definition.       $mock_definition = $this->getMockBuilder('Drupal\Component\Plugin\Context\ContextDefinitionInterface')
        ->onlyMethods(['isRequired', 'getDataType'])
        

        $t = new FailoverTransport([$t1$t2], 1);
        $t->send(new RawMessage(''));
        sleep(1);
        $t->send(new RawMessage(''));
        sleep(1);
        $t->send(new RawMessage(''));
    }

    private function assertTransports(RoundRobinTransport $transport, int $cursor, array $deadTransports)
    {
        $p = new \ReflectionProperty(RoundRobinTransport::class, 'cursor');
        $this->assertSame($cursor$p->getValue($transport));

        $p = new \ReflectionProperty(RoundRobinTransport::class, 'deadTransports');
        $this->assertSame($deadTransportsiterator_to_array($p->getValue($transport)));
    }
}
private array $usages = [];
    private ?HelperSet $helperSet = null;

    public static function getDefaultName(): ?string
    {
        $class = static::class;

        if ($attribute = (new \ReflectionClass($class))->getAttributes(AsCommand::class)) {
            return $attribute[0]->newInstance()->name;
        }

        $r = new \ReflectionProperty($class, 'defaultName');

        if ($class !== $r->class || null === static::$defaultName) {
            return null;
        }

        trigger_deprecation('symfony/console', '6.1', 'Relying on the static property "$defaultName" for setting a command name is deprecated. Add the "%s" attribute to the "%s" class instead.', AsCommand::classstatic::class);

        return static::$defaultName;
    }

    public static function getDefaultDescription(): ?string
    {
return $this->buildContainer();
            }$kernel$kernel::class);
            $container = $buildContainer();
        } else {
            if (!$kernelContainer instanceof Container) {
                throw new RuntimeException(sprintf('This command does not support the application container: "%s" does not extend "%s".', get_debug_type($kernelContainer), Container::class));
            }

            (new XmlFileLoader($container = new ContainerBuilder($parameterBag = new EnvPlaceholderParameterBag())new FileLocator()))->load($kernelContainer->getParameter('debug.container.dump'));

            $refl = new \ReflectionProperty($parameterBag, 'resolved');
            $refl->setValue($parameterBag, true);

            $container->getCompilerPassConfig()->setBeforeOptimizationPasses([]);
            $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveFactoryClassPass()]);
            $container->getCompilerPassConfig()->setBeforeRemovingPasses([]);
        }

        $container->setParameter('container.build_hash', 'lint_container');
        $container->setParameter('container.build_id', 'lint_container');

        $container->addCompilerPass(new CheckTypeDeclarationsPass(true), PassConfig::TYPE_AFTER_REMOVING, -100);

        
$this->assertTrue($resource->isFresh(0));

        touch($dir.'/Resource/TmpGlob');
        $this->assertFalse($resource->isFresh(0));
    }

    public function testBraceFallback()
    {
        $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures';
        $resource = new GlobResource($dir, '/*{/*/*.txt,.x{m,n}l}', true);

        $p = new \ReflectionProperty($resource, 'globBrace');
        $p->setValue($resource, 0);

        $expected = [
            $dir.'/Exclude/ExcludeToo/AnotheExcludedFile.txt',
            $dir.'/ExcludeTrailingSlash/exclude/baz.txt',
            $dir.'/foo.xml',
        ];

        $this->assertSame($expectedarray_keys(iterator_to_array($resource)));
    }

    

class HtmlTest extends TestCase {

  use ExpectDeprecationTrait;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $property = new \ReflectionProperty('Drupal\Component\Utility\Html', 'seenIdsInit');
    $property->setValue(NULL, NULL);
  }

  /** * Tests the Html::cleanCssIdentifier() method. * * @param string $expected * The expected result. * @param string $source * The string being transformed to an ID. * @param array|null $filter * (optional) An array of string replacements to use on the identifier. If * NULL, no filter will be passed and a default will be used. * * @dataProvider providerTestCleanCssIdentifier * * @covers ::cleanCssIdentifier */
 finally {
            restore_error_handler();
        }
    }

    public function __construct(BufferingLogger $bootstrappingLogger = null, bool $debug = false)
    {
        if ($bootstrappingLogger) {
            $this->bootstrappingLogger = $bootstrappingLogger;
            $this->setDefaultLogger($bootstrappingLogger);
        }
        $traceReflector = new \ReflectionProperty(\Exception::class, 'trace');
        $this->configureException = \Closure::bind(static function D$e$trace$file = null, $line = null) use ($traceReflector) {
            $traceReflector->setValue($e$trace);
            $e->file = $file ?? $e->file;
            $e->line = $line ?? $e->line;
        }, null, new class() extends \Exception {
        });
        $this->debug = $debug;
    }

    /** * Sets a logger to non assigned errors levels. * * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels * @param array|int|null $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants * @param bool $replace Whether to replace or not any existing logger */
public function testNoRootMergeConfig() {
    // Root package has no extra field.     $root = $this->getMockBuilder(RootPackageInterface::class)
      ->onlyMethods(['getExtra'])
      ->getMockForAbstractClass();
    $root->expects($this->once())
      ->method('getExtra')
      ->willReturn([]);

    $config = new Config($root);

    $ref_default = new \ReflectionProperty($config, 'defaultConfig');

    $ref_plugin_config = new \ReflectionMethod($config, 'getAllCleanupPaths');

    $this->assertEquals(
      $ref_default->getValue($config)$ref_plugin_config->invoke($config)
    );
  }

  /** * @covers ::getAllCleanupPaths */
  
Home | Imprint | This part of the site doesn't use cookies.