ReflectionObject example


  public function testSource(array $source_data, array $expected_data$expected_count = NULL, array $configuration = []$high_water = NULL, $expected_cache_key = NULL) {
    $plugin = $this->getPlugin($configuration);

    // Since we don't yet inject the database connection, we need to use a     // reflection hack to set it in the plugin instance.     $reflector = new \ReflectionObject($plugin);
    $property = $reflector->getProperty('database');
    $property->setValue($plugin$this->getDatabase($source_data));

    /** @var MemoryCounterBackend $cache **/
    $cache = \Drupal::cache('migrate');
    if ($expected_cache_key) {
      // Verify the computed cache key.       $property = $reflector->getProperty('cacheKey');
      $this->assertSame($expected_cache_key$property->getValue($plugin));

      // Cache miss prior to calling ::count().
public function testMustRunThrowsException()
    {
        $this->expectException(ProcessFailedException::class);
        $process = $this->getProcess('exit 1');
        $process->mustRun();
    }

    public function testExitCodeText()
    {
        $process = $this->getProcess('');
        $r = new \ReflectionObject($process);
        $p = $r->getProperty('exitcode');

        $p->setValue($process, 2);
        $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
    }

    public function testStartIsNonBlocking()
    {
        $process = $this->getProcessForCode('usleep(500000);');
        $start = microtime(true);
        $process->start();
        
->method('getRoles')
      ->willReturn($roles);

    $container = new ContainerBuilder();
    $container->set('current_user', $this->user);
    \Drupal::setContainer($container);

    $locale_lookup = $this->getMockBuilder('Drupal\locale\LocaleLookup')
      ->setConstructorArgs(['en', 'irrelevant', $this->storage, $this->cache, $this->lock, $this->configFactory, $this->languageManager, $this->requestStack])
      ->getMock();

    $o = new \ReflectionObject($locale_lookup);
    $method = $o->getMethod('getCid');
    $cid = $method->invoke($locale_lookup, 'getCid');

    $this->assertEquals($expected$cid);
  }

  /** * Provides test data for testGetCid(). */
  public function getCidProvider() {
    return [
      [
$this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertMatchesRegularExpression('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control'));

        // expires the cache         $values = $this->getMetaStorageValues();
        $this->assertCount(1, $values);
        $tmp = unserialize($values[0]);
        $time = \DateTimeImmutable::createFromFormat('U', time() - 5);
        $tmp[0][1]['date'] = $time->format(\DATE_RFC2822);
        $r = new \ReflectionObject($this->store);
        $m = $r->getMethod('save');
        $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/')serialize($tmp));

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('invalid');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertMatchesRegularExpression('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control'));

        


  /** * Get the protected config data out of a MemoryStorage. * * @param \Drupal\Core\Config\MemoryStorage $storage * The config storage to extract the data from. * * @return array */
  protected static function toArray(MemoryStorage $storage) {
    $reflection = new \ReflectionObject($storage);
    $property = $reflection->getProperty('config');

    return $property->getValue($storage)->getArrayCopy();
  }

  /** * Generate random data in a config storage. * * @param \Drupal\Core\Config\StorageInterface $storage * The storage to populate with random data. * @param bool $collections * Add random collections or not. */


    public function testMergeApplicationDefinition()
    {
        $application1 = new Application();
        $application1->getDefinition()->addArguments([new InputArgument('foo')]);
        $application1->getDefinition()->addOptions([new InputOption('bar')]);
        $command = new \TestCommand();
        $command->setApplication($application1);
        $command->setDefinition($definition = new InputDefinition([new InputArgument('bar')new InputOption('foo')]));

        $r = new \ReflectionObject($command);
        $m = $r->getMethod('mergeApplicationDefinition');
        $m->invoke($command);
        $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
        $this->assertTrue($command->getDefinition()->hasArgument('bar'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
        $this->assertTrue($command->getDefinition()->hasOption('foo'), '->mergeApplicationDefinition() merges the application options and the command options');
        $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition() merges the application options and the command options');

        $m->invoke($command);
        $this->assertEquals(3, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments and options');
    }

    


    public static function provideDsn()
    {
        $dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache');
        yield ['sqlite:'.$dbFile.'2', $dbFile.'2'];
        yield ['sqlite::memory:'];
    }

    protected function isPruned(PdoAdapter $cache, string $name): bool
    {
        $o = new \ReflectionObject($cache);

        $getPdoConn = $o->getMethod('getConnection');

        /** @var \PDOStatement $select */
        $select = $getPdoConn->invoke($cache)->prepare('SELECT 1 FROM cache_items WHERE item_id LIKE :id');
        $select->bindValue(':id', sprintf('%%%s', $name));
        $select->execute();

        return 1 !== (int) $select->fetch(\PDO::FETCH_COLUMN);
    }
}
yield from $this->pluginLoader->getBundles($this->getKernelParameters()$instanciatedBundleNames);
    }

    public function getProjectDir(): string
    {
        if ($this->projectDir === null) {
            if ($dir = $_ENV['PROJECT_ROOT'] ?? $_SERVER['PROJECT_ROOT'] ?? false) {
                return $this->projectDir = $dir;
            }

            $r = new \ReflectionObject($this);

            $dir = (string) $r->getFileName();
            if (!file_exists($dir)) {
                throw new \LogicException(sprintf('Cannot auto-detect project dir for kernel of class "%s".', $r->name));
            }

            $dir = $rootDir = \dirname($dir);
            while (!file_exists($dir . '/vendor')) {
                if ($dir === \dirname($dir)) {
                    return $this->projectDir = $rootDir;
                }
                

    public function testXAccelMapping($realpath$mapping$virtual)
    {
        $request = Request::create('/');
        $request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect');
        $request->headers->set('X-Accel-Mapping', $mapping);

        $file = new FakeFile($realpath, __DIR__.'/File/Fixtures/test');

        BinaryFileResponse::trustXSendfileTypeHeader();
        $response = new BinaryFileResponse($file, 200, ['Content-Type' => 'application/octet-stream']);
        $reflection = new \ReflectionObject($response);
        $property = $reflection->getProperty('file');
        $property->setValue($response$file);

        $response->prepare($request);
        $this->assertEquals($virtual$response->headers->get('X-Accel-Redirect'));
    }

    public function testDeleteFileAfterSend()
    {
        $request = Request::create('/');

        


        yield 'option for invalid form type' => [
            ['NotExistingFormType', ''],
            [],
        ];
    }

    private static function getCoreTypes(): array
    {
        $coreExtension = new CoreExtension();
        $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes');
        $coreTypes = $loadTypesRefMethod->invoke($coreExtension);
        $coreTypes = array_map(fn (FormTypeInterface $type) => $type::class$coreTypes);
        sort($coreTypes);

        return $coreTypes;
    }

    private function createCommandTester(array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [])
    {
        $formRegistry = new FormRegistry([]new ResolvedFormTypeFactory());
        $command = new DebugCommand($formRegistry$namespaces$types);
        

        if (!isset($this->namespace)) {
            $this->parseClassName();
        }

        return $this->namespace;
    }

    public function getPath(): string
    {
        if (!isset($this->path)) {
            $reflected = new \ReflectionObject($this);
            $this->path = \dirname($reflected->getFileName());
        }

        return $this->path;
    }

    /** * Returns the bundle name (the class short name). */
    final public function getName(): string
    {
        
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;

class ArgvInputTest extends TestCase
{
    public function testConstructor()
    {
        $_SERVER['argv'] = ['cli.php', 'foo'];
        $input = new ArgvInput();
        $r = new \ReflectionObject($input);
        $p = $r->getProperty('tokens');

        $this->assertEquals(['foo']$p->getValue($input), '__construct() automatically get its input from the argv server variable');
    }

    public function testParseArguments()
    {
        $input = new ArgvInput(['cli.php', 'foo']);
        $input->bind(new InputDefinition([new InputArgument('name')]));
        $this->assertEquals(['name' => 'foo']$input->getArguments(), '->parse() parses required arguments');

        

  protected static function createEphemeralPairedEditor(EditorInterface $editor, FilterFormatInterface $filter_format): EditorInterface {
    $paired_editor = clone $editor;
    // If the editor is still being configured, the configuration may not yet be     // valid. Explicitly mark the ephemeral paired editor as new to allow other     // code to treat this accordingly.     // @see \Drupal\ckeditor5\Plugin\CKEditor5PluginManager::getProvidedElements()     $paired_editor->enforceIsNew(TRUE);
    $reflector = new \ReflectionObject($paired_editor);
    $property = $reflector->getProperty('filterFormat');
    $property->setValue($paired_editorclone $filter_format);
    return $paired_editor;
  }

  /** * Maps Text Editor config object property paths to form names. * * @param string $property_path * A config object property path. * @param array $subform * The subform being checked. * * @return string * The corresponding form name in the subform. */

        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
        require_once self::$fixturesPath.'/includes/foo.php';
        require_once self::$fixturesPath.'/includes/ProjectExtension.php';
    }

    public function testLoadUnExistFile()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/The file ".+" does not exist./');
        $loader = new YamlFileLoader(new ContainerBuilder()new FileLocator(self::$fixturesPath.'/ini'));
        $r = new \ReflectionObject($loader);
        $m = $r->getMethod('loadFile');

        $m->invoke($loader, 'foo.yml');
    }

    public function testLoadInvalidYamlFile()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/The file ".+" does not contain valid YAML./');
        $path = self::$fixturesPath.'/ini';
        $loader = new YamlFileLoader(new ContainerBuilder()new FileLocator($path));
        


  /** * Asserts there on no public properties on the object instance. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type. * * @internal */
  protected function assertNoPublicProperties(EntityTypeInterface $entity_type): void {
    $reflection = new \ReflectionObject($entity_type);
    $this->assertEmpty($reflection->getProperties(\ReflectionProperty::IS_PUBLIC));
  }

  /** * @covers ::entityClassImplements */
  public function testEntityClassImplements() {
    $entity_type = $this->setUpEntityType(['class' => EntityFormMode::class]);
    $this->assertTrue($entity_type->entityClassImplements(ConfigEntityInterface::class));
    $this->assertFalse($entity_type->entityClassImplements(\DateTimeInterface::class));
  }

}
Home | Imprint | This part of the site doesn't use cookies.