Collect coverage data.

@param \SimpleXMLElement $file     clover XML object of a file
@param string            $path     path to source file
@param string            $filename filename

@return \PhpCoveralls\Bundle\CoverallsBundle\Entity\SourceFile
325065
protected function collectCoverage(\SimpleXMLElement $file, $path, $filename)
    {
        if ($this->jsonFile->hasSourceFile($path)) {
            $srcFile = $this->jsonFile->getSourceFile($path);
        } else {
            $srcFile = new SourceFile($path, $filename);
        }

        foreach ($file->line as $line) {
            if ((string) $line['type'] === 'stmt') {
                $lineNum = (int) $line['num'];

                if ($lineNum > 0) {
                    $srcFile->addCoverage($lineNum - 1, (int) $line['count']);
                }
            }
        }

        return $srcFile;
    }
476918
private function loadXml($file)
    {
        $internal = libxml_use_internal_errors(true);

        $doc = new DOMDocument();
        $doc->preserveWhiteSpace = false;
        $doc->validateOnParse = true;

        if (!@$doc->load($file)) {
            $errors = libxml_get_errors();

            libxml_use_internal_errors($internal);

            throw XmlException::createUsingErrors($errors);
        }

        libxml_use_internal_errors($internal);

        return new DOMXPath($doc);
    }
185996
public static function stringToDOMDocument($xml, $filename = '')
    {
        $preUseInternalErrors = libxml_use_internal_errors(true);
        try {
            libxml_clear_errors();
            $doc = new DOMDocument();
            if (@$doc->loadXML($xml) === false) {
                throw new Exception(empty($filename) ? 'Failed to parse xml' : ('Failed to load file '.$filename));
            }
        } catch (Exception $x) {
            libxml_use_internal_errors($preUseInternalErrors);
            libxml_clear_errors();
            throw $x;
        }
        libxml_use_internal_errors($preUseInternalErrors);

        return $doc;
    }
1128390
public function collectAndWriteCoverage($args)
    {
        if ($this->valid($args)) {
            extract($args);

            // Check for exist and valid hook
            if (isset($hook) && $hook instanceof HookInterface) {
                $this->hook = $hook;
                unset($hook);
            }

            // Get the realpath coverage directory
            $coverage_dir = realpath($coverage_dir);
            $coverage_file = $coverage_dir.DIRECTORY_SEPARATOR.self::COVERAGE_FILE;
            $coverage_output = $coverage_dir.DIRECTORY_SEPARATOR.self::COVERAGE_OUTPUT;

            // Get the coverage information
            if (is_dir($coverage_dir) && is_file($coverage_file)) {
                // Build the coverage xml object
                $xml = file_get_contents($coverage_file);
                $coverage = new SimpleXMLElement($xml);

                // Prepare the coveralls payload
                $data = $this->collect($coverage, $args);

                // Write the coverage output
                $this->printer->out('Writing coverage output...');
                file_put_contents($coverage_output, json_encode($data->all(), JSON_NUMERIC_CHECK));
            }
        }
    }
11928
public function get($file)
    {
        $basepath = $this->config['basepath'];
        $suffix = $this->config['suffix'];
        $target = "$basepath/$file{$suffix}";

        if (!is_readable($target)) {
            throw new \Exception(t("No such file content: @FILENAME", ["@FILENAME" => $target]));
        }

        $filter  = $this->config['textfilter'];
        $content = file_get_contents($target);
        $content = $this->di->textFilter->doFilter($content, $filter);

        return $content;
    }
811418
static function fetchDOMFromFile( $filename )
    {
        if ( file_exists( $filename ) )
        {
            $dom = new DOMDocument( '1.0', 'utf-8' );
            $dom->preserveWhiteSpace = false;
            $success = $dom->load( $filename );

            if ( !$success )
            {
                return false;
            }
            else
            {
                return $dom;
            }
        }
        return false;
    }
115316
public function export($file = null)
    {
        if ($file) {
            return isset($this->_coverage[$file]) ? $this->_coverage($file, $this->_coverage[$file]) : [];
        }
        $result = [];
        $base = preg_quote($this->base(), '~');
        foreach ($this->_coverage as $file => $rawCoverage) {
            if ($coverage = $this->_coverage($file, $rawCoverage)) {
                $result[preg_replace("~^{$base}~", '', $file)] = $coverage;
            }
        }
        return $result;
    }
1295369
public function collect(\SimpleXMLElement $xml, $rootDir)
    {
        $root = rtrim($rootDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        if ($this->jsonFile === null) {
            $this->jsonFile = new JsonFile();
        }

        // overwrite if run_at has already been set
        $runAt = $this->collectRunAt($xml);
        $this->jsonFile->setRunAt($runAt);

        $xpaths = [
            '/coverage/project/file',
            '/coverage/project/package/file',
        ];

        foreach ($xpaths as $xpath) {
            foreach ($xml->xpath($xpath) as $file) {
                $srcFile = $this->collectFileCoverage($file, $root);

                if ($srcFile !== null) {
                    $this->jsonFile->addSourceFile($srcFile);
                }
            }
        }

        return $this->jsonFile;
    }
1120331
public function dontSeeFileFound($filename, $path = '')
    {
        if ($path === '') {
            \PHPUnit\Framework\Assert::assertFileNotExists($filename);
            return;
        }

        $found = $this->findFileInPath($filename, $path);

        if ($found === false) {
            //this line keeps a count of assertions correct
            \PHPUnit\Framework\Assert::assertTrue(true);
            return;
        }

        \PHPUnit\Framework\Assert::assertFileNotExists($found);
    }
152402
public static function loadFromFile(string $file): Dom
    {
        $dom       = new Dom;
        self::$dom = $dom;

        return $dom->loadFromFile($file);
    }
1233770
public function load($path, $file)
  {
    $the_file = $path . '/' . $file;

    return json_decode($this->read_file($the_file), true);
  }
107691
protected function loadMetadataFromFile(\ReflectionClass $class, $file)
    {
        $previous = libxml_use_internal_errors(true);
        $elem = simplexml_load_file($file);
        libxml_use_internal_errors($previous);
        if (false === $elem) {
            throw new XmlErrorException(libxml_get_last_error());
        }
        $metadata = new ClassMetadata($name = $class->name);
        if (!$elems = $elem->xpath("./class[@name = '".$name."']")) {
            throw new RuntimeException(sprintf('Could not find class %s inside XML element.', $name));
        }
        $elem = reset($elems);
        $metadata->fileResources[] = $file;
        $metadata->fileResources[] = $class->getFileName();

        if (null !== $xmlRootName = $elem->attributes()->{'xml-root-name'}) {
            $metadata->xmlRootName = (string)$xmlRootName;
        }
        if (null !== $xmlRootNamespace = $elem->attributes()->{'xml-root-namespace'}) {
            $metadata->xmlRootNamespace = (string)$xmlRootNamespace;
        }

        foreach ($elem->xpath('./route') as $r) {
            if ('' === $type = (string)$r->attributes()->{'type'}) {
                throw new RuntimeException('Could not find attribute "type" inside XML element.');
            }
            if ('' === $name = (string)$r->attributes()->{'name'}) {
                throw new RuntimeException('Could not find attribute "name" inside XML element.');
            }

            $params = array();
            foreach ($r->xpath('./param') as $p) {
                $params[(string)$p->attributes()] = (string)$p;
            }

            $metadata->addRoute($type, $name, $params);
        }

        return $metadata;
    }
946330
public function loadConfigurationByFilename($filename)
    {

        // initialize the DOMDocument with the configuration file to be validated
        $configurationFile = new \DOMDocument();
        $configurationFile->load($filename);

        // substitute xincludes
        $configurationFile->xinclude(LIBXML_SCHEMA_CREATE);

        // create a DOMElement with the base.dir configuration
        $paramElement = $configurationFile->createElement('param', APPSERVER_BP);
        $paramElement->setAttribute('name', DirectoryKeys::BASE);
        $paramElement->setAttribute('type', ParamNode::TYPE_STRING);

        // create an XPath instance
        $xpath = new \DOMXpath($configurationFile);
        $xpath->registerNamespace('a', 'http://www.appserver.io/appserver');

        // for node data in a selected id
        $baseDirParam = $xpath->query(sprintf('/a:appserver/a:params/a:param[@name="%s"]', DirectoryKeys::BASE));
        if ($baseDirParam->length === 0) {
            // load the <params> node
            $paramNodes = $xpath->query('/a:appserver/a:params');

            // load the first item => the node itself
            if ($paramsNode = $paramNodes->item(0)) {
                // append the base.dir DOMElement
                $paramsNode->appendChild($paramElement);
            } else {
                // throw an exception, because we can't find a mandatory node
                throw new \Exception('Can\'t find /appserver/params node');
            }
        }

        // create a new DOMDocument with the merge content => necessary because else, schema validation fails!!
        $doc = new \DOMDocument();
        $doc->loadXML($configurationFile->saveXML());

        // return the XML document
        return $doc;
    }
212062
public function fileGetContents($file)
    {
        $client = new Client();
        $response = $client->createRequest()
            ->setMethod('get')
            ->setUrl($file)
            ->addHeaders(['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'])
            ->setOptions([
                'timeout' => $this->readFileTimeout, // set timeout to 1 seconds for the case server is not responding
            ])
            ->send();

        if ($response->isOk) {
            return $response->content;
        }

        throw new \Exception("File get contents '{$file}' error: ".$response->content);
    }
1242643
protected function extract($file, $path)
	{
		// we must use cmdline tar, as PharData::extract() messes up symlinks
		$command = 'tar -xzf ' . ProcessExecutor::escape($file) . ' -C ' . ProcessExecutor::escape($path);

		if (0 === $this->process->execute($command, $ignoredOutput)) {
			return;
		}

		throw new \RuntimeException("Failed to execute '$command'\n\n" . $this->process->getErrorOutput());
	}
640657
protected function getGlobPaths($path)
    {
        $paths = [];
        $iterator = new \GlobIterator($path);

        foreach ($iterator as $fileInfo) {
            /* @var $fileInfo \SplFileInfo */
            $paths[] = $fileInfo->getPathname();
        }

        // validate
        if (count($paths) === 0) {
            throw new InvalidConfigurationException("coverage_clover XML file is not readable: ${path}");
        }

        return $paths;
    }
972792
public function loadSetupFile($path)
	{
		$result = false;

		if ($path)
		{
			if (!file_exists($path))
			{
				return $result;
			}

			$xml = simplexml_load_file($path);

			if ($params = $xml->params)
			{
				foreach ($params as $param)
				{
					$this->setXML($param);
					$result = true;
				}
			}
		}
		else
		{
			$result = true;
		}

		return $result;
	}