<?php
namespace Gitonomy\Git;
use Gitonomy\Git\Blame\Line;
use Gitonomy\Git\Exception\InvalidArgumentException;
use Gitonomy\Git\Parser\BlameParser;
class Blame implements \Countable
{
protected $repository;
protected $revision;
protected $file;
protected $lineRange;
protected $lines;
public function __construct(Repository $repository, Revision $revision, $file, $lineRange = null)
{
$this->repository = $repository;
$this->revision = $revision;
$this->lineRange = $lineRange;
$this->file = $file;
}
public function getLine($number)
{
if ($number < 1) {
throw new InvalidArgumentException('Line number should be at least 1');
}
$lines = $this->getLines();
if (!isset($lines[$number])) {
throw new InvalidArgumentException('Line does not exist');
}
return $lines[$number];
}
public function getGroupedLines()
{
$result = [];
$commit = null;
$current = [];
foreach ($this->getLines() as $lineNumber => $line) {
if ($commit !== $line->getCommit()) {
if (count($current)) {
$result[] = [$commit, $current];
}
$commit = $line->getCommit();
$current = [];
}
$current[$lineNumber] = $line;
}
if (count($current)) {
$result[] = [$commit, $current];
}
return $result;
}
public function getLines()
{
if (null !== $this->lines) {
return $this->lines;
}
$args = ['-p'];
if (null !== $this->lineRange) {
$args[] = '-L';
$args[] = $this->lineRange;
}
$args[] = $this->revision->getRevision();
$args[] = '--';
$args[] = $this->file;
$parser = new BlameParser($this->repository);
$parser->parse($this->repository->run('blame', $args));
$this->lines = $parser->lines;
return $this->lines;
}
public function count()
{
return count($this->getLines());
}
}