Esempio n. 1
0
 /**
  * It should provide a duplicate version of itself.
  */
 public function testDuplicate()
 {
     $this->document->loadXml($this->getXml());
     $duplicate = $this->document->duplicate();
     $this->assertNotsame($this->document, $duplicate);
     $this->assertNotsame($this->document->firstChild, $duplicate->firstChild);
     $this->assertNotsame($this->document->firstChild->firstChild, $duplicate->firstChild->firstChild);
 }
Esempio n. 2
0
 public function getReportsDocument()
 {
     $reportsDocument = new Document();
     $reportsEl = $reportsDocument->createRoot('reports');
     $reportsEl->appendElement('report');
     $reportsEl->appendElement('report');
     return $reportsDocument;
 }
Esempio n. 3
0
 public function createResult($benchmark = null, $extraCmd = '')
 {
     $benchmark = $benchmark ?: 'benchmarks/set4';
     $process = $this->phpbench('run ' . $benchmark . ' --executor=debug --dump-file=' . $this->fname . ' ' . $extraCmd);
     if ($process->getExitCode() !== 0) {
         throw new \Exception('Could not generate test data:' . $process->getErrorOutput() . $process->getOutput());
     }
     $document = new Document();
     $document->load($this->fname);
     return $document;
 }
Esempio n. 4
0
    public function generate(SuiteDocument $results, Config $config)
    {
        $document = new Document();
        $reportEl = $document->createRoot('reports');
        $reportEl->setAttribute('name', $config->getName());
        $reportEl = $reportEl->appendElement('report');
        $descriptionEl = $reportEl->appendElement('description');
        $descriptionEl->nodeValue = <<<EOT
Warning: The histogram report is experimental, it may change or be removed without warning in
future versions of PHPBench.
EOT;
        $tableEl = $reportEl->appendElement('table');
        foreach ($results->query('//subject') as $subjectEl) {
            foreach ($subjectEl->query('.//variant') as $variantEl) {
                $times = array();
                foreach ($variantEl->query('.//iteration') as $iterationEl) {
                    $times[] = $iterationEl->getAttribute('rev-time');
                }
                if (count($times) > 1) {
                    $histogram = Statistics::histogram($times, $config['bins']);
                    $kde = new Kde($times);
                    $kdeX = Statistics::linspace(min($times), max($times), $config['bins'] + 1);
                    $kdeY = $kde->evaluate($kdeX);
                } else {
                    $histogram = array((string) current($times) => 1);
                    $kdeY = array(null);
                }
                $counter = 0;
                foreach ($histogram as $xValue => $frequency) {
                    $kdeVal = $kdeY[$counter++];
                    $rowEl = $tableEl->appendElement('row');
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'benchmark');
                    $cellEl->nodeValue = functions\class_name($subjectEl->evaluate('string(ancestor::benchmark/@class)'));
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'subject');
                    $cellEl->nodeValue = $subjectEl->evaluate('string(./@name)');
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'index');
                    $cellEl->nodeValue = $counter;
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'time');
                    $cellEl->nodeValue = $xValue;
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'freq');
                    $cellEl->nodeValue = $frequency;
                    $cellEl = $rowEl->appendElement('cell');
                    $cellEl->setAttribute('name', 'kde');
                    $cellEl->nodeValue = $kdeVal;
                }
            }
        }
        return $document;
    }
Esempio n. 5
0
 /**
  * {@inheritdoc}
  */
 public function fetch($runId)
 {
     if (!$this->has($runId)) {
         throw new \InvalidArgumentException(sprintf('Cannot find run with UUID "%s"', $runId));
     }
     $path = $this->getPath($runId);
     $dom = new Document();
     $dom->load($path);
     $collection = $this->xmlDecoder->decode($dom);
     return $collection;
 }
Esempio n. 6
0
 /**
  * {@inheritdoc}
  */
 public function generate(SuiteDocument $result, array $config)
 {
     $reportDoms = $this->reportManager->generateReports($result, $config['reports']);
     $compositeDom = new Document();
     $compositeEl = $compositeDom->createRoot('reports');
     foreach ($reportDoms as $reportsDom) {
         foreach ($reportsDom->xpath()->query('./report') as $reportDom) {
             $reportEl = $compositeDom->importNode($reportDom, true);
             $compositeEl->appendChild($reportEl);
         }
     }
     return $compositeDom;
 }
Esempio n. 7
0
 /**
  * {@inheritdoc}
  */
 public function generate(SuiteCollection $collection, Config $config)
 {
     $reportDoms = $this->reportManager->generateReports($collection, $config['reports']);
     $compositeDom = new Document();
     $compositeEl = $compositeDom->createRoot('reports');
     $compositeEl->setAttribute('name', $config->getName());
     foreach ($reportDoms as $reportsDom) {
         foreach ($reportsDom->xpath()->query('./report') as $reportDom) {
             $reportEl = $compositeDom->importNode($reportDom, true);
             $compositeEl->appendChild($reportEl);
         }
     }
     return $compositeDom;
 }
Esempio n. 8
0
 /**
  * Return a SuiteCollection from a number of PHPBench xml files.
  *
  * @param string[] $files
  *
  * @return SuiteCollection
  */
 public function decodeFiles(array $files)
 {
     // combine into one document.
     //
     $suiteDocument = new Document('phpbench');
     $rootEl = $suiteDocument->createRoot('phpbench');
     foreach ($files as $file) {
         $fileDom = new Document();
         $fileDom->load($file);
         foreach ($fileDom->query('./suite') as $suiteEl) {
             $importedEl = $suiteDocument->importNode($suiteEl, true);
             $rootEl->appendChild($importedEl);
         }
     }
     return $this->decode($suiteDocument);
 }
Esempio n. 9
0
    private function getDocument()
    {
        $xml = <<<EOT
<?xml version="1.0"?>
<document>
    <article id="1">
        <title>Morning</title>
    </article>
    <article id="2">
        <title>Afternoon</title>
    </article>
</document>
EOT;
        $document = new Document();
        $document->loadXml($xml);
        return $document;
    }
 protected function doGenerate($definition, SuiteDocument $document, Config $config, array $parameters = array())
 {
     if ($config['debug']) {
         $this->output->writeln('<info>Suite XML</info>');
         $this->output->writeln($document->saveXML());
     }
     $definition = $this->definitionLoader->load($definition, $document);
     if (isset($config['pretty_params']) && true === $config['pretty_params']) {
         $definition['classes']['params'] = array(array('json_format', array()));
     }
     if (array_key_exists('formatting', $config) && $config['formatting'] === false) {
         foreach ($definition['classes'] as &$class) {
             $class = array();
         }
     }
     $tableDom = $this->tabular->tabulate($document, $definition, $parameters);
     if ($config['exclude']) {
         foreach ($config['exclude'] as $cellName) {
             $excludeCells = $tableDom->xpath()->query(sprintf('//cell[@name="%s"]', $cellName));
             foreach ($excludeCells as $excludeCell) {
                 $excludeCell->parentNode->removeChild($excludeCell);
             }
         }
     }
     $reportDom = new Document();
     $reportEl = $reportDom->createRoot('reports');
     $reportEl->setAttribute('name', $config->getName());
     $reportEl = $reportEl->appendElement('report');
     if ($config['debug']) {
         $tableDom->formatOutput = true;
         $this->output->writeln('<info>Table XML</info>');
         $this->output->writeln($tableDom->saveXML());
     }
     if ($config['title']) {
         $reportEl->setAttribute('title', $config['title']);
     }
     if ($config['description']) {
         $reportEl->appendElement('description', $config['description']);
     }
     $tableEl = $reportEl->ownerDocument->importNode($tableDom->firstChild, true);
     $reportEl->appendChild($tableEl);
     return $reportEl->ownerDocument;
 }
Esempio n. 11
0
 private function createEntry($uuid, \DateTime $date)
 {
     $dom = new Document();
     $test = $dom->createRoot('test');
     $test->setAttribute('uuid', $uuid);
     $path = Workspace::getWorkspacePath() . $date->format('/Y/m/d/') . '/' . $uuid . '.xml';
     if (!$this->filesystem->exists(dirname($path))) {
         $this->filesystem->mkdir(dirname($path));
     }
     $dom->save($path);
     return $this->createCollection($uuid, $date);
 }
Esempio n. 12
0
 /**
  * Render the table.
  *
  * @param mixed $tableDom
  * @param mixed $config
  */
 public function render(Document $reportDom, Config $config)
 {
     $template = $config['template'];
     $out = strtr($config['file'], ['%report_name%' => $reportDom->firstChild->getAttribute('name')]);
     if (!file_exists($template)) {
         throw new \RuntimeException(sprintf('XSLT template file "%s" does not exist', $template));
     }
     foreach ($reportDom->query('.//row') as $rowEl) {
         $formatterParams = [];
         foreach ($rowEl->query('./formatter-param') as $paramEl) {
             $formatterParams[$paramEl->getAttribute('name')] = $paramEl->nodeValue;
         }
         foreach ($rowEl->query('./cell') as $cellEl) {
             $value = $cellEl->nodeValue;
             if ('' !== $value && $cellEl->hasAttribute('class')) {
                 $classes = explode(' ', $cellEl->getAttribute('class'));
                 $value = $this->formatter->applyClasses($classes, $value, $formatterParams);
                 $cellEl->nodeValue = $value;
             }
         }
     }
     $stylesheetDom = new \DOMDocument('1.0');
     $stylesheetDom->load($template);
     $xsltProcessor = new \XsltProcessor();
     $xsltProcessor->importStylesheet($stylesheetDom);
     $xsltProcessor->setParameter(null, 'title', $config['title']);
     $xsltProcessor->setParameter(null, 'phpbench-version', PhpBench::VERSION);
     $xsltProcessor->setParameter(null, 'date', date('Y-m-d H:i:s'));
     $output = $xsltProcessor->transformToXml($reportDom);
     if (!$output) {
         throw new \InvalidArgumentException(sprintf('Could not render report with XSL file "%s"', $template));
     }
     if ($out) {
         file_put_contents($out, $output);
         $this->output->writeln('Dumped XSLT report:');
         $this->output->writeln($out);
     } else {
         $this->output->write($output);
     }
 }
Esempio n. 13
0
    public function getReportsDocument()
    {
        $document = new Document();
        $report = <<<EOT
<?xml version="1.0"?>
<reports>
    <report title="Report Title">
        <description>Report Description</description>
        <table>
            <group name="body">
                <row>
                    <cell name="one">Hello</cell>
                    <cell name="two">Goodbye</cell>
                </row>
            </group>
        </table>
    </report>
</reports>
EOT;
        $document->loadXml($report);
        return $document;
    }
Esempio n. 14
0
 public function setUp()
 {
     Workspace::initWorkspace();
     $this->archivePath = Workspace::getWorkspacePath();
     // create some files
     $dom = new Document();
     $dom->createRoot('hello');
     $dom->save($this->archivePath . '/' . '1.xml');
     $dom->save($this->archivePath . '/' . '2.txt');
     $dom->save($this->archivePath . '/' . '2.xml');
     $this->registry = $this->prophesize(Registry::class);
     $this->xmlEncoder = $this->prophesize(XmlEncoder::class);
     $this->xmlDecoder = $this->prophesize(XmlDecoder::class);
     $this->filesystem = $this->prophesize(Filesystem::class);
     $this->archiver = new XmlArchiver($this->registry->reveal(), $this->xmlEncoder->reveal(), $this->xmlDecoder->reveal(), $this->archivePath, $this->filesystem->reveal());
     $this->historyEntry = $this->prophesize(HistoryEntry::class);
     $this->output = new BufferedOutput();
     $this->storage = $this->prophesize(DriverInterface::class);
     $this->document = $this->prophesize(Document::class);
     $this->collection = $this->prophesize(SuiteCollection::class);
     $this->collection2 = $this->prophesize(SuiteCollection::class);
     $this->registry->getService()->willReturn($this->storage->reveal());
 }
Esempio n. 15
0
 /**
  * {@inheritdoc}
  */
 public function generate(SuiteCollection $suiteCollection, Config $config)
 {
     $document = new Document();
     $reportsEl = $document->createRoot('reports');
     $reportsEl->setAttribute('name', 'table');
     $reportEl = $reportsEl->appendElement('report');
     if (isset($config['title'])) {
         $reportEl->setAttribute('title', $config['title']);
     }
     if (isset($config['description'])) {
         $reportEl->appendElement('description', $config['description']);
     }
     foreach ($suiteCollection as $suite) {
         $tableEl = $reportEl->appendElement('table');
         $colsEl = $tableEl->appendElement('cols');
         foreach (['provider', 'key', 'value'] as $colName) {
             $col = $colsEl->appendElement('col');
             $col->setAttribute('name', $colName);
             $col->setAttribute('label', $colName);
         }
         $tableEl->setAttribute('title', sprintf('Suite #%s %s', $suite->getUuid(), $suite->getDate()->format('Y-m-d H:i:s')));
         $groupEl = $tableEl->appendElement('group');
         $groupEl->setAttribute('name', 'body');
         foreach ($suite->getEnvInformations() as $envInformation) {
             foreach ($envInformation as $key => $value) {
                 $rowEl = $groupEl->appendElement('row');
                 $cellEl = $rowEl->appendElement('cell', $envInformation->getName());
                 $cellEl->setAttribute('name', 'provider');
                 $cellEl = $rowEl->appendElement('cell', $key);
                 $cellEl->setAttribute('name', 'key');
                 $cellEl = $rowEl->appendElement('cell', is_bool($value) ? $value ? 'yes' : 'no' : $value);
                 $cellEl->setAttribute('name', 'value');
             }
         }
     }
     return $document;
 }
Esempio n. 16
0
 /**
  * Encode a Suite object into a XML document.
  *
  * @param SuiteCollection $suiteCollection
  *
  * @return Document
  */
 public function encode(SuiteCollection $suiteCollection)
 {
     $dom = new Document();
     $rootEl = $dom->createRoot('phpbench');
     $rootEl->setAttribute('version', PhpBench::VERSION);
     foreach ($suiteCollection->getSuites() as $suite) {
         $suiteEl = $rootEl->appendElement('suite');
         $suiteEl->setAttribute('context', $suite->getContextName());
         $suiteEl->setAttribute('date', $suite->getDate()->format('Y-m-d H:i:s'));
         $suiteEl->setAttribute('config-path', $suite->getConfigPath());
         $suiteEl->setAttribute('uuid', $suite->getUuid());
         $envEl = $suiteEl->appendElement('env');
         foreach ($suite->getEnvInformations() as $information) {
             $infoEl = $envEl->appendElement($information->getName());
             foreach ($information as $key => $value) {
                 $infoEl->setAttribute($key, $value);
             }
         }
         foreach ($suite->getBenchmarks() as $benchmark) {
             $this->processBenchmark($benchmark, $suiteEl);
         }
     }
     return $dom;
 }
Esempio n. 17
0
 public function render(Document $reportsDocument, array $config)
 {
     $this->output->writeln('Report XML (debug):');
     $this->output->writeln($reportsDocument->saveXml());
 }
Esempio n. 18
0
 /**
  * {@inheritdoc}
  */
 public function restore(OutputInterface $output)
 {
     $driver = $this->storageRegistry->getService();
     $iterator = new \DirectoryIterator($this->archivePath);
     $files = $this->filterFiles($iterator);
     $totalCount = count($files);
     $files = $this->filterExisting($driver, $files);
     $count = count($files);
     $output->writeln(sprintf('Restoring %s of %s suites.', $count, $totalCount));
     foreach ($files as $index => $file) {
         $this->writeProgress($output, $index, $count, '.');
         $document = new Document();
         $document->load($file->getPathname());
         $collection = $this->xmlDecoder->decode($document);
         $driver->store($collection);
     }
     $output->write(PHP_EOL);
 }
Esempio n. 19
0
 protected function assertXPathEvaluation(Document $dom, $expected, $expr)
 {
     $result = $dom->evaluate($expr);
     $this->assertEquals($expected, $result, $expr);
 }
Esempio n. 20
0
 public function convert($path)
 {
     $dom = new Document(1.0);
     $traceEl = $dom->createRoot('trace');
     $handle = fopen($path, 'r');
     $version = fgets($handle);
     if (!preg_match('/^Version: (.*)$/', $version, $matches)) {
         throw new \InvalidArgumentException(sprintf('Expected "Version" in trace "%s"', $path));
     }
     $version = $matches[1];
     $traceEl->setAttribute('version', $matches[1]);
     $format = fgets($handle);
     if (!preg_match('/^File format: (.*)$/', $format, $matches)) {
         throw new \InvalidArgumentException(sprintf('Expected "File format" in trace "%s"', $path));
     }
     $traceEl->setAttribute('format', $matches[1]);
     $start = fgets($handle);
     if (!preg_match('/^TRACE START \\[(.*)\\]$/', $start, $matches)) {
         throw new \InvalidArgumentException(sprintf('Expected "TRACE START" in "%s"', $path));
     }
     $traceEl->setAttribute('start', $matches[1]);
     $scopeEl = $traceEl;
     $tree = [];
     $lineNb = 3;
     $buffer = null;
     while ($line = fgets($handle)) {
         $lineNb++;
         if (preg_match('/TRACE END\\s+\\[(.*)\\]/', $line, $matches)) {
             $scopeEl->setAttribute('end-time', $last[3]);
             $scopeEl->setAttribute('end-memory', trim($last[4]));
             $scopeEl->setAttribute('end', $matches[1]);
             break;
         }
         $parts = explode("\t", $line);
         $level = $parts[0];
         // '0' is entry, '1' is exit, 'R' is return
         if (isset($parts[2]) && $parts[2] == '1') {
             $scopeEl = $tree[$level];
             $scopeEl->setAttribute('end-time', $parts[3]);
             $scopeEl->setAttribute('end-memory', trim($parts[4]));
             $scopeEl = $scopeEl->parentNode;
             continue;
         } elseif (isset($parts[2]) && $parts[2] == 'R') {
             $scopeEl = $tree[$level];
             $scopeEl = $scopeEl->parentNode;
             continue;
         } elseif (isset($parts[2]) && $parts[2] == '') {
             $last = $parts;
             continue;
         }
         if (count($parts) < 9) {
             throw new \InvalidArgumentException(sprintf('Expected at least 9 fields, got "%s" in "%s:%s"', count($parts), $path, $lineNb));
         }
         $entryEl = $scopeEl->appendElement('entry');
         $entryEl->setAttribute('level', $parts[0]);
         $entryEl->setAttribute('func_nb', $parts[1]);
         $entryEl->setAttribute('start-time', $parts[3]);
         $entryEl->setAttribute('start-memory', $parts[4]);
         $entryEl->setAttribute('function', $parts[5]);
         $entryEl->setAttribute('is_user', $parts[6]);
         $entryEl->setAttribute('include', $parts[7]);
         $entryEl->setAttribute('filename', $parts[8]);
         $entryEl->setAttribute('line', $parts[9]);
         // parse number of parameters if set.
         if (isset($parts[10])) {
             $entryEl->setAttribute('nb_params', $parts[10]);
         }
         // parse arguments
         $i = 11;
         while (isset($parts[$i])) {
             $argEl = $entryEl->appendElement('arg');
             $argEl->nodeValue = html_entity_decode($parts[$i]);
             $i++;
         }
         $tree[$level] = $entryEl;
         $scopeEl = $entryEl;
     }
     return $dom;
 }
Esempio n. 21
0
 protected function assertXPathEval(Document $document, $expected, $expression)
 {
     $result = $document->evaluate($expression);
     $this->assertEquals($expected, $result);
 }
Esempio n. 22
0
 /**
  * Generate the report DOM document to pass to the report renderer.
  *
  * @param array $tables
  * @param Config $config
  *
  * @return Document
  */
 private function generateDocument(array $tables, Config $config)
 {
     $document = new Document();
     $reportsEl = $document->createRoot('reports');
     $reportsEl->setAttribute('name', 'table');
     $reportEl = $reportsEl->appendElement('report');
     $classMap = array_merge($this->classMap, $config['class_map']);
     if (isset($config['title'])) {
         $reportEl->setAttribute('title', $config['title']);
     }
     if (isset($config['description'])) {
         $reportEl->appendElement('description', $config['description']);
     }
     foreach ($tables as $breakHash => $table) {
         $tableEl = $reportEl->appendElement('table');
         // Build the col(umn) definitions.
         foreach ($table as $row) {
             $colsEl = $tableEl->appendElement('cols');
             foreach ($row->getNames() as $cellIndex => $colName) {
                 $colEl = $colsEl->appendElement('col');
                 $colEl->setAttribute('name', $colName);
                 // column labels are the column names by default.
                 // the user may override by column name or column index.
                 $colLabel = $colName;
                 if (isset($config['labels'][$colName])) {
                     $colLabel = $config['labels'][$colName];
                 } elseif (isset($config['labels'][$cellIndex])) {
                     $colLabel = $config['labels'][$cellIndex];
                 }
                 $colEl->setAttribute('label', $colLabel);
             }
             break;
         }
         if ($breakHash) {
             $tableEl->setAttribute('title', $breakHash);
         }
         $groupEl = $tableEl->appendElement('group');
         $groupEl->setAttribute('name', 'body');
         foreach ($table as $row) {
             $rowEl = $groupEl->appendElement('row');
             // apply formatter options
             foreach ($row->getFormatParams() as $paramName => $paramValue) {
                 $paramEl = $rowEl->appendElement('formatter-param', $paramValue);
                 $paramEl->setAttribute('name', $paramName);
             }
             foreach ($row as $key => $value) {
                 $cellEl = $rowEl->appendElement('cell', $value);
                 $cellEl->setAttribute('name', $key);
                 if (isset($classMap[$key])) {
                     $cellEl->setAttribute('class', implode(' ', $classMap[$key]));
                 }
             }
         }
     }
     return $document;
 }
Esempio n. 23
0
 public function render(Document $reportsDocument, Config $config)
 {
     $this->output->writeln('Report XML (debug):');
     $this->output->writeln($reportsDocument->dump());
 }
Esempio n. 24
0
    /**
     * It should throw an exception if an attribute name has no - prefix.
     *
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Expected attribute name to have a result key prefix, got "foo"
     */
    public function testInvalidAttribute()
    {
        $dom = new Document(1.0);
        $dom->loadXml(<<<EOT
<phpbench>
  <suite>
      <benchmark class="\\PhpBench\\Micro\\Math\\KdeBench">
      <subject name="benchKde">
        <variant>
          <iteration foo="12" />
        </variant>
      </subject>
      </benchmark>
  </suite>
</phpbench>
EOT
);
        $decoder = new XmlDecoder();
        $collection = $decoder->decode($dom);
    }
Esempio n. 25
0
 /**
  * Hydrate and return the history entry for the given path.
  *
  * The summary *should* used pre-calculated values from the XML
  * therefore reducing the normal overhead, however this code
  * is still quite expensive as we are creating the entire object
  * graph for each suite run.
  *
  * @param string $path
  *
  * @return HistoryEntry
  */
 private function getHistoryEntry($path)
 {
     $dom = new Document();
     $dom->load($path);
     $collection = $this->xmlDecoder->decode($dom);
     $suites = $collection->getSuites();
     $suite = reset($suites);
     $envInformations = $suite->getEnvInformations();
     $vcsBranch = null;
     if (isset($envInformations['vcs']['branch'])) {
         $vcsBranch = $envInformations['vcs']['branch'];
     }
     $summary = $suite->getSummary();
     $entry = new HistoryEntry($suite->getUuid(), $suite->getDate(), $suite->getContextName(), $vcsBranch, $summary->getNbSubjects(), $summary->getNbIterations(), $summary->getNbRevolutions(), $summary->getMinTime(), $summary->getMaxTime(), $summary->getMeanTime(), $summary->getMeanRelStDev(), $summary->getTotalTime());
     return $entry;
 }
Esempio n. 26
0
 /**
  * It should expand items from an expression when a source document is given.
  */
 public function testColumnNamesItems()
 {
     $dom = new Document();
     $dom->load(__DIR__ . '/files/articles.xml');
     $definition = $this->loader->load(array('rows' => array(array('cells' => array(array('name' => '{{ cell.item }}', 'literal' => 'bar', 'with_items' => array('selector' => '//article', 'value' => 'string(./@name)')))))), $dom);
     $this->assertEquals(array('one', 'two', 'three'), $definition->getColumnNames());
 }