Sha256: 2800cd0aac50c3f889cfb2b1a43f3833e8f387d4ad749984e2c82dd9f465bd5b

Contents?: true

Size: 1.64 KB

Versions: 3

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

require "json"
require "open3"

module Danger
  # [Danger](http://danger.systems/ruby/) plugin for [phpmd](https://phpmd.org/).
  #
  # @example Run phpmd and send warn comment.
  #
  #          phpmd.binary_path = "vendor/bin/phpmd"
  #          phpmd.run ruleset: "rulesets.xml"
  #
  # @see  ktakayama/danger-phpmd
  # @tags phpmd
  #
  class DangerPhpmd < Plugin
    # phpmd path
    # @return [String]
    attr_accessor :binary_path

    # Execute phpmd
    # @return [void]
    def run(options)
      return if target_files.empty?

      tmpfile = Tempfile.open("phpmd_result")
      Open3.capture3(cmd_path, "--reportfile", tmpfile.path, target_files.join(","), "json", options[:ruleset])
      results = parse(tmpfile.read)
      results.each do |result|
        warn(result[:message], file: result[:file], line: result[:line])
      end
    end

    private

    def cmd_path
      return binary_path if binary_path

      File.exist?("./vendor/bin/phpmd") ? "./vendor/bin/phpmd" : "phpmd"
    end

    def parse(json)
      array = JSON.parse json
      return if array.empty?

      path = "#{Dir.pwd}/"

      results = []
      array["files"].each do |line|
        file = line["file"].sub(path, "")
        line["violations"].each do |violation|
          results << {
            message: violation["description"],
            file: file,
            line: violation["beginLine"]
          }
        end
      end
      results
    end

    def target_files
      ((git.added_files + (git.modified_files - git.deleted_files)) - git.renamed_files.map { |r| r[:before] } + git.renamed_files.map { |r| r[:after] }).uniq
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
danger-phpmd-0.2.0 lib/phpmd/plugin.rb
danger-phpmd-0.1.1 lib/phpmd/plugin.rb
danger-phpmd-0.1.0 lib/phpmd/plugin.rb