var_export example

// top level data object was normalized into a scalar             if (!$parentNode->parentNode->parentNode) {
                $root = $parentNode->parentNode;
                $root->removeChild($parentNode);

                return $this->appendNode($root$data$format$context$xmlRootNodeName);
            }

            return $this->appendNode($parentNode$data$format$context, 'data');
        }

        throw new NotEncodableValueException('An unexpected value could not be serialized: '.(!\is_resource($data) ? var_export($data, true) : sprintf('%s resource', get_resource_type($data))));
    }

    /** * Selects the type of node to create and appends it to the parent. */
    private function appendNode(\DOMNode $parentNode, mixed $data, string $format, array $context, string $nodeName, string $key = null): bool
    {
        $dom = $parentNode instanceof \DOMDocument ? $parentNode : $parentNode->ownerDocument;
        $node = $dom->createElement($nodeName);
        if (null !== $key) {
            $node->setAttribute('key', $key);
        }
return $response;
    }

    /** * @param Request $request * * @return string */
    protected function getScript(object $request)
    {
        $kernel = var_export(serialize($this->kernel), true);
        $request = var_export(serialize($request), true);

        $errorReporting = error_reporting();

        $requires = '';
        foreach (get_declared_classes() as $class) {
            if (str_starts_with($class, 'ComposerAutoloaderInit')) {
                $r = new \ReflectionClass($class);
                $file = \dirname($r->getFileName(), 2).'/autoload.php';
                if (file_exists($file)) {
                    $requires .= 'require_once '.var_export($file, true).";\n";
                }
// @todo Fix the parser, eliminate this exception.         $this->expectException(ParseException::class);
        $this->expectExceptionMessage('Unable to parse at line 2 (near "!text |").');
        $this->parser->parse($yml, Yaml::PARSE_CUSTOM_TAGS);
    }

    /** * @dataProvider getDataFormSpecifications */
    public function testSpecifications($expected$yaml$comment)
    {
        $this->assertEquals($expectedvar_export($this->parser->parse($yaml), true)$comment);
    }

    public static function getDataFormSpecifications()
    {
        return self::loadTestsFromFixtureFiles('index.yml');
    }

    public static function getNonStringMappingKeysData()
    {
        return self::loadTestsFromFixtureFiles('nonStringKeys.yml');
    }

    
use Symfony\Component\Translation\MessageCatalogue;

/** * PhpFileDumper generates PHP files from a message catalogue. * * @author Michel Salib <michelsalib@hotmail.com> */
class PhpFileDumper extends FileDumper
{
    public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []): string
    {
        return "<?php\n\nreturn ".var_export($messages->all($domain), true).";\n";
    }

    protected function getExtension(): string
    {
        return 'php';
    }
}
$this->writeData(['remainingCount' => $remainingCount, 'deprecations' => $formattedLogs]$options);
    }

    private function writeData(array $data, array $options): void
    {
        $flags = $options['json_encoding'] ?? 0;

        // Recursively search for enum values, so we can replace it         // before json_encode (which will not display anything for \UnitEnum otherwise)         array_walk_recursive($datastatic function D&$value) {
            if ($value instanceof \UnitEnum) {
                $value = ltrim(var_export($value, true), '\\');
            }
        });

        $this->write(json_encode($data$flags | \JSON_PRETTY_PRINT)."\n");
    }

    protected function getRouteData(Route $route): array
    {
        $data = [
            'path' => $route->getPath(),
            'pathRegex' => $route->compile()->getRegex(),
            
$content .= '];' . \PHP_EOL;

        file_put_contents($this->path, $content);
    }

    private function dumpDataShort(): string
    {
        $content = '';

        foreach ($this->data as $key => $value) {
            $content .= ' ' . $this->formatKey($key) . ' => ' . var_export($value, true) . ',' . \PHP_EOL;
        }

        return $content;
    }

    private function dumpDataLong(): string
    {
        $content = '';

        foreach ($this->data as $key => $value) {
            if ($value === '') {
                

  public function assertFilteredString(FilterInterface $filter, array $tests): void {
    foreach ($tests as $source => $tasks) {
      $result = $filter->process($source$filter)->getProcessedText();
      foreach ($tasks as $value => $is_expected) {
        if ($is_expected) {
          $this->assertStringContainsString($value$resultnew FormattableMarkup('@source: @value found. Filtered result: @result.', [
            '@source' => var_export($source, TRUE),
            '@value' => var_export($value, TRUE),
            '@result' => var_export($result, TRUE),
          ]));
        }
        else {
          $this->assertStringNotContainsString($value$resultnew FormattableMarkup('@source: @value not found. Filtered result: @result.', [
            '@source' => var_export($source, TRUE),
            '@value' => var_export($value, TRUE),
            '@result' => var_export($result, TRUE),
          ]));
        }
      }
yield 'Date with full microseconds' => [
            ['date' => new \DateTimeImmutable('2023-01-24T01:02:03.456789Z')],
            'date: 2023-01-24T01:02:03.456789+00:00',
        ];
    }

    private function assertSameData($expected$actual)
    {
        $this->assertEquals($expected$actual);
        $this->assertSame(
            var_export($expected, true),
            var_export($actual, true)
        );
    }
}

class A
{
    public $a = 'foo';
}
// Create new role.     $role = Role::create([
      'id' => $rid,
      'label' => $name,
    ]);
    if (isset($weight)) {
      $role->set('weight', $weight);
    }
    $result = $role->save();

    $this->assertSame(SAVED_NEW, $resultnew FormattableMarkup('Created role ID @rid with name @name.', ['@name' => var_export($role->label(), TRUE), '@rid' => var_export($role->id(), TRUE)]));

    if ($result === SAVED_NEW) {
      // Grant the specified permissions to the role, if any.       if (!empty($permissions)) {
        $this->grantPermissions($role$permissions);
        $assigned_permissions = Role::load($role->id())->getPermissions();
        $missing_permissions = array_diff($permissions$assigned_permissions);
        $this->assertEmpty($missing_permissions);
      }
      return $role->id();
    }
    

        $class->addMethod($node->getName()$body[
            'PROPERTY' => $property->getName(),
            'COMMENT' => $comment,
            'DEFAULT' => $node->hasDefaultValue() ? ' = '.var_export($node->getDefaultValue(), true) : '',
        ]);
    }

    private function handlePrototypedArrayNode(PrototypedArrayNode $node, ClassBuilder $class, string $namespace): void
    {
        $name = $this->getSingularName($node);
        $prototype = $node->getPrototype();
        $methodName = $name;
        $hasNormalizationClosures = $this->hasNormalizationClosures($node) || $this->hasNormalizationClosures($prototype);

        $nodeParameterTypes = $this->getParameterTypes($node);
        

        $dumpedValue = $this->getDump($value);
        $isStaticValue = true;
        $marshalledValue = VarExporter::export($value$isStaticValue);

        $this->assertSame($staticValueExpected$isStaticValue);
        if ('var-on-sleep' !== $testName && 'php74-serializable' !== $testName) {
            $this->assertDumpEquals($dumpedValue$value);
        }

        $dump = "<?php\n\nreturn ".$marshalledValue.";\n";
        $dump = str_replace(var_export(__FILE__, true), "\\dirname(__DIR__).\\DIRECTORY_SEPARATOR.'VarExporterTest.php'", $dump);

        $fixtureFile = __DIR__.'/Fixtures/'.$testName.'.php';

        if (\PHP_VERSION_ID < 80200 && 'datetime' === $testName) {
            $fixtureFile = __DIR__.'/Fixtures/'.$testName.'-legacy.php';
        }
        $this->assertStringEqualsFile($fixtureFile$dump);

        if ('incomplete-class' === $testName || 'external-references' === $testName) {
            return;
        }
        
//Already connected, generate error             $this->setError('Already connected to a server');

            return false;
        }
        if (empty($port)) {
            $port = self::DEFAULT_PORT;
        }
        //Connect to the SMTP server         $this->edebug(
            "Connection: opening to $host:$port, timeout=$timeout, options=" .
            (count($options) > 0 ? var_export($options, true) : 'array()'),
            self::DEBUG_CONNECTION
        );

        $this->smtp_conn = $this->getSMTPConnection($host$port$timeout$options);

        if ($this->smtp_conn === false) {
            //Error info already set inside `getSMTPConnection()`             return false;
        }

        $this->edebug('Connection: opened', self::DEBUG_CONNECTION);

        
public function renderHeader(Value $o): string
    {
        $output = [];

        if ($o->depth) {
            if (null !== ($s = $o->getModifiers())) {
                $output[] = $s;
            }

            if (null !== $o->name) {
                $output[] = $this->escape(\var_export($o->name, true));

                if (null !== ($s = $o->getOperator())) {
                    $output[] = $this->escape($s);
                }
            }
        }

        if (null !== ($s = $o->getType())) {
            if ($o->reference) {
                $s = '&'.$s;
            }

            
    // and returns "datetime_default".     $this->assertEquals('datetime_default', $this->plugin->transform([]$this->migrateExecutable, $this->row, 'property'));
  }

  /** * Tests an exception is thrown when the input is not a date field. * * @covers ::transform */
  public function testDefaultsException() {
    $this->expectException(MigrateException::class);
    $this->expectExceptionMessage(sprintf('Failed to lookup field type %s in the static map.', var_export([], TRUE)));
    $this->plugin->transform([]$this->migrateExecutable, $this->row, 'property');
  }

}
$parameter_string .= $type_name . ' ';
    }

    if ($parameter->isPassedByReference()) {
      $parameter_string .= '&';
    }

    $parameter_string .= '$' . $parameter->getName();

    if ($parameter->isDefaultValueAvailable()) {
      $parameter_string .= ' = ';
      $parameter_string .= var_export($parameter->getDefaultValue(), TRUE);
    }

    return $parameter_string;
  }

  /** * Builds the body of a wrapped method. * * @param \ReflectionMethod $reflection_method * A reflection method for the method. * * @return string */
Home | Imprint | This part of the site doesn't use cookies.