/**
  * Prints a result set from PHPDCD_Detector::detectDeadCode().
  *
  * @param array  $result
  * @param string $commonPath
  */
 public function printResult(array $result, $commonPath)
 {
     foreach ($result as $name => $source) {
         printf("\n  - %s()\n    declared in %s:%d\n", $name, str_replace($commonPath, '', $source['file']), $source['line']);
     }
     print "\n" . PHP_Timer::resourceUsage() . "\n";
 }
 public function run(\PHPUnit_Framework_TestResult $result = null)
 {
     if (!$result) {
         $result = new \PHPUnit_Framework_TestResult();
     }
     $opt = null;
     \PHP_Timer::start();
     $result->startTest($this);
     try {
         $opt = \Docopt::handle($this->doc, array('argv' => $this->argv, 'exit' => false));
     } catch (\Exception $ex) {
         // gulp
     }
     $found = null;
     if ($opt) {
         if (!$opt->success) {
             $found = array('user-error');
         } elseif (empty($opt->args)) {
             $found = array();
         } else {
             $found = $opt->args;
         }
     }
     $time = \PHP_Timer::stop();
     try {
         \PHPUnit_Framework_Assert::assertEquals($this->expect, $found);
     } catch (\PHPUnit_Framework_AssertionFailedError $e) {
         $result->addFailure($this, $e, $time);
     }
     $result->endTest($this, $time);
     return $result;
 }
Beispiel #3
0
 public function run(\PHPUnit_Framework_TestResult $result = null)
 {
     if (!$result) {
         $result = new \PHPUnit_Framework_TestResult();
     }
     $reader = new \Fulfil\Test\SpecTest\Reader();
     $tests = $reader->read($testFile);
     foreach ($tests as $test) {
         foreach ($test->data as $case) {
             \PHP_Timer::start();
             $result->startTest($this);
             try {
                 $ctx = new \Fulfil\Context();
                 $test->test->apply($case->in, $ctx);
                 $flat = $ctx->flatten();
             } catch (\Exception $ex) {
                 // yum
             }
             $time = \PHP_Timer::stop();
             try {
                 \PHPUnit_Framework_Assert::assertEquals($case->valid, $flat->valid);
             } catch (\PHPUnit_Framework_AssertionFailedError $e) {
                 $result->addFailure($this, $e, $time);
             }
             $result->endTest($this, $time);
         }
     }
     return $result;
 }
Beispiel #4
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if (\App::environment() === 'production') {
         $this->error('This feature is not available on this server');
     }
     $command = base_path('vendor' . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . 'apigen') . ' generate -s app  -d  phpdoc';
     $this->comment($command);
     $process = new Process($command);
     $process->run(function ($type, $buffer) {
         $buffer = trim($buffer);
         if (empty($buffer)) {
             return;
         }
         if ('err' === $type) {
             $this->error($buffer);
         } else {
             $this->comment($buffer);
         }
     });
     if (!$process->isSuccessful()) {
         $this->error($process->getErrorOutput());
         return;
     }
     $this->comment('Documentation generated in folder ' . base_path('phpdoc'));
     $this->comment(\PHP_Timer::resourceUsage());
 }
 protected function printFooter(PHPUnit_Framework_TestResult $result)
 {
     $this->write('<div class="stats">');
     parent::printFooter($result);
     $this->write('</div>');
     $this->write('<div class="resourceUsage">');
     $this->write(PHP_Timer::resourceUsage());
     $this->write('</div>');
 }
Beispiel #6
0
 public function twigRender($template, $output = [])
 {
     $output['resources'] = \PHP_Timer::resourceUsage();
     $fullPath = $this->templatePath . $template;
     $templateFile = strrchr($fullPath, DS);
     $loader = new \Twig_Loader_Filesystem(str_replace($templateFile, '', $fullPath));
     $twig = new \Twig_Environment($loader);
     return $twig->render($templateFile, $output);
 }
Beispiel #7
0
 public function renderTwig($layout, $params = [])
 {
     $time = \PHP_Timer::resourceUsage();
     $params['time'] = $time;
     $loader = new \Twig_Loader_Filesystem([str_replace('\\', '/', __DIR__ . '/layouts'), str_replace('\\', '/', __DIR__ . '/templates')]);
     $twig = new \Twig_Environment($loader, ['cache' => false]);
     $content = $twig->render($layout, $params);
     return $content;
 }
 /**
  * Example middleware invokable class.
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     // Start the timer at the beginning of the request
     \PHP_Timer::start();
     $response = $next($request, $response);
     // Log the results
     $this->logger->info($request->getUri()->getAuthority() . ' ' . $request->getHeaderLine('AUTH_PRINCIPAL') . ' ' . $request->getAttribute('ip_address') . ' ' . $request->getMethod() . ' ' . $request->getUri()->getPath() . ' ' . $response->getStatusCode() . ' ' . $request->getBody()->getSize() . ' ' . $response->getBody()->getSize() . ' ' . \PHP_Timer::stop());
     return $response;
 }
Beispiel #9
0
 public function testArrays()
 {
     $total = 1000000;
     $try1 = array_fill(0, $total, 1);
     $try1[rand(0, count($try1) - 1)] = null;
     $try2 = array_fill(0, $total, 1);
     $try2[rand(0, count($try1) - 1)] = null;
     $try2[(string) count($try2)] = 'value';
     $uk = rand(0, $total);
     unset($try2[$uk]);
     print 'isSequentialFastest:' . PHP_EOL;
     \PHP_Timer::start();
     $isHashFalse = !ArrayStructure::isSequentialFastest($try1);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     \PHP_Timer::start();
     $isHashTrue = !ArrayStructure::isSequentialFastest($try2);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     $this->assertFalse($isHashFalse);
     $this->assertTrue($isHashTrue);
     print 'isSequentialSimple:' . PHP_EOL;
     \PHP_Timer::start();
     $isSeqFalse = !ArrayStructure::isSequentialSimple($try1);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     \PHP_Timer::start();
     $isSeqTrue = !ArrayStructure::isSequentialSimple($try2);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     $this->assertFalse($isSeqFalse);
     $this->assertTrue($isSeqTrue);
     print 'isSequentialExotic:' . PHP_EOL;
     \PHP_Timer::start();
     $isSeqTrue = ArrayStructure::isSequentialExotic($try1);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     \PHP_Timer::start();
     $isSeqFalse = ArrayStructure::isSequentialExotic($try2);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     $this->assertFalse($isSeqFalse);
     $this->assertTrue($isSeqTrue);
     print 'isAssoc:' . PHP_EOL;
     \PHP_Timer::start();
     $isAssocFalse = ArrayStructure::isAssoc($try1);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     \PHP_Timer::start();
     $isAssocTrue = ArrayStructure::isAssoc($try2);
     $time = \PHP_Timer::stop();
     print \PHP_Timer::secondsToTimeString($time) . PHP_EOL;
     $this->assertFalse($isAssocFalse);
     $this->assertTrue($isAssocTrue);
 }
Beispiel #10
0
 /**
  * Run the invocable, and its prerequisites, by calling the invoke method
  *
  * @param string $start
  */
 public function run($start)
 {
     Timer::start();
     $task = $this->buildfile->get($start);
     $nodes = $this->buildfile->get($start)->getAdjacencyList();
     foreach ($nodes as $prerequisite) {
         $this->run($prerequisite);
     }
     $task->invoke();
     $this->duration = Timer::stop();
 }
 /**
  * If the dispatcher is run when there is a non-empty queue, a payload will
  * be dispatched from that queue.
  */
 public function testRun()
 {
     $dispatcher = new SyncDispatcher($this->queue, $this->worker);
     $dispatcher->setWorkerTimeout(1000);
     $this->queue->expects($this->any())->method('count')->willReturn(123);
     $this->queue->expects($this->once())->method('pop')->willReturn('test');
     $this->worker->expects($this->once())->method('run')->with('test');
     Timer::start();
     $dispatcher->run();
     $time = Timer::stop();
     $this->assertEquals(1, $time, "Time not within 50ms of target.", 0.05);
 }
 /**
  * When a payload is dispatched, a timeout should occur, after which the
  * worker associated with the dispatcher should consume the payload.
  */
 public function testDispatchAction()
 {
     $dispatcher = new DaemonDispatcher($this->queue, $this->worker, 3);
     $dispatcher->setManager($this->manager);
     $dispatcher->setWorkerTimeout(1000);
     $this->worker->expects($this->once())->method('run')->with('testing');
     Timer::start();
     $dispatcher->getDispatchAction('testing')->__invoke();
     $time = Timer::stop();
     $this->assertEquals(1, $time, "Time not within 50ms of target.", 0.05);
     $this->assertEmpty($dispatcher->getManager()->count());
 }
Beispiel #13
0
 /**
  * Метод вывода одной новости по её id
  *
  */
 protected function actionOne()
 {
     $id = (int) $_GET['id'] ?: false;
     if (empty($id)) {
         $this->redirect('/');
     }
     if (!empty($article = NewsModel::findById($id))) {
         $this->view->render('/news/one.html', ['article' => $article, 'resource' => \PHP_Timer::resourceUsage()]);
     } else {
         $this->view->erroradmin = false;
         throw new Exception404('Страница с такой новостью не найдена');
     }
 }
 public function testPersistentResourceSimulation()
 {
     PHP_Timer::start();
     $movie = new ffmpeg_movie(self::$moviePath, true);
     $movie = new ffmpeg_movie(self::$moviePath, true);
     $movie = new ffmpeg_movie(self::$moviePath, true);
     $elapsed = PHP_Timer::stop();
     PHP_Timer::start();
     $movie = new ffmpeg_movie(self::$moviePath);
     $movie = new ffmpeg_movie(self::$moviePath);
     $movie = new ffmpeg_movie(self::$moviePath);
     $elapsed1 = PHP_Timer::stop();
     $this->assertGreaterThan($elapsed, $elapsed1, 'Persistent resource simulation should be faster');
 }
Beispiel #15
0
 /**
  * Class constructor for full/combined report
  *
  * @param string $source       Data source
  * @param array  $options      Options for parser
  * @param array  $warnings     List of warning messages already produced
  * @param array  $reportChilds List of reports to print
  */
 public function __construct($source, $options, $warnings, $reportChilds)
 {
     $pci = new PHP_CompatInfo($options);
     if ($pci->parse($source) === false) {
         return;
     }
     $reportResults = $pci->toArray();
     $masterResults = $reportResults[0];
     if ($options['verbose'] < 3) {
         $reportResults = $reportResults[0];
     } else {
         unset($reportResults[0]);
     }
     $base = realpath($source);
     if (is_file($base)) {
         $base = dirname($base);
     }
     $allWarnings = array_unique(array_merge($warnings, $pci->getWarnings()));
     $options = $pci->getOptions();
     if (empty($reportChilds)) {
         $reportChilds = array('summary', 'extension', 'interface', 'trait', 'class', 'function', 'constant', 'global', 'token', 'condition');
     }
     foreach ($reportChilds as $report) {
         $classReport = 'PHP_CompatInfo_Report_' . ucfirst($report);
         new $classReport($source, $options, $allWarnings, $reportResults);
     }
     echo PHP_EOL;
     if (count($allWarnings) > 0 && $options['verbose'] > 0) {
         echo 'Warning messages : (' . count($allWarnings) . ')' . PHP_EOL;
         echo PHP_EOL;
         foreach ($allWarnings as $warn) {
             if (in_array($warn, $warnings)) {
                 // other listeners need to be notifed about console warnings
                 $pci->addWarning($warn);
             }
             echo '  ' . $warn . PHP_EOL;
         }
         echo PHP_EOL;
     }
     if (class_exists('PHP_Timer', true) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL;
         echo PHP_EOL;
     }
     echo 'Required PHP ' . $masterResults['versions'][0] . ' (min)';
     if (!empty($masterResults['versions'][1])) {
         echo ', ' . $masterResults['versions'][1] . ' (max)';
     }
     echo PHP_EOL;
 }
Beispiel #16
0
 public function run(PHPUnit_Framework_TestResult $result = null)
 {
     PHPUnit_Framework_Assert::resetCount();
     if ($result === NULL) {
         $result = new PHPUnit_Framework_TestResult();
     }
     $this->suite->publishTestArticles();
     // Add articles needed by the tests.
     $backend = new ParserTestSuiteBackend();
     $result->startTest($this);
     // Support the transition to PHPUnit 3.5 where PHPUnit_Util_Timer is replaced with PHP_Timer
     if (class_exists('PHP_Timer')) {
         PHP_Timer::start();
     } else {
         PHPUnit_Util_Timer::start();
     }
     $r = false;
     try {
         # Run the test.
         # On failure, the subclassed backend will throw an exception with
         # the details.
         $pt = new PHPUnitParserTest();
         $r = $pt->runTest($this->test['test'], $this->test['input'], $this->test['result'], $this->test['options'], $this->test['config']);
     } catch (PHPUnit_Framework_AssertionFailedError $e) {
         // PHPUnit_Util_Timer -> PHP_Timer support (see above)
         if (class_exists('PHP_Timer')) {
             $result->addFailure($this, $e, PHP_Timer::stop());
         } else {
             $result->addFailure($this, $e, PHPUnit_Util_Timer::stop());
         }
     } catch (Exception $e) {
         // PHPUnit_Util_Timer -> PHP_Timer support (see above)
         if (class_exists('PHP_Timer')) {
             $result->addFailure($this, $e, PHP_Timer::stop());
         } else {
             $result->addFailure($this, $e, PHPUnit_Util_Timer::stop());
         }
     }
     // PHPUnit_Util_Timer -> PHP_Timer support (see above)
     if (class_exists('PHP_Timer')) {
         $result->endTest($this, PHP_Timer::stop());
     } else {
         $result->endTest($this, PHPUnit_Util_Timer::stop());
     }
     $backend->recorder->record($this->test['test'], $r);
     $this->addToAssertionCount(PHPUnit_Framework_Assert::getCount());
     return $result;
 }
function podlove_validate_image_cache()
{
    set_time_limit(5 * MINUTE_IN_SECONDS);
    PHP_Timer::start();
    $cache_files = glob(trailingslashit(Image::cache_dir()) . "*" . DIRECTORY_SEPARATOR . "*" . DIRECTORY_SEPARATOR . "cache.yml");
    foreach ($cache_files as $cache_file) {
        $cache = Yaml::parse(file_get_contents($cache_file));
        $validator = new HttpHeaderValidator($cache['source'], $cache['etag'], $cache['last-modified']);
        $validator->validate();
        if ($validator->hasChanged()) {
            wp_schedule_single_event(time(), 'podlove_refetch_cached_image', [$cache['source'], $cache['filename']]);
        }
    }
    $time = PHP_Timer::stop();
    \Podlove\Log::get()->addInfo(sprintf('Finished validating %d images in %s', count($cache_files), PHP_Timer::secondsToTimeString($time)));
}
Beispiel #18
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if (\App::environment() === 'production') {
         $this->error('This feature is not available on this server');
     }
     $process = new Process('apidoc -i ' . base_path('app/Http/Controllers') . ' -o ' . base_path('apidoc'));
     $process->run();
     if (!$process->isSuccessful()) {
         $this->error('Impossible to generate doc');
         $this->error($process->getErrorOutput());
         $this->info('You need to install apidoc: (sudo) npm install apidoc -g');
         return;
     }
     $this->info($process->getOutput());
     $this->comment('Documentation generated in folder ' . base_path('doc'));
     $this->comment(\PHP_Timer::resourceUsage());
 }
Beispiel #19
0
 /**
  * Executes the current command.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|int null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $finder = new FinderFacade($input->getArgument('values'), $input->getOption('exclude'), $this->handleCSVOption($input, 'names'), $this->handleCSVOption($input, 'names-exclude'));
     $files = $finder->findFiles();
     if (empty($files)) {
         $output->writeln('No files found to scan');
         exit(1);
     }
     $quiet = $output->getVerbosity() == OutputInterface::VERBOSITY_QUIET;
     $detector = new Detector();
     $result = $detector->detectDeadCode($files, $input->getOption('recursive'));
     if (!$quiet) {
         $printer = new Text();
         $printer->printResult($output, $result);
         $output->writeln(\PHP_Timer::resourceUsage());
     }
 }
Beispiel #20
0
 /**
  * Executes the current command.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|int null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $database = new Database($input->getArgument('database'));
     $repository = $input->getArgument('repository');
     $quiet = $output->getVerbosity() == OutputInterface::VERBOSITY_QUIET;
     $finder = new FinderFacade(array($repository), $input->getOption('exclude'), $this->handleCSVOption($input, 'names'), $this->handleCSVOption($input, 'names-exclude'));
     $progressHelper = null;
     if ($input->getOption('progress')) {
         $progressHelper = $this->getHelperSet()->get('progress');
     }
     $processor = new Processor($repository, $database, $finder, $output, $progressHelper);
     $processor->process();
     if ($input->getOption('progress')) {
         $progressHelper->finish();
         $output->writeln('');
     }
     if (!$quiet) {
         $output->writeln(\PHP_Timer::resourceUsage());
     }
 }
Beispiel #21
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     \Log::info('Assets::Clean cleaning build assets');
     $baseAssetsPath = base_path('public/assets/');
     if (!is_dir($baseAssetsPath)) {
         $this->warn(sprintf("Folder %s does not exists", $baseAssetsPath));
         return;
     }
     if ($handle = opendir($baseAssetsPath)) {
         while (false !== ($entry = readdir($handle))) {
             $path = $baseAssetsPath . '/' . $entry;
             if ($entry != "." && $entry != ".." && is_dir($path)) {
                 $this->info('Delete public/assets/' . $entry);
                 $this->deleteDir($path);
             }
         }
         closedir($handle);
     }
     $this->comment(\PHP_Timer::resourceUsage());
 }
Beispiel #22
0
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $configFile = $input->getArgument('config');
     if (!$configFile) {
         throw new \Exception('Config argument needed');
     }
     $filesystem = new FilesystemAccess(null);
     $config = new Config($filesystem);
     $config->loadConfig($configFile);
     $config = $config->getConfig();
     $config->folders->root = realpath($config->folders->root);
     $filesystem->setRoot($config->folders->root);
     $directoryScanner = new DirectoryScanner($filesystem, $config->folders->root);
     foreach ($config->folders->include as $include) {
         $directoryScanner->includeDirectory($include);
     }
     foreach ($config->folders->exclude as $exclude) {
         $directoryScanner->excludeDirectory($exclude);
     }
     foreach ($config->filetypes->include as $include) {
         $directoryScanner->includeFiletype($include);
     }
     foreach ($config->filetypes->exclude as $exclude) {
         $directoryScanner->excludeFiletype($exclude);
     }
     $files = $directoryScanner->getFiles();
     $outputClass = new ChainedOutput($output);
     foreach ($config->output as $outputConfiguration) {
         $outputClass->addOutputClass($outputConfiguration->class, $outputConfiguration->parameter);
     }
     $classScanner = new ClassScanner($filesystem, $config->folders->root, $config->vendor, $outputClass);
     $classModifier = new NamespaceDependencyChecker($filesystem, $classScanner, $config->vendor, $config->folders->root, $outputClass);
     $classModifier->analyze($files);
     $outputClass->printAll();
     $outputClass->writeln(\PHP_Timer::resourceUsage());
     if ($classScanner->foundError || $classModifier->foundError) {
         return 1;
     } else {
         return 0;
     }
 }
Beispiel #23
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     \Log::info('Assets::Update Run bower update');
     $this->info("Update bower assets");
     $process = new Process('bower update --allow-root');
     $process->run(function ($type, $buffer) {
         if ('err' === $type) {
             $this->error($buffer);
         } else {
             $this->info($buffer);
         }
     });
     if (!$process->isSuccessful()) {
         $this->error('Impossible to update bower');
         $this->error($process->getErrorOutput());
     }
     $this->info("Remove useless local bower package");
     $process = new Process('bower prune --allow-root');
     $process->run();
     $this->comment(\PHP_Timer::resourceUsage());
 }
Beispiel #24
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Build assets");
     $cmd = sprintf('node ./node_modules/gassetic/bin.js %s --env=%s', $this->getGasseticArgument(), $this->getEnv());
     $this->info($cmd);
     $process = new Process($cmd);
     $process->setTimeout($this->option('watch') ? 86400 : 30);
     $process->run(function ($type, $buffer) {
         // prevent double line break
         $buffer = str_replace("\n", "", $buffer);
         if ('err' === $type) {
             $this->error($buffer);
         } else {
             $this->info($buffer);
         }
     });
     if (!$process->isSuccessful()) {
         $this->error($process->getErrorOutput());
     }
     $this->comment(\PHP_Timer::resourceUsage());
 }
 public function testPersistentResourceSimulation()
 {
     PHP_Timer::start();
     $provider = new FFmpegOutputProvider('ffmpeg', true);
     $provider->setMovieFile(self::$moviePath);
     $provider->getOutput();
     $provider = clone $provider;
     $provider->getOutput();
     $provider = clone $provider;
     $provider->getOutput();
     $elapsed = PHP_Timer::stop();
     PHP_Timer::start();
     $provider = new FFmpegOutputProvider('ffmpeg', false);
     $provider->setMovieFile(self::$moviePath);
     $provider->getOutput();
     $provider = clone $provider;
     $provider->getOutput();
     $provider = clone $provider;
     $provider->getOutput();
     $elapsed1 = PHP_Timer::stop();
     $this->assertGreaterThan($elapsed, $elapsed1, 'Persistent resource simulation should be faster');
 }
Beispiel #26
0
 /**
  * Executes the current command.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|integer null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $finder = new FinderFacade($input->getArgument('values'), $input->getOption('exclude'), $this->handleCSVOption($input, 'names'), $this->handleCSVOption($input, 'names-exclude'));
     $files = $finder->findFiles();
     if (empty($files)) {
         $output->writeln('No files found to scan');
         exit(1);
     }
     $progressHelper = null;
     if ($input->getOption('progress')) {
         $progressHelper = $this->getHelperSet()->get('progress');
         $progressHelper->start($output, count($files));
     }
     $strategy = new DefaultStrategy();
     $detector = new Detector($strategy, $progressHelper);
     $quiet = $output->getVerbosity() == OutputInterface::VERBOSITY_QUIET;
     $clones = $detector->copyPasteDetection($files, $input->getOption('min-lines'), $input->getOption('min-tokens'), $input->getOption('fuzzy'));
     if ($input->getOption('progress')) {
         $progressHelper->finish();
         $output->writeln('');
     }
     if (!$quiet) {
         $printer = new Text();
         $printer->printResult($output, $clones);
         unset($printer);
     }
     $logPmd = $input->getOption('log-pmd');
     if ($logPmd) {
         $pmd = new PMD($logPmd);
         $pmd->processClones($clones);
         unset($pmd);
     }
     if (!$quiet) {
         print \PHP_Timer::resourceUsage() . "\n";
     }
     if (count($clones) > 0) {
         exit(1);
     }
 }
Beispiel #27
0
 /**
  * Runs a test and collects its result in a TestResult instance.
  * Executes before/after hooks coming from traits.
  *
  * @param  \PHPUnit_Framework_TestResult $result
  * @return \PHPUnit_Framework_TestResult
  */
 public final function run(\PHPUnit_Framework_TestResult $result = null)
 {
     $this->testResult = $result;
     $result->startTest($this);
     foreach ($this->hooks as $hook) {
         if (method_exists($this, $hook . 'Start')) {
             $this->{$hook . 'Start'}();
         }
     }
     $status = self::STATUS_PENDING;
     $time = 0;
     $e = null;
     if (!$this->ignored) {
         \PHP_Timer::start();
         try {
             $this->test();
             $status = self::STATUS_OK;
         } catch (\PHPUnit_Framework_AssertionFailedError $e) {
             $status = self::STATUS_FAIL;
         } catch (\PHPUnit_Framework_Exception $e) {
             $status = self::STATUS_ERROR;
         } catch (\Throwable $e) {
             $e = new \PHPUnit_Framework_ExceptionWrapper($e);
             $status = self::STATUS_ERROR;
         } catch (\Exception $e) {
             $e = new \PHPUnit_Framework_ExceptionWrapper($e);
             $status = self::STATUS_ERROR;
         }
         $time = \PHP_Timer::stop();
     }
     foreach (array_reverse($this->hooks) as $hook) {
         if (method_exists($this, $hook . 'End')) {
             $this->{$hook . 'End'}($status, $time, $e);
         }
     }
     $result->endTest($this, $time);
     return $result;
 }
Beispiel #28
0
 /**
  * Prints a result set from PHPCPD_Detector::copyPasteDetection().
  *
  * @param PHPCPD_CloneMap $clones
  * @param string          $commonPath
  * @param bool            $verbose
  */
 public function printResult(PHPCPD_CloneMap $clones, $commonPath, $verbose)
 {
     $numClones = count($clones);
     if ($numClones > 0) {
         $buffer = '';
         $files = array();
         $lines = 0;
         foreach ($clones as $clone) {
             if (!isset($files[$clone->aFile])) {
                 $files[$clone->aFile] = TRUE;
             }
             if (!isset($files[$clone->bFile])) {
                 $files[$clone->bFile] = TRUE;
             }
             $lines += $clone->size;
             if ($verbose) {
                 $buffer .= sprintf("\n  - %s:%d-%d\n    %s:%d-%d\n", str_replace($commonPath, '', $clone->aFile), $clone->aStartLine, $clone->aStartLine + $clone->size, str_replace($commonPath, '', $clone->bFile), $clone->bStartLine, $clone->bStartLine + $clone->size);
             }
         }
         printf("Found %d exact clones with %d duplicated lines in %d files%s", $numClones, $lines, count($files), $verbose ? ":\n" . $buffer : ".\n");
     }
     printf("%s%s duplicated lines out of %d total lines of code.\n\n%s\n", $numClones > 0 ? "\n" : '', $clones->getPercentage(), $clones->getNumLines(), PHP_Timer::resourceUsage());
 }
 /**
  * 
  * Compares two propel objects and notifies the PHPUnit / Kaltura's listeners
  * @param BaseObject $outputReference
  * @param BaseObject $newResult
  * @return array<> $newErrors, if the objects are equal
  */
 public function comparePropelObjectsByFields($outputReference, $newResult, $validErrorFields)
 {
     //Gets the data peer of the object (used to geting all the obejct feilds)
     $dataPeer = $outputReference->getPeer();
     $outputReferenceId = $outputReference->getId();
     $newResultId = $newResult->getId();
     //Gets all object feilds
     $fields = call_user_func(array($dataPeer, "getFieldNames"), BasePeer::TYPE_PHPNAME);
     $newErrors = array();
     //Create the xml elements by all fields and their values
     foreach ($fields as $field) {
         PHP_Timer::start();
         //If the field is in the valid failure list then we skip him
         if (in_array($field, $validErrorFields)) {
             continue;
         } else {
             $expectedValue = $outputReference->getByName($field);
             $actualValue = $newResult->getByName($field);
             //if this is an array we need to change it to a string
             $this->compareOnField($field, $actualValue, $expectedValue, "assertEquals");
         }
     }
     return $newErrors;
 }
    $totalUser += $newInstallCount;
    $start = microtime(true);
    $groupedDetail = $userDetailProvider->generate($groupedUidList);
    $delta = microtime(true) - $start;
    appendLog(sprintf('Total %d new install on %s, read detail cost %s', $newInstallCount, $calendarDay, PHP_Timer::secondsToTimeString($delta)));
    $esUpdateQueue = [];
    foreach ($groupedDetail as $payload) {
        $shardId = $payload['shardId'];
        $shardUserList = $payload['dataSet'];
        $count = count($shardUserList);
        if ($count === 0) {
            continue;
        }
        appendLog(sprintf('%s have %d user to sync', $shardId, $count));
        $esUpdateQueue = array_merge($esUpdateQueue, $shardUserList);
        $queueLength = count($esUpdateQueue);
        if ($queueLength >= $magicNumber) {
            appendLog(sprintf('%s: flush ES update queue: %d user on date %s to sync %s', date('c'), $queueLength, $calendarDay, PHP_Timer::resourceUsage()));
            call_user_func($esUpdateHandler, $indexer, $esUpdateQueue);
            $esUpdateQueue = [];
        }
    }
    call_user_func($esUpdateHandler, $indexer, $esUpdateQueue);
    $calendarMarker->mark($markerDate);
    appendLog(sprintf('Total %d user processed, cost %s', $totalUser, PHP_Timer::resourceUsage()));
    ++$processedRound;
    if ($processedRound >= $safeRound) {
        appendLog(sprintf('Safe round finished, cost %s', PHP_Timer::resourceUsage()));
        break;
    }
}