You are here

class SiteAuditCheckCodebasePhpDeadCodeDetection in Site Audit 8.2

Class SiteAuditCheckCodebasePhpDeadCodeDetection.

Hierarchy

Expanded class hierarchy of SiteAuditCheckCodebasePhpDeadCodeDetection

File

Check/Codebase/PhpDeadCodeDetection.php, line 12
Contains \SiteAudit\Check\Codebase\PhpDeadCodeDetection.

View source
class SiteAuditCheckCodebasePhpDeadCodeDetection extends SiteAuditCheckAbstract {

  /**
   * Implements \SiteAudit\Check\Abstract\getLabel().
   */
  public function getLabel() {
    return dt('PHP Dead Code Detector');
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getDescription().
   */
  public function getDescription() {
    return dt('Run phpdcd on custom code.');
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getResultFail().
   */
  public function getResultFail() {
    return dt('Cannot check for unreachable code; an invalid custom code path was specified!');
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getResultInfo().
   */
  public function getResultInfo() {
    if (isset($this->registry['phpdcd_path_error'])) {
      return dt('Missing phpdcd.');
    }
    elseif (isset($this->registry['custom_code'])) {
      return dt('Cannot check for unreachable code; no custom code path specified.');
    }
    return dt('phpdcd does not support XML output yet; please request support in https://github.com/sebastianbergmann/phpdcd/pull/58');
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getResultPass().
   */
  public function getResultPass() {
    return dt('No dead code code found by PHP Dead Code Detector');
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getResultWarn().
   */
  public function getResultWarn() {
    $ret_val = '';
    if (drush_get_option('html') == TRUE) {
      $ret_val .= '<table class="table table-condensed">';
      $ret_val .= '<thead><tr><th>' . dt('Lines Of Code') . '</th><th>' . dt('Starting Line Number') . '</th></tr></thead>';
      foreach ($this->registry['phpdcd_out'] as $filename => $violations) {
        $ret_val .= "<tr align='center'><td colspan='3'>File: {$filename}</td></tr>";
        foreach ($violations as $violation) {
          $loc = $violation->loc;
          $line = $violation->line;
          $ret_val .= "<tr><td>{$loc}</td><td>{$line}</td></tr>";
        }
      }
      $ret_val .= '</table>';
    }
    else {
      $rows = 0;
      foreach ($this->registry['phpdcd_out'] as $filename => $violations) {
        if ($rows++ > 0) {
          $ret_val .= PHP_EOL;
          if (!drush_get_option('json')) {
            $ret_val .= str_repeat(' ', 4);
          }
        }
        $ret_val .= dt('Filename: @filename, Violations: @total', array(
          '@filename' => $filename,
          '@total' => count($violations),
        ));
        foreach ($violations as $violation) {
          $ret_val .= PHP_EOL;
          if (!drush_get_option('json')) {
            $ret_val .= str_repeat(' ', 6);
          }
          $loc = $violation->loc;
          $line = $violation->line;
          $ret_val .= "{$loc} lines starting from line {$line}";
        }
      }
    }
    return $ret_val;
  }

  /**
   * Implements \SiteAudit\Check\Abstract\getAction().
   */
  public function getAction() {
    if (isset($this->registry['phpdcd_path_error'])) {
      return dt('Run "composer install" from the site_audit installation root to install missing dependencies.');
    }
    if (isset($this->registry['custom_code'])) {
      return dt('Use the --custom-code option.');
    }
  }

  /**
   * Implements \SiteAudit\Check\Abstract\calculateScore().
   */
  public function calculateScore() {

    // Get the path of phpdcd.
    $phpdcd_path = $this
      ->getExecPath('phpdcd');
    if ($phpdcd_path === '') {
      $this->registry['phpdcd_path_error'] = TRUE;
      return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO;
    }

    // Get the custom code paths.
    $custom_code = $this
      ->getCustomCodePaths();
    if ($custom_code === FALSE) {
      return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_FAIL;
    }
    if (empty($custom_code)) {
      $this->registry['custom_code'] = TRUE;
      return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO;
    }

    // Get options.
    $valid_options = array(
      'names' => '*.php,*.module,*.install,*.test,*.inc,*.profile,*.theme',
      'names-exclude' => '*.features.*,*_default.inc,*.ds.inc,*.strongarm.inc,*.panelizer.inc,*_defaults.inc,*.box.inc,*.context.inc,*displays.inc',
    );
    $options = $this
      ->getOptions($valid_options, 'phpdcd-');
    $temp_file = tempnam(sys_get_temp_dir(), 'site_audit');
    $option_string = " --log-xml={$temp_file}";
    foreach ($options as $option => $value) {
      $option_string .= " --{$option}";
      if ($value !== TRUE) {
        $option_string .= "={$value}";
      }
    }

    // Suppress XML errors which will be handled by try catch instead.
    libxml_use_internal_errors(TRUE);
    foreach ($custom_code as $path) {
      $command = $phpdcd_path . ' ' . $path . $option_string;
      $process = new Process($command);
      $process
        ->run();
      $error = $process
        ->getErrorOutput();
      if (strpos($error, 'The "--log-xml" option does not exist.') !== FALSE) {
        return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO;
      }
      try {
        $output = simplexml_load_file($temp_file);
        foreach ($output as $data) {
          $filename = $this
            ->getRelativePath((string) $data->file);
          $this->registry['phpdcd_out'][$filename][] = $data;
        }
      } catch (Exception $e) {
        $this
          ->logXmlError($path, 'phpdcd');
        continue;
      }
    }
    if (empty($this->registry['phpdcd_out'])) {
      return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_PASS;
    }
    return SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_WARN;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
SiteAuditCheckAbstract::$abort protected property Indicate that no other checks should be run after this check.
SiteAuditCheckAbstract::$customCode private static property Use for checking whether custom code paths have been validated.
SiteAuditCheckAbstract::$optOut protected property User has opted out of this check in configuration.
SiteAuditCheckAbstract::$percentOverride protected property If set, will override the Report's percentage.
SiteAuditCheckAbstract::$registry protected property Use for passing data between checks within a report.
SiteAuditCheckAbstract::$score protected property Quantifiable number associated with result on a scale of 0 to 2.
SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_FAIL constant
SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_INFO constant
SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_PASS constant
SiteAuditCheckAbstract::AUDIT_CHECK_SCORE_WARN constant
SiteAuditCheckAbstract::getCustomCodePaths public function Returns an array containing custom code paths or AUDIT_CHECK_SCORE_INFO.
SiteAuditCheckAbstract::getExecPath public function Returns the path of the executable.
SiteAuditCheckAbstract::getOptions public function Returns the values of the valid options for a command.
SiteAuditCheckAbstract::getPercentOverride public function Get the report percent override, if any.
SiteAuditCheckAbstract::getRegistry public function Get the check registry.
SiteAuditCheckAbstract::getRelativePath public function Gives path relative to DRUPAL_ROOT of the path is inside Drupal.
SiteAuditCheckAbstract::getResult public function Determine the result message based on the score.
SiteAuditCheckAbstract::getScore public function Get a quantifiable number representing a check result; lazy initialization.
SiteAuditCheckAbstract::getScoreCssClass public function Get the CSS class associated with a score.
SiteAuditCheckAbstract::getScoreDrushLevel public function Get the Drush message level associated with a score.
SiteAuditCheckAbstract::getScoreLabel public function Get a human readable label for a score.
SiteAuditCheckAbstract::logXmlError public function Logs error if unable to parse XML output.
SiteAuditCheckAbstract::renderAction public function Display action items for a user to perform.
SiteAuditCheckAbstract::shouldAbort public function Determine whether the check failed so badly that the report must stop.
SiteAuditCheckAbstract::__construct public function Constructor.
SiteAuditCheckCodebasePhpDeadCodeDetection::calculateScore public function Implements \SiteAudit\Check\Abstract\calculateScore(). Overrides SiteAuditCheckAbstract::calculateScore
SiteAuditCheckCodebasePhpDeadCodeDetection::getAction public function Implements \SiteAudit\Check\Abstract\getAction(). Overrides SiteAuditCheckAbstract::getAction
SiteAuditCheckCodebasePhpDeadCodeDetection::getDescription public function Implements \SiteAudit\Check\Abstract\getDescription(). Overrides SiteAuditCheckAbstract::getDescription
SiteAuditCheckCodebasePhpDeadCodeDetection::getLabel public function Implements \SiteAudit\Check\Abstract\getLabel(). Overrides SiteAuditCheckAbstract::getLabel
SiteAuditCheckCodebasePhpDeadCodeDetection::getResultFail public function Implements \SiteAudit\Check\Abstract\getResultFail(). Overrides SiteAuditCheckAbstract::getResultFail
SiteAuditCheckCodebasePhpDeadCodeDetection::getResultInfo public function Implements \SiteAudit\Check\Abstract\getResultInfo(). Overrides SiteAuditCheckAbstract::getResultInfo
SiteAuditCheckCodebasePhpDeadCodeDetection::getResultPass public function Implements \SiteAudit\Check\Abstract\getResultPass(). Overrides SiteAuditCheckAbstract::getResultPass
SiteAuditCheckCodebasePhpDeadCodeDetection::getResultWarn public function Implements \SiteAudit\Check\Abstract\getResultWarn(). Overrides SiteAuditCheckAbstract::getResultWarn