Esempio n. 1
0
 /**
  * @param mixed $var
  */
 function appendLog($var)
 {
     static $handler = null;
     if ($handler === null) {
         $logDir = LOG_DIR;
         assert(is_dir($logDir), 'log dir "' . $logDir . '" must be a dir');
         $logDir .= '/' . date('Ymd');
         if (!is_dir($logDir)) {
             $success = mkdir($logDir);
             assert($success, 'log dir create failed: ' . $logDir . ': ' . json_encode(error_get_last()));
         }
         $logFile = $logDir . '/' . GAME_VERSION;
         $cloner = new VarCloner();
         $dumper = new CliDumper($logFile);
         $handler = function ($var) use($cloner, $dumper) {
             $dumper->dump($cloner->cloneVar($var));
         };
     }
     $origHandler = VarDumper::setHandler($handler);
     VarDumper::dump(date('c'));
     foreach (func_get_args() as $var) {
         VarDumper::dump($var);
     }
     VarDumper::setHandler($origHandler);
 }
Esempio n. 2
0
File: Cli.php Progetto: nochso/diff
 /**
  * @param string $input
  *
  * @return mixed
  */
 public function escape($input)
 {
     $this->dumper->dump($this->cloner->cloneVar($input), $this->memoryStream);
     $output = stream_get_contents($this->memoryStream, -1, 0);
     ftruncate($this->memoryStream, 0);
     return rtrim($output, "\n");
 }
 /**
  * @param $variable
  * @return resource|string
  * @throws Exception
  * @throws null
  */
 protected function dump($variable)
 {
     $output = fopen('php://memory', 'r+b');
     $this->dumper->dump($this->cloner->cloneVar($variable), $output);
     rewind($output);
     $output = stream_get_contents($output);
     return $output;
 }
 /**
  * Describe a View Composer for logging.
  * @param View $view    View being created
  * @param mixed $viewComposer   View Composer
  * @return string
  */
 protected function describeViewComposer(View $view, $viewComposer)
 {
     $description = "View Composer called for view '{$view->name()}': ";
     $this->cliDumper->dump($this->varCloner->cloneVar($viewComposer), function ($line, $depth) use(&$description) {
         $description .= "{$line} ";
     });
     return $description;
 }
 public function boot(Application $app)
 {
     // This code is here to lazy load the dump stack. This default
     // configuration for CLI mode is overridden in HTTP mode on
     // 'kernel.request' event
     VarDumper::setHandler(function ($var) use($app) {
         $dumper = new CliDumper();
         $dumper->dump($app['var_dumper.cloner']->cloneVar($var));
     });
 }
 private function getVarDumperDump($data)
 {
     $h = fopen('php://memory', 'r+b');
     $cloner = new VarCloner();
     $dumper = new CliDumper($h);
     $dumper->setColors(false);
     $dumper->dump($cloner->cloneVar($data)->withRefHandles(false));
     $data = stream_get_contents($h, -1, 0);
     fclose($h);
     return rtrim($data);
 }
Esempio n. 7
0
 /**
  * {@inheritdoc}
  */
 public function format($response)
 {
     $temp = tmpfile();
     $cloner = new VarCloner();
     $dumper = new CliDumper($temp);
     $dumper->dump($cloner->cloneVar($response));
     fseek($temp, 0);
     $response = stream_get_contents($temp);
     fclose($temp);
     return $response;
 }
Esempio n. 8
0
 protected function getDump($data)
 {
     $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
     $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
     $h = fopen('php://memory', 'r+b');
     $cloner = new VarCloner();
     $cloner->setMaxItems(-1);
     $dumper = new CliDumper($h, null, $flags);
     $dumper->setColors(false);
     $dumper->dump($cloner->cloneVar($data)->withRefHandles(false));
     $data = stream_get_contents($h, -1, 0);
     fclose($h);
     return rtrim($data);
 }
Esempio n. 9
0
 /**
  * @param $data
  * @param null|int $flags
  */
 public function dump($data, $flags = null)
 {
     if ($flags !== null) {
         if ($flags & self::NEWLINE_BEFORE) {
             $this->output->writeln('');
         }
     }
     $this->cliDumper->dump($this->varCloner->cloneVar($data));
     if ($flags !== null) {
         if ($flags & self::NEWLINE_AFTER) {
             $this->output->writeln('');
         }
     }
 }
Esempio n. 10
0
 protected function getDump($data, $key = null)
 {
     $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
     $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
     $cloner = new VarCloner();
     $cloner->setMaxItems(-1);
     $dumper = new CliDumper(null, null, $flags);
     $dumper->setColors(false);
     $data = $cloner->cloneVar($data)->withRefHandles(false);
     if (null !== $key && null === ($data = $data->seek($key))) {
         return;
     }
     return rtrim($dumper->dump($data, true));
 }
Esempio n. 11
0
 /**
  * @param string          $targetUrl   target url to import resource into
  * @param string          $file        path to file being loaded
  * @param OutputInterface $output      output of the command
  * @param Document        $doc         document to load
  * @param string          $host        host to import into
  * @param string          $rewriteHost string to replace with value from $host during loading
  * @param string          $rewriteTo   string to replace value from $rewriteHost with during loading
  * @param boolean         $sync        send requests syncronously
  *
  * @return Promise\Promise|null
  */
 protected function importResource($targetUrl, $file, OutputInterface $output, Document $doc, $host, $rewriteHost, $rewriteTo, $sync = false)
 {
     $content = str_replace($rewriteHost, $rewriteTo, $doc->getContent());
     $successFunc = function (ResponseInterface $response) use($output) {
         $output->writeln('<comment>Wrote ' . $response->getHeader('Link')[0] . '</comment>');
     };
     $errFunc = function (RequestException $e) use($output, $file) {
         $output->writeln('<error>' . str_pad(sprintf('Failed to write <%s> from \'%s\' with message \'%s\'', $e->getRequest()->getUri(), $file, $e->getMessage()), 140, ' ') . '</error>');
         if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
             $this->dumper->dump($this->cloner->cloneVar($this->parser->parse($e->getResponse()->getBody(), false, false, true)), function ($line, $depth) use($output) {
                 if ($depth > 0) {
                     $output->writeln('<error>' . str_pad(str_repeat('  ', $depth) . $line, 140, ' ') . '</error>');
                 }
             });
         }
     };
     if ($sync === false) {
         $promise = $this->client->requestAsync('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)]);
         $promise->then($successFunc, $errFunc);
     } else {
         $promise = new Promise\Promise();
         try {
             $promise->resolve($successFunc($this->client->request('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)])));
         } catch (BadResponseException $e) {
             $promise->resolve($errFunc($e));
         }
     }
     return $promise;
 }
Esempio n. 12
0
 public function boot()
 {
     if ($this->container->getParameter('kernel.debug')) {
         $container = $this->container;
         // This code is here to lazy load the dump stack. This default
         // configuration for CLI mode is overridden in HTTP mode on
         // 'kernel.request' event
         VarDumper::setHandler(function ($var) use($container) {
             $dumper = new CliDumper();
             $cloner = $container->get('var_dumper.cloner');
             $handler = function ($var) use($dumper, $cloner) {
                 $dumper->dump($cloner->cloneVar($var));
             };
             VarDumper::setHandler($handler);
             $handler($var);
         });
     }
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  */
 protected function dumpLine($depth, $endOfValue = false)
 {
     if (-1 === $this->lastDepth && isset($_SERVER['REQUEST_TIME_FLOAT'])) {
         if ($this->colors) {
             echo sprintf("[%sm%s", $this->styles['ref'], $this->prefix());
         } else {
             echo $this->prefix();
         }
         echo "\n";
     }
     $this->lastDepth = $depth;
     parent::dumpLine($depth, $endOfValue);
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  */
 public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
 {
     $this->dumpEllipsis($cursor, $hasChild, $cut);
     if ($hasChild) {
         $this->line .= '</samp>';
     }
     parent::leaveHash($cursor, $type, $class, $hasChild, 0);
 }
Esempio n. 15
0
 public function __destruct()
 {
     if (0 === $this->clonesCount-- && !$this->isCollected && $this->data) {
         $this->clonesCount = 0;
         $this->isCollected = true;
         $h = headers_list();
         $i = count($h);
         array_unshift($h, 'Content-Type: ' . ini_get('default_mimetype'));
         while (0 !== stripos($h[$i], 'Content-Type:')) {
             --$i;
         }
         if ('cli' !== PHP_SAPI && stripos($h[$i], 'html')) {
             $dumper = new HtmlDumper('php://output', $this->charset);
         } else {
             $dumper = new CliDumper('php://output', $this->charset);
             $dumper->setColors(false);
         }
         foreach ($this->data as $i => $dump) {
             $this->data[$i] = null;
             if ($dumper instanceof HtmlDumper) {
                 $dump['name'] = $this->htmlEncode($dump['name']);
                 $dump['file'] = $this->htmlEncode($dump['file']);
                 if ('' !== $dump['file']) {
                     if ($this->fileLinkFormat) {
                         $link = strtr($this->fileLinkFormat, array('%f' => $dump['file'], '%l' => $dump['line']));
                         $dump['name'] = sprintf('<a href="%s" title="%s">%s</a>', $link, $dump['file'], $dump['name']);
                     } else {
                         $dump['name'] = sprintf('<abbr title="%s">%s</abbr>', $dump['file'], $dump['name']);
                     }
                 }
                 echo "\n<span class=\"sf-dump-meta\">{$dump['name']} on line {$dump['line']}:</span>";
             } else {
                 echo "{$dump['name']} on line {$dump['line']}:\n";
             }
             $dumper->dump($dump['data']);
         }
         $this->data = array();
         $this->dataCount = 0;
     }
 }
Esempio n. 16
0
    /**
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function testBuggyRefs()
    {
        if (PHP_VERSION_ID >= 50600) {
            $this->markTestSkipped('PHP 5.6 fixed refs counting');
        }
        $var = $this->getSpecialVars();
        $var = $var[0];
        $dumper = new CliDumper();
        $dumper->setColors(false);
        $cloner = new VarCloner();
        $data = $cloner->cloneVar($var)->withMaxDepth(3);
        $out = '';
        $dumper->dump($data, function ($line, $depth) use(&$out) {
            if ($depth >= 0) {
                $out .= str_repeat('  ', $depth) . $line . "\n";
            }
        });
        $this->assertSame(<<<EOTXT
array:1 [
  0 => array:1 [
    0 => array:1 [
      0 => array:1 [ …1]
    ]
  ]
]

EOTXT
, $out);
    }
 private function inlineData(array $extraction)
 {
     $dumper = new CliDumper();
     $inlined = array();
     foreach ($extraction as $k => $v) {
         if (is_array($v)) {
             $inlined[$k] = $this->inlineData($v);
         } elseif ($v instanceof Data) {
             $inlined[$k] = rtrim($dumper->dump($v->withRefHandles(false), true));
         } else {
             $inlined[$k] = $v;
         }
     }
     return $inlined;
 }
Esempio n. 18
0
 /**
  * Replaces the default output stream of Symfony's
  * CliDumper and HtmlDumper classes in order to
  * be able to run on Google App Engine.
  *
  * 'php://stdout' is used by CliDumper,
  * 'php://output' is used by HtmlDumper,
  * both are not supported on GAE.
  */
 protected function replaceDefaultSymfonyLineDumpers()
 {
     HtmlDumper::$defaultOutput = CliDumper::$defaultOutput = function ($line, $depth, $indentPad) {
         if (-1 !== $depth) {
             echo str_repeat($indentPad, $depth) . $line . PHP_EOL;
         }
     };
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  */
 public function __construct($output = null, $charset = null)
 {
     $this->setStyles(['default' => '38;5;208', 'num' => '1;38;5;38', 'const' => '1;38;5;88', 'str' => '1;38;5;68', 'note' => '38;5;126', 'ref' => '38;5;247', 'public' => '', 'protected' => '', 'private' => '', 'meta' => '38;5;170', 'key' => '38;5;35', 'index' => '38;5;35']);
     parent::__construct($output, $charset);
 }
Esempio n. 20
0
 /**
  * Dump a value with elegance.
  *
  * @param  mixed  $value
  *
  * @return void
  */
 public function dump($value)
 {
     $dumper = new CliDumper();
     $dumper->dump((new VarCloner())->cloneVar($value));
 }
Esempio n. 21
0
 private function execute($input)
 {
     $input = trim($input);
     if (empty($input)) {
         return;
     }
     $args = array_filter(explode(' ', $input));
     if (count($args) === 1 and array_key_exists($args[0], $this->currentLevel['content'])) {
         $this->execute("cd' {$args[0]}");
         return;
     }
     switch ($args[0]) {
         case 'ls':
             $this->output($this->ls());
             break;
         case 'cd':
             if (strpos($args[1], '/')) {
                 foreach (explode('/', $args[1]) as $arg) {
                     $this->execute("cd {$arg}");
                 }
                 break;
             }
             $item = str_replace('/', '', $args[1]);
             if ($item === '..') {
                 array_pop($this->levels);
                 $this->currentLevel = $this->parent();
                 break;
             } elseif ($item === '/') {
                 $this->levels = [$this->commands['content']['name']];
                 $this->currentLevel = $this->commands;
                 break;
             } elseif (array_key_exists($item, $this->currentLevel['content'])) {
                 array_push($this->levels, $item);
                 $this->currentLevel = $this->currentLevel['content'][$item];
                 break;
             } elseif ($item === '.') {
                 break;
             } else {
                 $this->output("Error: {$item} not found.\n");
                 break;
             }
         case 'exec':
             if (!isset($args[1])) {
                 $this->output("'exec' requires current element to be a command. Select one by 'cd'\n");
                 return;
             }
             $method = new \ReflectionMethod($this->levels[count($this->levels) - 2], $this->currentLevel['name']);
             $cmd = $method->invokeArgs(null, array_slice($args, 1));
             $this->client->send($cmd);
             $cloner = new VarCloner();
             $dumper = new CliDumper();
             $dumper->dump($cloner->cloneVar($this->client->getResponse()));
             break;
         case '?':
             $this->output("======== Available commands ========\n");
             $this->output(" - ls       : List available objects\n");
             $this->output(" - cd       : Change current directory ('cd ..' works)\n");
             $this->output(" - exec     : Execute current command eg: exec param1 param2 param3\n");
             $this->output(" - history  : Show command history\n");
             $this->output(" - quit     : Show command history\n");
             $this->output(" - ?        : Show this menu.....\n");
             break;
         case 'history':
             $this->output('  * ' . implode("\n  * ", array_values($this->history)) . "\n");
             break;
         case '':
             $this->prompt();
             break;
         case 'q':
         case 'quit':
             $this->client->logout();
             exit(0);
             break;
         default:
             $this->output("Error: Command not found for '{$input}'\n");
             $this->execute('?');
             $this->prompt();
     }
 }
Esempio n. 22
0
 /**
  *
  * {@inheritdoc}
  *
  */
 protected function dumpLine($depth, $endOfValue = false)
 {
     if ($endOfValue && 0 < $depth) {
         $this->line .= ',';
     }
     $this->line = $this->formatter->format($this->line);
     parent::dumpLine($depth, $endOfValue);
 }
Esempio n. 23
0
 /**
  * Assert status code, and on failure print the output to assist debugging.
  * @param int $code
  */
 public function assertResponseStatusWithDebug($code)
 {
     try {
         $actual = $this->response->getStatusCode();
         return $this->assertEquals($code, $actual, "Expected status code {$code}, got {$actual}.");
     } catch (\PHPUnit_Framework_ExpectationFailedException $e) {
         $content = $this->response->getContent();
         $json = json_decode($content);
         //check to see if the response was valid json, if so assign the object to $content
         if (json_last_error() === JSON_ERROR_NONE) {
             $content = $json;
         }
         $originalDefaultOutput = CliDumper::$defaultOutput;
         CliDumper::$defaultOutput = 'php://output';
         $dumper = new CliDumper();
         $dumper->dump((new VarCloner())->cloneVar($content));
         CliDumper::$defaultOutput = $originalDefaultOutput;
         throw $e;
     }
 }
Esempio n. 24
0
    /**
     * {@inheritdoc}
     */
    protected function dumpLine($depth)
    {
        if (-1 === $this->lastDepth) {
            $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
        }
        if (!$this->headerIsDumped) {
            $this->line = $this->getDumpHeader().$this->line;
        }

        if (-1 === $depth) {
            $this->line .= sprintf($this->dumpSuffix, $this->dumpId);
        }
        $this->lastDepth = $depth;

        // Replaces non-ASCII UTF-8 chars by numeric HTML entities
        $this->line = preg_replace_callback(
            '/[\x80-\xFF]+/',
            function ($m) {
                $m = unpack('C*', $m[0]);
                $i = 1;
                $entities = '';

                while (isset($m[$i])) {
                    if (0xF0 <= $m[$i]) {
                        $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80;
                    } elseif (0xE0 <= $m[$i]) {
                        $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++]  - 0x80;
                    } else {
                        $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80;
                    }

                    $entities .= '&#'.$c.';';
                }

                return $entities;
            },
            $this->line
        );

        if (-1 === $depth) {
            parent::dumpLine(0);
        }
        parent::dumpLine($depth);
    }
Esempio n. 25
0
 private function assertDumpEquals($dump, $data, $message = '')
 {
     $dumper = new CliDumper();
     $dumper->setColors(false);
     $this->assertSame(rtrim($dump), rtrim($dumper->dump($data, true)), $message);
 }
Esempio n. 26
0
 /**
  * Returns a string representation of the variable.
  *
  * Symfony VarDumper is used if installed, else print_r is used.
  *
  * @param mixed $var
  *
  * @return string
  */
 protected function dumpVar($var)
 {
     if (!class_exists('\\Symfony\\Component\\VarDumper\\VarDumper')) {
         return print_r($var, true);
     }
     $data = $this->getCloner()->cloneVar($var);
     $res = fopen('php://temp', 'r+');
     $dumper = new CliDumper($res);
     $dumper->setColors($this->output->isDecorated());
     $dumper->dump($data);
     $str = stream_get_contents($res, -1, 0);
     fclose($res);
     return $str;
 }
Esempio n. 27
0
 function dump($var)
 {
     $this->__dumper->dump($var);
 }
Esempio n. 28
0
    public function testGet()
    {
        require __DIR__ . '/Fixtures/dumb-var.php';
        $dumper = new CliDumper('php://output');
        $dumper->setColors(false);
        $cloner = new VarCloner();
        $cloner->addCasters(array(':stream' => function ($res, $a) {
            unset($a['uri']);
            return $a;
        }));
        $data = $cloner->cloneVar($var);
        ob_start();
        $dumper->dump($data);
        $out = ob_get_clean();
        $closureLabel = PHP_VERSION_ID >= 50400 ? 'public method' : 'function';
        $out = preg_replace('/[ \\t]+$/m', '', $out);
        $intMax = PHP_INT_MAX;
        $res1 = (int) $var['res'];
        $res2 = (int) $var[8];
        $this->assertStringMatchesFormat(<<<EOTXT
array:25 [
  "number" => 1
  0 => &1 null
  "const" => 1.1
  1 => true
  2 => false
  3 => NAN
  4 => INF
  5 => -INF
  6 => {$intMax}
  "str" => "déjà"
  7 => b"é@"
  "[]" => []
  "res" => :stream {@{$res1}
    wrapper_type: "plainfile"
    stream_type: "STDIO"
    mode: "r"
    unread_bytes: 0
    seekable: true
    timed_out: false
    blocked: true
    eof: false
    options: []
  }
  8 => :Unknown {@{$res2}}
  "obj" => Symfony\\Component\\VarDumper\\Tests\\Fixture\\DumbFoo {#%d
    +foo: "foo"
    +"bar": "bar"
  }
  "closure" => Closure {#%d
    reflection: """
      Closure [ <user> {$closureLabel} Symfony\\Component\\VarDumper\\Tests\\Fixture\\{closure} ] {
        @@ {$var['file']} {$var['line']} - {$var['line']}

        - Parameters [2] {
          Parameter #0 [ <required> \$a ]
          Parameter #1 [ <optional> PDO or NULL &\$b = NULL ]
        }
      }
      """
  }
  "line" => {$var['line']}
  "nobj" => array:1 [
    0 => &3 {#%d}
  ]
  "recurs" => &4 array:1 [
    0 => &4 array:1 [&4]
  ]
  9 => &1 null
  "sobj" => Symfony\\Component\\VarDumper\\Tests\\Fixture\\DumbFoo {#%d}
  "snobj" => &3 {#%d}
  "snobj2" => {#%d}
  "file" => "{$var['file']}"
  b"bin-key-é" => ""
]

EOTXT
, $out);
    }