Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Last active November 9, 2022 07:51
Show Gist options
  • Save AnandPilania/ec77899034512d9a14fa9119fe0286ca to your computer and use it in GitHub Desktop.
Save AnandPilania/ec77899034512d9a14fa9119fe0286ca to your computer and use it in GitHub Desktop.
Get project (local) SVN details in Laravel
<?php
namespace App\Support;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
class SVN
{
protected $connection;
protected $db;
protected $limit;
protected $isLastSet = false;
protected $select = ['revision', 'changed_author', 'changed_date', 'changed_revision'];
protected $groupBy = ['changed_revision'];
protected $orderBy = ['changed_date', 'DESC'];
public function __construct()
{
$path = base_path('.svn/wc.db');
if (!file_exists($path)) {
throw new \Exception('Unable to find SVN.');
}
if (!extension_loaded('pdo_sqlite')) {
$this->throwError('driver');
}
$this->setNoLimit();
$this->db = new \Illuminate\Database\Query\Builder($this->connection = new \Illuminate\Database\SQLiteConnection(new \PDO('sqlite:' . $path)));
}
public function select($cols)
{
$this->select = Arr::wrap($cols);
return $this;
}
public function groupBy($cols)
{
$this->groupBy = Arr::wrap($cols);
return $this;
}
public function orderBy($key, $dir)
{
$this->orderBy[] = [$key, $dir];
return $this;
}
public function getLast($limit)
{
$this->limit = $limit;
$this->isLastSet = true;
return $this;
}
public function getLastRevision()
{
if ($this->isLastSet) {
$this->throwError('getLast');
}
$this->limit = 1;
return !blank($revisions = $this->revisions())
? $revisions[0]
: $revisions;
}
public function revisions()
{
if (!$this->connection->getSchemaBuilder()->hasTable('NODES')) {
$this->throwError('table');
}
if (!blank($this->select) && (!blank($this->groupBy) || !blank($this->orderBy))) {
if (collect($this->groupBy ?? [])->filter(function ($c) {
return in_array($c, $this->select, true);
})->isEmpty()) {
$this->throwError('groupBy');
}
if (collect($this->orderBy ?? [])->chunk(2)->filter(function ($c, $k) {
return in_array($c->first(), $this->select, true);
})->isEmpty()) {
$this->throwError('orderBy');
}
}
return $this->db->newQuery()
->from('nodes')
->select($this->select)
->groupBy($this->groupBy)
->when(!blank($this->orderBy), function ($q) {
collect($this->orderBy)->chunk(2)->each(function ($c) use ($q) {
$q->orderBy(...$c);
});
})->limit($this->limit)->get()->all();
}
protected function setNoLimit()
{
$this->limit = PHP_INT_MAX;
}
protected function throwError($code)
{
throw new \Exception(
match ($code) {
'driver' => 'PDO_SQLITE extension to be enabled.',
'table' => 'NODES not found!',
'groupBy' => 'GroupBy column is not selected!',
'orderBy' => 'OrderBy column is not selected!',
'getLast' => 'Can\'t use getLastRevision method with getLast!',
'default' => 'Unknown Error'
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment