예제 #1
0
 /**
  * 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";
 }
예제 #2
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());
 }
예제 #3
0
 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>');
 }
예제 #4
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);
 }
예제 #5
0
파일: View.php 프로젝트: webmaza75/php2
 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;
 }
예제 #6
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('Страница с такой новостью не найдена');
     }
 }
예제 #7
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;
 }
예제 #8
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());
 }
예제 #9
0
파일: Command.php 프로젝트: hqye/phpdcd
 /**
  * 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());
     }
 }
예제 #10
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());
     }
 }
예제 #11
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());
 }
예제 #12
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;
     }
 }
예제 #13
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());
 }
예제 #14
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());
 }
예제 #15
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);
     }
 }
예제 #16
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());
 }
예제 #17
0
 /**
  * Prints the source of all errors and warnings.
  *
  * @param array   $report      Prepared report.
  * @param boolean $showSources Show sources?
  * @param int     $width       Maximum allowed lne width.
  * @param boolean $toScreen    Is the report being printed to screen?
  *
  * @return string
  */
 public function generate($report, $showSources = false, $width = 80, $toScreen = true)
 {
     $sources = array();
     $width = max($width, 70);
     $errorsShown = 0;
     foreach ($report['files'] as $filename => $file) {
         foreach ($file['messages'] as $line => $lineErrors) {
             foreach ($lineErrors as $column => $colErrors) {
                 foreach ($colErrors as $error) {
                     $errorsShown++;
                     $source = $error['source'];
                     if (isset($sources[$source]) === false) {
                         $sources[$source] = 1;
                     } else {
                         $sources[$source]++;
                     }
                 }
             }
         }
     }
     if ($errorsShown === 0) {
         // Nothing to show.
         return 0;
     }
     asort($sources);
     $sources = array_reverse($sources);
     echo PHP_EOL . 'PHP CODE SNIFFER VIOLATION SOURCE SUMMARY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     if ($showSources === true) {
         echo 'SOURCE' . str_repeat(' ', $width - 11) . 'COUNT' . PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
     } else {
         echo 'STANDARD  CATEGORY            SNIFF' . str_repeat(' ', $width - 40) . 'COUNT' . PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
     }
     foreach ($sources as $source => $count) {
         if ($showSources === true) {
             echo $source . str_repeat(' ', $width - 5 - strlen($source));
         } else {
             $parts = explode('.', $source);
             if (strlen($parts[0]) > 8) {
                 $parts[0] = substr($parts[0], 0, (strlen($parts[0]) - 8) * -1);
             }
             echo $parts[0] . str_repeat(' ', 10 - strlen($parts[0]));
             $category = $this->makeFriendlyName($parts[1]);
             if (strlen($category) > 18) {
                 $category = substr($category, 0, (strlen($category) - 18) * -1);
             }
             echo $category . str_repeat(' ', 20 - strlen($category));
             $sniff = $this->makeFriendlyName($parts[2]);
             if (isset($parts[3]) === true) {
                 $name = $this->makeFriendlyName($parts[3]);
                 $name[0] = strtolower($name[0]);
                 $sniff .= ' ' . $name;
             }
             if (strlen($sniff) > $width - 37) {
                 $sniff = substr($sniff, 0, $width - 37 - strlen($sniff));
             }
             echo $sniff . str_repeat(' ', $width - 35 - strlen($sniff));
         }
         //end if
         echo $count . PHP_EOL;
     }
     //end foreach
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'A TOTAL OF ' . $errorsShown . ' SNIFF VIOLATION(S) ';
     echo 'WERE FOUND IN ' . count($sources) . ' SOURCE(S)' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL . PHP_EOL;
     if ($toScreen === true && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
     return $errorsShown;
 }
예제 #18
0
 /**
  * Prints all errors and warnings for each file processed.
  *
  * Errors and warnings are displayed together, grouped by file.
  *
  * @param array   $report      Prepared report.
  * @param boolean $showSources Show sources?
  * @param int     $width       Maximum allowed lne width.
  * @param boolean $toScreen    Is the report being printed to screen?
  *
  * @return string
  */
 public function generate($report, $showSources = false, $width = 80, $toScreen = true)
 {
     $errorsShown = 0;
     $width = max($width, 70);
     foreach ($report['files'] as $filename => $file) {
         if (empty($file['messages']) === true) {
             continue;
         }
         echo PHP_EOL . 'FILE: ';
         if (strlen($filename) <= $width - 9) {
             echo $filename;
         } else {
             echo '...' . substr($filename, strlen($filename) - ($width - 9));
         }
         echo PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
         echo 'FOUND ' . $file['errors'] . ' ERROR(S) ';
         if ($file['warnings'] > 0) {
             echo 'AND ' . $file['warnings'] . ' WARNING(S) ';
         }
         echo 'AFFECTING ' . count($file['messages']) . ' LINE(S)' . PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
         // Work out the max line number for formatting.
         $maxLine = 0;
         foreach ($file['messages'] as $line => $lineErrors) {
             if ($line > $maxLine) {
                 $maxLine = $line;
             }
         }
         $maxLineLength = strlen($maxLine);
         // The length of the word ERROR or WARNING; used for padding.
         if ($file['warnings'] > 0) {
             $typeLength = 7;
         } else {
             $typeLength = 5;
         }
         // The padding that all lines will require that are
         // printing an error message overflow.
         $paddingLine2 = str_repeat(' ', $maxLineLength + 1);
         $paddingLine2 .= ' | ';
         $paddingLine2 .= str_repeat(' ', $typeLength);
         $paddingLine2 .= ' | ';
         // The maxium amount of space an error message can use.
         $maxErrorSpace = $width - strlen($paddingLine2) - 1;
         foreach ($file['messages'] as $line => $lineErrors) {
             foreach ($lineErrors as $column => $colErrors) {
                 foreach ($colErrors as $error) {
                     $message = $error['message'];
                     if ($showSources === true) {
                         $message .= ' (' . $error['source'] . ')';
                     }
                     // The padding that goes on the front of the line.
                     $padding = $maxLineLength - strlen($line);
                     $errorMsg = wordwrap($message, $maxErrorSpace, PHP_EOL . $paddingLine2);
                     echo ' ' . str_repeat(' ', $padding) . $line . ' | ' . $error['type'];
                     if ($error['type'] === 'ERROR') {
                         if ($file['warnings'] > 0) {
                             echo '  ';
                         }
                     }
                     echo ' | ' . $errorMsg . PHP_EOL;
                     $errorsShown++;
                 }
                 //end foreach
             }
             //end foreach
         }
         //end foreach
         echo str_repeat('-', $width) . PHP_EOL . PHP_EOL;
     }
     //end foreach
     if ($toScreen === true && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
     return $errorsShown;
 }
예제 #19
0
 /**
  * Returns the header containing resource usage
  *
  * @return string
  */
 public function getHeader()
 {
     return "\n\n" . $this->timer->resourceUsage() . "\n\n";
 }
예제 #20
0
 /**
  * Generates a summary of errors and warnings for each file processed.
  * 
  * If verbose output is enabled, results are shown for all files, even if
  * they have no errors or warnings. If verbose output is disabled, we only
  * show files that have at least one warning or error.
  * 
  * @param array   $report      Prepared report.
  * @param boolean $showSources Show sources?
  * @param int     $width       Maximum allowed lne width.
  * @param boolean $toScreen    Is the report being printed to screen?
  *
  * @return string
  */
 public function generate($report, $showSources = false, $width = 80, $toScreen = true)
 {
     $errorFiles = array();
     $width = max($width, 70);
     foreach ($report['files'] as $filename => $file) {
         $numWarnings = $file['warnings'];
         $numErrors = $file['errors'];
         // If verbose output is enabled, we show the results for all files,
         // but if not, we only show files that had errors or warnings.
         if (PHP_CODESNIFFER_VERBOSITY > 0 || $numErrors > 0 || $numWarnings > 0) {
             $errorFiles[$filename] = array('warnings' => $numWarnings, 'errors' => $numErrors);
         }
         //end if
     }
     //end foreach
     if (empty($errorFiles) === true) {
         // Nothing to print.
         return 0;
     }
     echo PHP_EOL . 'PHP CODE SNIFFER REPORT SUMMARY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'FILE' . str_repeat(' ', $width - 20) . 'ERRORS  WARNINGS' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     $totalErrors = 0;
     $totalWarnings = 0;
     $totalFiles = 0;
     foreach ($errorFiles as $file => $errors) {
         $padding = $width - 18 - strlen($file);
         if ($padding < 0) {
             $file = '...' . substr($file, $padding * -1 + 3);
             $padding = 0;
         }
         echo $file . str_repeat(' ', $padding) . '  ';
         echo $errors['errors'];
         echo str_repeat(' ', 8 - strlen((string) $errors['errors']));
         echo $errors['warnings'];
         echo PHP_EOL;
         $totalFiles++;
     }
     //end foreach
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'A TOTAL OF ' . $report['totals']['errors'] . ' ERROR(S) ';
     echo 'AND ' . $report['totals']['warnings'] . ' WARNING(S) ';
     echo 'WERE FOUND IN ' . $totalFiles . ' FILE(S)' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL . PHP_EOL;
     if ($showSources === true) {
         $source = new PHP_CodeSniffer_Reports_Source();
         $source->generate($report, $showSources, $width);
     }
     if ($toScreen === true && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
     return $report['totals']['errors'] + $report['totals']['warnings'];
 }
예제 #21
0
 protected function printHeader()
 {
     $timer = new PHP_Timer();
     $this->write("\n\n" . $timer->resourceUsage() . "\n\n");
 }
예제 #22
0
 /**
  *
  */
 public function buildSummary()
 {
     echo "\n\n";
     echo \PHP_Timer::resourceUsage();
     echo "\n\n";
 }
예제 #23
0
 /**
  * Generates a summary of errors and warnings for each file processed.
  * 
  * @param string  $cachedData    Any partial report data that was returned from
  *                               generateFileReport during the run.
  * @param int     $totalFiles    Total number of files processed during the run.
  * @param int     $totalErrors   Total number of errors found during the run.
  * @param int     $totalWarnings Total number of warnings found during the run.
  * @param boolean $showSources   Show sources?
  * @param int     $width         Maximum allowed line width.
  * @param boolean $toScreen      Is the report being printed to screen?
  *
  * @return void
  */
 public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $showSources = false, $width = 80, $toScreen = true)
 {
     if ($cachedData === '') {
         return;
     }
     echo PHP_EOL . 'PHP CODE SNIFFER REPORT SUMMARY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'FILE' . str_repeat(' ', $width - 20) . 'ERRORS  WARNINGS' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     echo $cachedData;
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'A TOTAL OF ' . $totalErrors . ' ERROR(S) ';
     echo 'AND ' . $totalWarnings . ' WARNING(S) ';
     echo 'WERE FOUND IN ' . $totalFiles . ' FILE(S)' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'UPGRADE TO PHP_CODESNIFFER 2.0 TO FIX ERRORS AUTOMATICALLY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL . PHP_EOL;
     if ($toScreen === true && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
 }
예제 #24
0
 protected function printHeader()
 {
     $this->write($this->verbose ? "\n" : "\n\n");
     $this->write(PHP_Timer::resourceUsage() . "\n\n");
 }
예제 #25
0
 /**
  * Prints the author of all errors and warnings, as given by "version control blame".
  *
  * @param string  $cachedData    Any partial report data that was returned from
  *                               generateFileReport during the run.
  * @param int     $totalFiles    Total number of files processed during the run.
  * @param int     $totalErrors   Total number of errors found during the run.
  * @param int     $totalWarnings Total number of warnings found during the run.
  * @param boolean $showSources   Show sources?
  * @param int     $width         Maximum allowed line width.
  * @param boolean $toScreen      Is the report being printed to screen?
  *
  * @return void
  */
 public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $showSources = false, $width = 80, $toScreen = true)
 {
     $errorsShown = $totalErrors + $totalWarnings;
     if ($errorsShown === 0) {
         // Nothing to show.
         return;
     }
     $width = max($width, 70);
     arsort($this->_authorCache);
     echo PHP_EOL . 'PHP CODE SNIFFER ' . $this->reportName . ' BLAME SUMMARY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     if ($showSources === true) {
         echo 'AUTHOR   SOURCE' . str_repeat(' ', $width - 43) . '(Author %) (Overall %) COUNT' . PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
     } else {
         echo 'AUTHOR' . str_repeat(' ', $width - 34) . '(Author %) (Overall %) COUNT' . PHP_EOL;
         echo str_repeat('-', $width) . PHP_EOL;
     }
     foreach ($this->_authorCache as $author => $count) {
         if ($this->_praiseCache[$author]['good'] === 0) {
             $percent = 0;
         } else {
             $total = $this->_praiseCache[$author]['bad'] + $this->_praiseCache[$author]['good'];
             $percent = round($this->_praiseCache[$author]['bad'] / $total * 100, 2);
         }
         $overallPercent = '(' . round($count / $errorsShown * 100, 2) . ')';
         $authorPercent = '(' . $percent . ')';
         $line = str_repeat(' ', 6 - strlen($count)) . $count;
         $line = str_repeat(' ', 12 - strlen($overallPercent)) . $overallPercent . $line;
         $line = str_repeat(' ', 11 - strlen($authorPercent)) . $authorPercent . $line;
         $line = $author . str_repeat(' ', $width - strlen($author) - strlen($line)) . $line;
         echo $line . PHP_EOL;
         if ($showSources === true && isset($this->_sourceCache[$author]) === true) {
             $errors = $this->_sourceCache[$author];
             asort($errors);
             $errors = array_reverse($errors);
             foreach ($errors as $source => $count) {
                 if ($source === 'count') {
                     continue;
                 }
                 $line = str_repeat(' ', 5 - strlen($count)) . $count;
                 echo '         ' . $source . str_repeat(' ', $width - 14 - strlen($source)) . $line . PHP_EOL;
             }
         }
     }
     //end foreach
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'A TOTAL OF ' . $errorsShown . ' SNIFF VIOLATION(S) ';
     echo 'WERE COMMITTED BY ' . count($this->_authorCache) . ' AUTHOR(S)' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL;
     echo 'UPGRADE TO PHP_CODESNIFFER 2.0 TO FIX ERRORS AUTOMATICALLY' . PHP_EOL;
     echo str_repeat('-', $width) . PHP_EOL . PHP_EOL;
     if ($toScreen === true && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
 }
예제 #26
0
 protected function printHeader()
 {
     $this->write("\n\n" . PHP_Timer::resourceUsage() . "\n\n");
 }
예제 #27
0
 /**
  * Prints the error report for the run.
  *
  * Note that this function may actually print multiple reports
  * as the user may have specified a number of output formats.
  *
  * @param PHP_CodeSniffer $phpcs       The PHP_CodeSniffer object containing
  *                                     the errors.
  * @param array           $reports     A list of reports to print.
  * @param bool            $showSources TRUE if report should show error sources
  *                                     (not used by all reports).
  * @param string          $reportFile  A default file to log report output to.
  * @param int             $reportWidth How wide the screen reports should be.
  *
  * @return int The number of error and warning messages shown.
  */
 public function printErrorReport(PHP_CodeSniffer $phpcs, $reports, $showSources, $reportFile, $reportWidth)
 {
     $reporting = new PHP_CodeSniffer_Reporting();
     $filesViolations = $phpcs->getFilesErrors();
     if (empty($reports) === true) {
         $reports['full'] = $reportFile;
     }
     $errors = 0;
     $toScreen = false;
     foreach ($reports as $report => $output) {
         if ($output === null) {
             $output = $reportFile;
         }
         if ($reportFile === null) {
             $toScreen = true;
         }
         // We don't add errors here because the number of
         // errors reported by each report type will always be the
         // same, so we really just need 1 number.
         $errors = $reporting->printReport($report, $filesViolations, $showSources, $output, $reportWidth);
     }
     // Only print PHP_Timer output if no reports were
     // printed to the screen so we don't put additional output
     // in something like an XML report. If we are printing to screen,
     // the report types would have already worked out who should
     // print the timer info.
     if ($toScreen === false && PHP_CODESNIFFER_INTERACTIVE === false && class_exists('PHP_Timer', false) === true) {
         echo PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL;
     }
     // They should all return the same value, so it
     // doesn't matter which return value we end up using.
     return $errors;
 }
예제 #28
0
 /**
  * @covers PHP_Timer::resourceUsage
  */
 public function testResourceUsage()
 {
     $this->assertStringMatchesFormat('Time: %s, Memory: %s', PHP_Timer::resourceUsage());
 }
예제 #29
0
    $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;
    }
}
예제 #30
0
 /**
  * First runs PHPUnit and then post processes the generated coverage data
  * to calculate the change coverage.
  *
  * @param array(string) $argv The raw command line arguments.
  *
  * @return integer
  */
 public function run(array $argv)
 {
     $this->printVersionString();
     try {
         $this->handleArguments($argv);
         $arguments = $this->extractPhpunitArguments($argv);
     } catch (InvalidArgumentException $e) {
         $exception = $e->getMessage();
         $arguments = array('--help');
     }
     $phpunit = new PHP_ChangeCoverage_PHPUnit($this->phpunitBinary);
     $phpunit->run($arguments);
     if ($phpunit->isHelp()) {
         $this->writeLine();
         $this->writeLine();
         $this->writeLine('Additional options added by PHP_ChangeCoverage');
         $this->writeLine();
         $this->writeLine('  --temp-dir               Temporary directory for generated runtime data.');
         $this->writeLine('  --phpunit-binary         Optional path to phpunit\'s binary.');
         $this->writeLine('  --modified-since         Cover only lines that were changed since this date.');
         $this->writeLine('                           This option accepts textual date expressions.');
         $this->writeLine('  --unmodified-as-covered  Mark all unmodified lines as covered.');
         if (isset($exception)) {
             $this->writeLine();
             $this->writeLine($exception);
             return 2;
         }
     } else {
         if (file_exists($this->temporaryClover)) {
             PHP_Timer::start();
             $report = $this->createCoverageReport();
             $codeCoverage = $this->rebuildCoverageData($report);
             $this->writeCoverageClover($codeCoverage);
             $this->writeCoverageHtml($codeCoverage);
             PHP_Timer::stop();
             $this->writeLine(PHP_Timer::resourceUsage());
             unlink($this->temporaryClover);
         }
     }
     return $phpunit->getExitCode();
 }