Refactored project structure.

This commit is contained in:
Dmitry Khomutov 2018-03-04 18:04:15 +07:00
commit c015d8c58b
No known key found for this signature in database
GPG key ID: EC19426474B37AAC
308 changed files with 39 additions and 47 deletions

1098
src/Model/Build.php Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,320 @@
<?php
namespace PHPCensor\Model\Build;
use GuzzleHttp\Client;
use PHPCensor\Builder;
use PHPCensor\Helper\Bitbucket;
use PHPCensor\Helper\Diff;
use PHPCensor\Config;
use PHPCensor\Model\Build;
use PHPCensor\Model\BuildError;
/**
* BitBucket Build Model
*
* @author Dan Cryer <dan@block8.co.uk>
*/
class BitbucketBuild extends GitBuild
{
/**
* Get link to commit from another source (i.e. BitBucket)
*
* @return string
*/
public function getCommitLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/commits/' . $this->getCommitId();
}
/**
* Get link to branch from another source (i.e. BitBucket)
*
* @return string
*/
public function getBranchLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/src/?at=' . $this->getBranch();
}
/**
* Get link to remote branch (from pull request) from another source (i.e. BitBucket)
*/
public function getRemoteBranchLink()
{
$remoteBranch = $this->getExtra('remote_branch');
$remoteReference = $this->getExtra('remote_reference');
return 'https://bitbucket.org/' . $remoteReference . '/src/?at=' . $remoteBranch;
}
/**
* Get link to tag from another source (i.e. BitBucket)
*
* @return string
*/
public function getTagLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/src/?at=' . $this->getTag();
}
/**
* Send status updates to any relevant third parties (i.e. Bitbucket)
*
* @return boolean
*/
public function sendStatusPostback()
{
if (!in_array($this->getSource(), [Build::SOURCE_WEBHOOK, Build::SOURCE_WEBHOOK_PULL_REQUEST], true)) {
return false;
}
$project = $this->getProject();
if (empty($project)) {
return false;
}
$username = Config::getInstance()->get('php-censor.bitbucket.username');
$appPassword = Config::getInstance()->get('php-censor.bitbucket.app_password');
if (empty($username) || empty($appPassword) || empty($this->data['id'])) {
return false;
}
$allowStatusCommit = (boolean)Config::getInstance()->get(
'php-censor.bitbucket.status.commit',
false
);
if (!$allowStatusCommit) {
return false;
}
switch ($this->getStatus()) {
case 0:
case 1:
$status = 'INPROGRESS';
$description = 'PHP Censor build running.';
break;
case 2:
$status = 'SUCCESSFUL';
$description = 'PHP Censor build passed.';
break;
case 3:
$status = 'FAILED';
$description = 'PHP Censor build failed.';
break;
default:
$status = 'STOPPED';
$description = 'PHP Censor build failed to complete.';
break;
}
$phpCensorUrl = Config::getInstance()->get('php-censor.url');
$url = sprintf(
'/2.0/repositories/%s/commit/%s/statuses/build',
Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()
? $this->getExtra('remote_reference')
: $project->getReference(),
$this->getCommitId()
);
$client = new Client([
'base_uri' => 'https://api.bitbucket.org',
'http_errors' => false,
]);
$response = $client->post($url, [
'auth' => [$username, $appPassword],
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'state' => $status,
'key' => 'PHP-CENSOR',
'url' => $phpCensorUrl . '/build/view/' . $this->getId(),
'name' => 'PHP Censor Build #' . $this->getId(),
'description' => $description,
],
]);
$status = (integer)$response->getStatusCode();
return ($status >= 200 && $status < 300);
}
/**
* Get the URL to be used to clone this remote repository.
*
* @return string
*/
protected function getCloneUrl()
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
return 'git@bitbucket.org:' . $this->getProject()->getReference() . '.git';
} else {
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '.git';
}
}
/**
* Get a template to use for generating links to files.
*
* @return string
*/
public function getFileLinkTemplate()
{
$reference = $this->getProject()->getReference();
if (Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()) {
$reference = $this->getExtra('remote_reference');
}
$link = 'https://bitbucket.org/' . $reference . '/';
$link .= 'src/' . $this->getCommitId() . '/';
$link .= '{FILE}';
$link .= '#{BASEFILE}-{LINE}';
return $link;
}
/**
* @inheritdoc
*/
protected function postCloneSetup(Builder $builder, $cloneTo, array $extra = null)
{
$success = true;
$skipGitFinalization = false;
try {
if (Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()) {
$helper = new Bitbucket();
$diff = $helper->getPullRequestDiff(
$this->getProject()->getReference(),
$this->getExtra('pull_request_number')
);
$diffFile = $this->writeDiff($builder->buildPath, $diff);
$cmd = 'cd "%s" && git checkout -b php-censor/' . $this->getId() . ' && git apply "%s"';
$success = $builder->executeCommand($cmd, $cloneTo, $diffFile);
unlink($diffFile);
$skipGitFinalization = true;
}
} catch (\Exception $ex) {
$success = false;
}
if ($success && !$skipGitFinalization) {
$success = parent::postCloneSetup($builder, $cloneTo, $extra);
}
return $success;
}
/**
* Create an diff file on disk for this build.
*
* @param string $cloneTo
* @param string $diff
*
* @return string
*/
protected function writeDiff($cloneTo, $diff)
{
$filePath = dirname($cloneTo . '/temp');
$diffFile = $filePath . '.patch';
file_put_contents($diffFile, $diff);
chmod($diffFile, 0600);
return $diffFile;
}
/**
* @inheritDoc
*/
public function reportError(
Builder $builder,
$plugin,
$message,
$severity = BuildError::SEVERITY_NORMAL,
$file = null,
$lineStart = null,
$lineEnd = null
) {
$allowCommentCommit = (boolean)Config::getInstance()->get(
'php-censor.bitbucket.comments.commit',
false
);
$allowCommentPullRequest = (boolean)Config::getInstance()->get(
'php-censor.bitbucket.comments.pull_request',
false
);
if ($allowCommentCommit || $allowCommentPullRequest) {
$diffLineNumber = $this->getDiffLineNumber($builder, $file, $lineStart);
if (!is_null($diffLineNumber)) {
$helper = new Bitbucket();
$repo = $this->getProject()->getReference();
$prNumber = $this->getExtra('pull_request_number');
$commit = $this->getCommitId();
if (!empty($prNumber)) {
if ($allowCommentPullRequest) {
$helper->createPullRequestComment($repo, $prNumber, $commit, $file, $lineStart, $message);
}
} else {
if ($allowCommentCommit) {
$helper->createCommitComment($repo, $commit, $file, $lineStart, $message);
}
}
}
}
parent::reportError($builder, $plugin, $message, $severity, $file, $lineStart, $lineEnd);
}
/**
* Uses git diff to figure out what the diff line position is, based on the error line number.
*
* @param Builder $builder
* @param string $file
* @param integer $line
*
* @return integer|null
*/
protected function getDiffLineNumber(Builder $builder, $file, $line)
{
$builder->logExecOutput(false);
$line = (integer)$line;
$prNumber = $this->getExtra('pull_request_number');
$path = $builder->buildPath;
if (!empty($prNumber)) {
$builder->executeCommand('cd %s && git diff origin/%s "%s"', $path, $this->getBranch(), $file);
} else {
$commitId = $this->getCommitId();
$compare = empty($commitId) ? 'HEAD' : $commitId;
$builder->executeCommand('cd %s && git diff %s^^ "%s"', $path, $compare, $file);
}
$builder->logExecOutput(true);
$diff = $builder->getLastOutput();
$helper = new Diff();
$lines = $helper->getLinePositions($diff);
return isset($lines[$line]) ? $lines[$line] : null;
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace PHPCensor\Model\Build;
use PHPCensor\Model\Build;
/**
* BitbucketHgBuild Build Model
*
* @author Artem Bochkov <artem.v.bochkov@gmail.com>
*/
class BitbucketHgBuild extends HgBuild
{
/**
* Get link to commit from another source (i.e. BitBucket)
*
* @return string
*/
public function getCommitLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/commits/' . $this->getCommitId();
}
/**
* Get link to branch from another source (i.e. BitBucket)
*
* @return string
*/
public function getBranchLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/src/?at=' . $this->getBranch();
}
/**
* Get link to remote branch (from pull request) from another source (i.e. BitBucket)
*/
public function getRemoteBranchLink()
{
$remoteBranch = $this->getExtra('remote_branch');
$remoteReference = $this->getExtra('remote_reference');
return 'https://bitbucket.org/' . $remoteReference . '/src/?at=' . $remoteBranch;
}
/**
* Get link to tag from another source (i.e. BitBucket)
*
* @return string
*/
public function getTagLink()
{
return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/src/?at=' . $this->getTag();
}
/**
* Get the URL to be used to clone this remote repository.
*
* @return string
*/
protected function getCloneUrl()
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
return 'ssh://hg@bitbucket.org/' . $this->getProject()->getReference();
} else {
return 'https://bitbucket.org/' . $this->getProject()->getReference();
}
}
/**
* Get a template to use for generating links to files.
*
* @return string
*/
public function getFileLinkTemplate()
{
$reference = $this->getProject()->getReference();
if (Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()) {
$reference = $this->getExtra('remote_reference');
}
$link = 'https://bitbucket.org/' . $reference . '/';
$link .= 'src/' . $this->getCommitId() . '/';
$link .= '{FILE}';
$link .= '#{BASEFILE}-{LINE}';
return $link;
}
}

View file

@ -0,0 +1,168 @@
<?php
namespace PHPCensor\Model\Build;
use PHPCensor\Model\Build;
use PHPCensor\Builder;
use Psr\Log\LogLevel;
/**
* Remote Git Build Model
*
* @author Dan Cryer <dan@block8.co.uk>
*/
class GitBuild extends Build
{
/**
* Get the URL to be used to clone this remote repository.
*/
protected function getCloneUrl()
{
return $this->getProject()->getReference();
}
/**
* Create a working copy by cloning, copying, or similar.
*/
public function createWorkingCopy(Builder $builder, $buildPath)
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
$success = $this->cloneBySsh($builder, $buildPath);
} else {
$success = $this->cloneByHttp($builder, $buildPath);
}
if ($success) {
$success = $this->mergeBranches($builder, $buildPath);
}
if (!$success) {
$builder->logFailure('Failed to clone remote git repository.');
return false;
}
return $this->handleConfig($builder, $buildPath);
}
/**
* @param Builder $builder
* @param string $buildPath
* @return bool
*/
protected function mergeBranches(Builder $builder, $buildPath)
{
$branches = $this->getExtra('branches');
if (!empty($branches)) {
$cmd = 'cd "%s" && git merge --quiet origin/%s';
foreach ($branches as $branch) {
$success = $builder->executeCommand($cmd, $buildPath, $branch);
if (!$success) {
$builder->log('Fail merge branch origin/'.$branch, LogLevel::ERROR);
return false;
}
$builder->log('Merged branch origin/'.$branch, LogLevel::INFO);
}
}
return true;
}
/**
* Use an HTTP-based git clone.
*/
protected function cloneByHttp(Builder $builder, $cloneTo)
{
$cmd = 'cd .. && git clone --recursive ';
$depth = $builder->getConfig('clone_depth');
if (!is_null($depth)) {
$cmd .= ' --depth ' . intval($depth) . ' ';
}
$cmd .= ' -b "%s" "%s" "%s"';
$success = $builder->executeCommand($cmd, $this->getBranch(), $this->getCloneUrl(), $cloneTo);
if ($success) {
$success = $this->postCloneSetup($builder, $cloneTo);
}
return $success;
}
/**
* Use an SSH-based git clone.
*/
protected function cloneBySsh(Builder $builder, $cloneTo)
{
$keyFile = $this->writeSshKey($cloneTo);
$gitSshWrapper = $this->writeSshWrapper($cloneTo, $keyFile);
// Do the git clone:
$cmd = 'cd .. && git clone --recursive ';
$depth = $builder->getConfig('clone_depth');
if (!is_null($depth)) {
$cmd .= ' --depth ' . intval($depth) . ' ';
}
$cmd .= ' -b "%s" "%s" "%s"';
$cmd = 'export GIT_SSH="'.$gitSshWrapper.'" && ' . $cmd;
$success = $builder->executeCommand($cmd, $this->getBranch(), $this->getCloneUrl(), $cloneTo);
if ($success) {
$extra = [
'git_ssh_wrapper' => $gitSshWrapper
];
$success = $this->postCloneSetup($builder, $cloneTo, $extra);
}
// Remove the key file and git wrapper:
unlink($keyFile);
unlink($gitSshWrapper);
return $success;
}
/**
* Handle any post-clone tasks, like switching branches.
*
* @param Builder $builder
* @param string $cloneTo
* @param array $extra
*
* @return boolean
*/
protected function postCloneSetup(Builder $builder, $cloneTo, array $extra = null)
{
$success = true;
$commitId = $this->getCommitId();
$chdir = 'cd "%s"';
if (empty($this->getEnvironment()) && !empty($commitId)) {
$cmd = $chdir . ' && git checkout %s --quiet';
$success = $builder->executeCommand($cmd, $cloneTo, $commitId);
}
// Always update the commit hash with the actual HEAD hash
if ($builder->executeCommand($chdir . ' && git rev-parse HEAD', $cloneTo)) {
$commitId = trim($builder->getLastOutput());
$this->setCommitId($commitId);
if ($builder->executeCommand($chdir . ' && git log -1 --pretty=format:%%s %s', $cloneTo, $commitId)) {
$this->setCommitMessage(trim($builder->getLastOutput()));
}
if ($builder->executeCommand($chdir . ' && git log -1 --pretty=format:%%ae %s', $cloneTo, $commitId)) {
$this->setCommitterEmail(trim($builder->getLastOutput()));
}
}
return $success;
}
}

View file

@ -0,0 +1,305 @@
<?php
namespace PHPCensor\Model\Build;
use GuzzleHttp\Client;
use PHPCensor\Builder;
use PHPCensor\Helper\Diff;
use PHPCensor\Helper\Github;
use PHPCensor\Config;
use PHPCensor\Model\Build;
use PHPCensor\Model\BuildError;
/**
* Github Build Model
*
* @author Dan Cryer <dan@block8.co.uk>
*/
class GithubBuild extends GitBuild
{
/**
* Get link to commit from another source (i.e. Github)
*
* @return string
*/
public function getCommitLink()
{
return 'https://github.com/' . $this->getProject()->getReference() . '/commit/' . $this->getCommitId();
}
/**
* Get link to branch from another source (i.e. Github)
*
* @return string
*/
public function getBranchLink()
{
return 'https://github.com/' . $this->getProject()->getReference() . '/tree/' . $this->getBranch();
}
/**
* Get link to remote branch (from pull request) from another source (i.e. Github)
*/
public function getRemoteBranchLink()
{
$remoteBranch = $this->getExtra('remote_branch');
$remoteReference = $this->getExtra('remote_reference');
return 'https://github.com/' . $remoteReference . '/tree/' . $remoteBranch;
}
/**
* Get link to tag from another source (i.e. Github)
*
* @return string
*/
public function getTagLink()
{
return 'https://github.com/' . $this->getProject()->getReference() . '/tree/' . $this->getTag();
}
/**
* Send status updates to any relevant third parties (i.e. Github)
*
* @return boolean
*/
public function sendStatusPostback()
{
if (!in_array($this->getSource(), [Build::SOURCE_WEBHOOK, Build::SOURCE_WEBHOOK_PULL_REQUEST], true)) {
return false;
}
$project = $this->getProject();
if (empty($project)) {
return false;
}
$token = Config::getInstance()->get('php-censor.github.token');
if (empty($token) || empty($this->data['id'])) {
return false;
}
$allowStatusCommit = (boolean)Config::getInstance()->get(
'php-censor.github.status.commit',
false
);
if (!$allowStatusCommit) {
return false;
}
switch ($this->getStatus()) {
case 0:
case 1:
$status = 'pending';
$description = 'PHP Censor build running.';
break;
case 2:
$status = 'success';
$description = 'PHP Censor build passed.';
break;
case 3:
$status = 'failure';
$description = 'PHP Censor build failed.';
break;
default:
$status = 'error';
$description = 'PHP Censor build failed to complete.';
break;
}
$phpCensorUrl = Config::getInstance()->get('php-censor.url');
$url = '/repos/' . $project->getReference() . '/statuses/' . $this->getCommitId();
$client = new Client([
'base_uri' => 'https://api.github.com',
'http_errors' => false,
]);
$response = $client->post($url, [
'headers' => [
'Authorization' => 'token ' . $token,
'Content-Type' => 'application/x-www-form-urlencoded'
],
'json' => [
'state' => $status,
'target_url' => $phpCensorUrl . '/build/view/' . $this->getId(),
'description' => $description,
'context' => 'PHP Censor',
]
]);
$status = (integer)$response->getStatusCode();
return ($status >= 200 && $status < 300);
}
/**
* Get the URL to be used to clone this remote repository.
*
* @return string
*/
protected function getCloneUrl()
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
return 'git@github.com:' . $this->getProject()->getReference() . '.git';
} else {
return 'https://github.com/' . $this->getProject()->getReference() . '.git';
}
}
/**
* Get a parsed version of the commit message, with links to issues and commits.
*
* @return string
*/
public function getCommitMessage()
{
$rtn = parent::getCommitMessage();
$project = $this->getProject();
if (!is_null($project)) {
$reference = $project->getReference();
$commitLink = '<a href="https://github.com/' . $reference . '/issues/$1">#$1</a>';
$rtn = preg_replace('/\#([0-9]+)/', $commitLink, $rtn);
$rtn = preg_replace('/\@([a-zA-Z0-9_]+)/', '<a href="https://github.com/$1">@$1</a>', $rtn);
}
return $rtn;
}
/**
* Get a template to use for generating links to files.
*
* @return string
*/
public function getFileLinkTemplate()
{
$reference = $this->getProject()->getReference();
if (Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()) {
$reference = $this->getExtra('remote_reference');
}
$link = 'https://github.com/' . $reference . '/';
$link .= 'blob/' . $this->getCommitId() . '/';
$link .= '{FILE}';
$link .= '#L{LINE}-L{LINE_END}';
return $link;
}
/**
* @inheritdoc
*/
protected function postCloneSetup(Builder $builder, $cloneTo, array $extra = null)
{
$success = true;
try {
if (Build::SOURCE_WEBHOOK_PULL_REQUEST === $this->getSource()) {
$pullRequestId = $this->getExtra('pull_request_number');
$cmd = 'cd "%s" && git checkout -b php-censor/' . $this->getId()
. ' %s && git pull -q --no-edit origin pull/%s/head';
if (!empty($extra['git_ssh_wrapper'])) {
$cmd = 'export GIT_SSH="'.$extra['git_ssh_wrapper'].'" && ' . $cmd;
}
$success = $builder->executeCommand($cmd, $cloneTo, $this->getBranch(), $pullRequestId);
}
} catch (\Exception $ex) {
$success = false;
}
if ($success) {
$success = parent::postCloneSetup($builder, $cloneTo, $extra);
}
return $success;
}
/**
* @inheritdoc
*/
public function reportError(
Builder $builder,
$plugin,
$message,
$severity = BuildError::SEVERITY_NORMAL,
$file = null,
$lineStart = null,
$lineEnd = null
) {
$allowCommentCommit = (boolean)Config::getInstance()->get(
'php-censor.github.comments.commit',
false
);
$allowCommentPullRequest = (boolean)Config::getInstance()->get(
'php-censor.github.comments.pull_request',
false
);
if ($allowCommentCommit || $allowCommentPullRequest) {
$diffLineNumber = $this->getDiffLineNumber($builder, $file, $lineStart);
if (!is_null($diffLineNumber)) {
$helper = new Github();
$repo = $this->getProject()->getReference();
$prNumber = $this->getExtra('pull_request_number');
$commit = $this->getCommitId();
if (!empty($prNumber)) {
if ($allowCommentPullRequest) {
$helper->createPullRequestComment($repo, $prNumber, $commit, $file, $diffLineNumber, $message);
}
} else {
if ($allowCommentCommit) {
$helper->createCommitComment($repo, $commit, $file, $diffLineNumber, $message);
}
}
}
}
parent::reportError($builder, $plugin, $message, $severity, $file, $lineStart, $lineEnd);
}
/**
* Uses git diff to figure out what the diff line position is, based on the error line number.
*
* @param Builder $builder
* @param string $file
* @param integer $line
*
* @return integer|null
*/
protected function getDiffLineNumber(Builder $builder, $file, $line)
{
$builder->logExecOutput(false);
$line = (integer)$line;
$prNumber = $this->getExtra('pull_request_number');
$path = $builder->buildPath;
if (!empty($prNumber)) {
$builder->executeCommand('cd %s && git diff origin/%s "%s"', $path, $this->getBranch(), $file);
} else {
$commitId = $this->getCommitId();
$compare = empty($commitId) ? 'HEAD' : $commitId;
$builder->executeCommand('cd %s && git diff %s^^ "%s"', $path, $compare, $file);
}
$builder->logExecOutput(true);
$diff = $builder->getLastOutput();
$helper = new Diff();
$lines = $helper->getLinePositions($diff);
return isset($lines[$line]) ? $lines[$line] : null;
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace PHPCensor\Model\Build;
/**
* Gitlab Build Model
*
* @author André Cianfarani <a.cianfarani@c2is.fr>
*/
class GitlabBuild extends GitBuild
{
/**
* Get link to commit from another source (i.e. Github)
*/
public function getCommitLink()
{
$domain = $this->getProject()->getAccessInformation("domain");
return 'http://' . $domain . '/' . $this->getProject()->getReference() . '/commit/' . $this->getCommitId();
}
/**
* Get link to branch from another source (i.e. Github)
*/
public function getBranchLink()
{
$domain = $this->getProject()->getAccessInformation("domain");
return 'http://' . $domain . '/' . $this->getProject()->getReference() . '/tree/' . $this->getBranch();
}
/**
* Get link to specific file (and line) in a the repo's branch
*/
public function getFileLinkTemplate()
{
return sprintf(
'http://%s/%s/blob/%s/{FILE}#L{LINE}',
$this->getProject()->getAccessInformation("domain"),
$this->getProject()->getReference(),
$this->getCommitId()
);
}
/**
* Get the URL to be used to clone this remote repository.
*/
protected function getCloneUrl()
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
$user = $this->getProject()->getAccessInformation("user");
$domain = $this->getProject()->getAccessInformation("domain");
$port = $this->getProject()->getAccessInformation('port');
$url = $user . '@' . $domain . ':';
if (!empty($port)) {
$url .= $port . '/';
}
$url .= $this->getProject()->getReference() . '.git';
return $url;
}
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace PHPCensor\Model\Build;
/**
* GogsBuild Build Model
*/
class GogsBuild extends GitBuild
{
/**
* Get link to commit from Gogs repository
*/
public function getCommitLink()
{
return $this->getProject()->getReference() . '/commit/' . $this->getCommitId();
}
/**
* Get link to branch from Gogs repository
*/
public function getBranchLink()
{
return $this->getProject()->getReference() . '/src/' . $this->getBranch();
}
/**
* Get link to specific file (and line) in a the repo's branch
*/
public function getFileLinkTemplate()
{
return sprintf(
'%s/src/%s/{FILE}#L{LINE}',
$this->getProject()->getReference(),
$this->getCommitId()
);
}
}

101
src/Model/Build/HgBuild.php Normal file
View file

@ -0,0 +1,101 @@
<?php
namespace PHPCensor\Model\Build;
use PHPCensor\Model\Build;
use PHPCensor\Builder;
/**
* Mercurial Build Model
*
* @author Pavel Gopanenko <pavelgopanenko@gmail.com>
*/
class HgBuild extends Build
{
/**
* Get the URL to be used to clone this remote repository.
*/
protected function getCloneUrl()
{
return $this->getProject()->getReference();
}
/**
* Create a working copy by cloning, copying, or similar.
*/
public function createWorkingCopy(Builder $builder, $buildPath)
{
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
$success = $this->cloneBySsh($builder, $buildPath);
} else {
$success = $this->cloneByHttp($builder, $buildPath);
}
if (!$success) {
$builder->logFailure('Failed to clone remote hg repository.');
return false;
}
return $this->handleConfig($builder, $buildPath);
}
/**
* Use a HTTP-based hg clone.
*/
protected function cloneByHttp(Builder $builder, $cloneTo)
{
return $builder->executeCommand('hg clone %s "%s" -r %s', $this->getCloneUrl(), $cloneTo, $this->getBranch());
}
/**
* Use an SSH-based hg clone.
*
* @param Builder $builder
* @param string $cloneTo
*
* @return bool
*/
protected function cloneBySsh(Builder $builder, $cloneTo)
{
$keyFile = $this->writeSshKey($cloneTo);
// Do the hg clone:
$cmd = 'hg clone --ssh "ssh -i '.$keyFile.'" %s "%s" -r %s';
$success = $builder->executeCommand($cmd, $this->getCloneUrl(), $cloneTo, $this->getBranch());
if ($success) {
$success = $this->postCloneSetup($builder, $cloneTo);
}
// Remove the key file:
unlink($keyFile);
return $success;
}
/**
* Handle post-clone tasks (switching branch, etc.)
*
* @param Builder $builder
* @param string $cloneTo
* @param array $extra
*
* @return bool
*/
protected function postCloneSetup(Builder $builder, $cloneTo, array $extra = null)
{
$success = true;
$commitId = $this->getCommitId();
// Allow switching to a specific branch:
if (!empty($commitId)) {
$cmd = 'cd "%s" && hg checkout %s';
$success = $builder->executeCommand($cmd, $cloneTo, $this->getBranch());
}
return $success;
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace PHPCensor\Model\Build;
use PHPCensor\Model\Build;
use PHPCensor\Builder;
/**
* Local Build Model
*
* @author Dan Cryer <dan@block8.co.uk>
*/
class LocalBuild extends Build
{
/**
* Create a working copy by cloning, copying, or similar.
*/
public function createWorkingCopy(Builder $builder, $buildPath)
{
$reference = $this->getProject()->getReference();
$reference = substr($reference, -1) == '/' ? substr($reference, 0, -1) : $reference;
$buildPath = substr($buildPath, 0, -1);
// If there's a /config file in the reference directory, it is probably a bare repository
// which we'll extract into our build path directly.
if (is_file($reference.'/config') && $this->handleBareRepository($builder, $reference, $buildPath) === true) {
return $this->handleConfig($builder, $buildPath) !== false;
}
$configHandled = $this->handleConfig($builder, $reference);
if ($configHandled === false) {
return false;
}
$buildSettings = $builder->getConfig('build_settings');
if (isset($buildSettings['prefer_symlink']) && $buildSettings['prefer_symlink'] === true) {
return $this->handleSymlink($builder, $reference, $buildPath);
} else {
$cmd = 'cp -Rf "%s" "%s/"';
$builder->executeCommand($cmd, $reference, $buildPath);
}
return true;
}
/**
* Check if this is a "bare" git repository, and if so, unarchive it.
* @param Builder $builder
* @param $reference
* @param $buildPath
* @return bool
*/
protected function handleBareRepository(Builder $builder, $reference, $buildPath)
{
$gitConfig = parse_ini_file($reference.'/config', true);
// If it is indeed a bare repository, then extract it into our build path:
if ($gitConfig['core']['bare']) {
$cmd = 'mkdir %2$s; git --git-dir="%1$s" archive %3$s | tar -x -C "%2$s"';
$builder->executeCommand($cmd, $reference, $buildPath, $this->getBranch());
return true;
}
return false;
}
/**
* Create a symlink if required.
* @param Builder $builder
* @param $reference
* @param $buildPath
* @return bool
*/
protected function handleSymlink(Builder $builder, $reference, $buildPath)
{
if (is_link($buildPath) && is_file($buildPath)) {
unlink($buildPath);
}
$builder->log(sprintf('Symlinking: %s to %s', $reference, $buildPath));
if (!symlink($reference, $buildPath)) {
$builder->logFailure('Failed to symlink.');
return false;
}
return true;
}
}

View file

@ -0,0 +1,127 @@
<?php
namespace PHPCensor\Model\Build;
use PHPCensor\Model\Build;
use PHPCensor\Builder;
/**
* Remote Subversion Build Model
*
* @author Nadir Dzhilkibaev <imam.sharif@gmail.com>
*/
class SvnBuild extends Build
{
protected $svnCommand = 'svn export -q --non-interactive ';
/**
* Get the URL to be used to clone this remote repository.
*/
protected function getCloneUrl()
{
$url = rtrim($this->getProject()->getReference(), '/') . '/';
$branch = ltrim($this->getBranch(), '/');
// For empty default branch or default branch name like "/trunk" or "trunk" (-> "trunk")
if (empty($branch) || $branch == 'trunk') {
$url .= 'trunk';
// For default branch with standard default branch directory ("branches") like "/branch-1" or "branch-1"
// (-> "branches/branch-1")
} elseif (false === strpos($branch, '/')) {
$url .= 'branches/' . $branch;
// For default branch with non-standard branch directory like "/branch/branch-1" or "branch/branch-1"
// (-> "branch/branch-1")
} else {
$url .= $branch;
}
return $url;
}
/**
* @param Builder $builder
*
* @return void
*/
protected function extendSvnCommandFromConfig(Builder $builder)
{
$cmd = $this->svnCommand;
$svn = $builder->getConfig('svn');
if ($svn) {
foreach ($svn as $key => $value) {
$cmd .= " --$key $value ";
}
}
$depth = $builder->getConfig('clone_depth');
if (!is_null($depth)) {
$cmd .= ' --depth ' . intval($depth) . ' ';
}
$this->svnCommand = $cmd;
}
/**
* Create a working copy by cloning, copying, or similar.
*/
public function createWorkingCopy(Builder $builder, $buildPath)
{
$this->handleConfig($builder, $buildPath);
$this->extendSvnCommandFromConfig($builder);
$key = trim($this->getProject()->getSshPrivateKey());
if (!empty($key)) {
$success = $this->cloneBySsh($builder, $buildPath);
} else {
$success = $this->cloneByHttp($builder, $buildPath);
}
if (!$success) {
$builder->logFailure('Failed to export remote subversion repository.');
return false;
}
return $this->handleConfig($builder, $buildPath);
}
/**
* Use an HTTP-based svn export.
*/
protected function cloneByHttp(Builder $builder, $cloneTo)
{
$cmd = $this->svnCommand;
if (!empty($this->getCommitId())) {
$cmd .= ' -r %s %s "%s"';
$success = $builder->executeCommand($cmd, $this->getCommitId(), $this->getCloneUrl(), $cloneTo);
} else {
$cmd .= ' %s "%s"';
$success = $builder->executeCommand($cmd, $this->getCloneUrl(), $cloneTo);
}
return $success;
}
/**
* Use an SSH-based svn export.
*/
protected function cloneBySsh(Builder $builder, $cloneTo)
{
$cmd = $this->svnCommand . ' %s "%s"';
$keyFile = $this->writeSshKey($cloneTo);
$sshWrapper = $this->writeSshWrapper($cloneTo, $keyFile);
$cmd = 'export SVN_SSH="' . $sshWrapper . '" && ' . $cmd;
$success = $builder->executeCommand($cmd, $this->getCloneUrl(), $cloneTo);
// Remove the key file and svn wrapper:
unlink($keyFile);
unlink($sshWrapper);
return $success;
}
}

472
src/Model/BuildError.php Normal file
View file

@ -0,0 +1,472 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Model;
use PHPCensor\Store\Factory;
class BuildError extends Model
{
const SEVERITY_CRITICAL = 0;
const SEVERITY_HIGH = 1;
const SEVERITY_NORMAL = 2;
const SEVERITY_LOW = 3;
/**
* @var string
*/
protected $tableName = 'build_error';
/**
* @var array
*/
protected $data = [
'id' => null,
'build_id' => null,
'plugin' => null,
'file' => null,
'line_start' => null,
'line_end' => null,
'severity' => null,
'message' => null,
'create_date' => null,
'hash' => null,
'is_new' => null,
];
/**
* @var array
*/
protected $getters = [
// Direct property getters:
'id' => 'getId',
'build_id' => 'getBuildId',
'plugin' => 'getPlugin',
'file' => 'getFile',
'line_start' => 'getLineStart',
'line_end' => 'getLineEnd',
'severity' => 'getSeverity',
'message' => 'getMessage',
'create_date' => 'getCreateDate',
'hash' => 'getHash',
'is_new' => 'getIsNew',
// Foreign key getters:
'Build' => 'getBuild',
];
/**
* @var array
*/
protected $setters = [
// Direct property setters:
'id' => 'setId',
'build_id' => 'setBuildId',
'plugin' => 'setPlugin',
'file' => 'setFile',
'line_start' => 'setLineStart',
'line_end' => 'setLineEnd',
'severity' => 'setSeverity',
'message' => 'setMessage',
'create_date' => 'setCreateDate',
'hash' => 'setHash',
'is_new' => 'setIsNew',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @return integer
*/
public function getBuildId()
{
$rtn = $this->data['build_id'];
return $rtn;
}
/**
* @return string
*/
public function getPlugin()
{
$rtn = $this->data['plugin'];
return $rtn;
}
/**
* @return string
*/
public function getFile()
{
$rtn = $this->data['file'];
return $rtn;
}
/**
* @return integer
*/
public function getLineStart()
{
$rtn = $this->data['line_start'];
return $rtn;
}
/**
* @return integer
*/
public function getLineEnd()
{
$rtn = $this->data['line_end'];
return $rtn;
}
/**
* @return integer
*/
public function getSeverity()
{
$rtn = $this->data['severity'];
return $rtn;
}
/**
* @return string
*/
public function getMessage()
{
$rtn = $this->data['message'];
return $rtn;
}
/**
* @return \DateTime
*/
public function getCreateDate()
{
$rtn = $this->data['create_date'];
if (!empty($rtn)) {
$rtn = new \DateTime($rtn);
}
return $rtn;
}
/**
* @return string
*/
public function getHash()
{
$rtn = (string)$this->data['hash'];
return $rtn;
}
/**
* @return string
*/
public function getIsNew()
{
$rtn = $this->data['is_new'];
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @param integer $value
*/
public function setBuildId($value)
{
$this->validateNotNull('build_id', $value);
$this->validateInt('build_id', $value);
if ($this->data['build_id'] === $value) {
return;
}
$this->data['build_id'] = $value;
$this->setModified('build_id');
}
/**
* @param string $value
*/
public function setPlugin($value)
{
$this->validateNotNull('plugin', $value);
$this->validateString('plugin', $value);
if ($this->data['plugin'] === $value) {
return;
}
$this->data['plugin'] = $value;
$this->setModified('plugin');
}
/**
* @param string $value
*/
public function setFile($value)
{
$this->validateString('file', $value);
if ($this->data['file'] === $value) {
return;
}
$this->data['file'] = $value;
$this->setModified('file');
}
/**
* @param integer $value
*/
public function setLineStart($value)
{
$this->validateInt('line_start', $value);
if ($this->data['line_start'] === $value) {
return;
}
$this->data['line_start'] = $value;
$this->setModified('line_start');
}
/**
* @param integer $value
*/
public function setLineEnd($value)
{
$this->validateInt('line_end', $value);
if ($this->data['line_end'] === $value) {
return;
}
$this->data['line_end'] = $value;
$this->setModified('line_end');
}
/**
* @param integer $value
*/
public function setSeverity($value)
{
$this->validateNotNull('severity', $value);
$this->validateInt('severity', $value);
if ($this->data['severity'] === $value) {
return;
}
$this->data['severity'] = $value;
$this->setModified('severity');
}
/**
* @param string $value
*/
public function setMessage($value)
{
$this->validateNotNull('message', $value);
$this->validateString('message', $value);
if ($this->data['message'] === $value) {
return;
}
$this->data['message'] = $value;
$this->setModified('message');
}
/**
* @param \DateTime $value
*/
public function setCreateDate(\DateTime $value)
{
$this->validateNotNull('create_date', $value);
$stringValue = $value->format('Y-m-d H:i:s');
if ($this->data['create_date'] === $stringValue) {
return;
}
$this->data['create_date'] = $stringValue;
$this->setModified('create_date');
}
/**
* @param string $value
*/
public function setHash($value)
{
$this->validateNotNull('hash', $value);
$this->validateString('hash', $value);
if ($this->data['hash'] === $value) {
return;
}
$this->data['hash'] = $value;
$this->setModified('hash');
}
/**
* @param integer $value
*/
public function setIsNew($value)
{
$this->validateNotNull('is_new', $value);
$this->validateInt('is_new', $value);
if ($this->data['is_new'] === $value) {
return;
}
$this->data['is_new'] = $value;
$this->setModified('is_new');
}
/**
* Get the Build model for this BuildError by Id.
*
* @return \PHPCensor\Model\Build|null
*/
public function getBuild()
{
$buildId = $this->getBuildId();
if (empty($buildId)) {
return null;
}
return Factory::getStore('Build')->getById($buildId);
}
/**
* Get the language string key for this error's severity level.
*
* @return string
*/
public function getSeverityString()
{
switch ($this->getSeverity()) {
case self::SEVERITY_CRITICAL:
return 'critical';
case self::SEVERITY_HIGH:
return 'high';
case self::SEVERITY_NORMAL:
return 'normal';
case self::SEVERITY_LOW:
return 'low';
}
}
/**
* Get the language string key for this error's severity level.
*
* @param integer $severity
*
* @return string
*/
public static function getSeverityName($severity)
{
switch ($severity) {
case self::SEVERITY_CRITICAL:
return 'critical';
case self::SEVERITY_HIGH:
return 'high';
case self::SEVERITY_NORMAL:
return 'normal';
case self::SEVERITY_LOW:
return 'low';
}
}
/**
* @param string $plugin
* @param string $file
* @param integer $lineStart
* @param integer $lineEnd
* @param integer $severity
* @param string $message
*
* @return string
*/
public static function generateHash($plugin, $file, $lineStart, $lineEnd, $severity, $message)
{
return md5($plugin . $file . $lineStart . $lineEnd . $severity . $message);
}
/**
* Get the class to apply to HTML elements representing this error.
*
* @return string
*/
public function getSeverityClass()
{
switch ($this->getSeverity()) {
case self::SEVERITY_CRITICAL:
return 'danger';
case self::SEVERITY_HIGH:
return 'warning';
case self::SEVERITY_NORMAL:
return 'info';
case self::SEVERITY_LOW:
return 'default';
}
}
}

172
src/Model/BuildMeta.php Normal file
View file

@ -0,0 +1,172 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Model;
use PHPCensor\Store\Factory;
class BuildMeta extends Model
{
/**
* @var string
*/
protected $tableName = 'build_meta';
/**
* @var array
*/
protected $data = [
'id' => null,
'build_id' => null,
'meta_key' => null,
'meta_value' => null,
];
/**
* @var array
*/
protected $getters = [
// Direct property getters:
'id' => 'getId',
'build_id' => 'getBuildId',
'meta_key' => 'getMetaKey',
'meta_value' => 'getMetaValue',
// Foreign key getters:
'Build' => 'getBuild',
];
/**
* @var array
*/
protected $setters = [
// Direct property setters:
'id' => 'setId',
'build_id' => 'setBuildId',
'meta_key' => 'setMetaKey',
'meta_value' => 'setMetaValue',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @return integer
*/
public function getBuildId()
{
$rtn = $this->data['build_id'];
return $rtn;
}
/**
* @return string
*/
public function getMetaKey()
{
$rtn = $this->data['meta_key'];
return $rtn;
}
/**
* @return string
*/
public function getMetaValue()
{
$rtn = $this->data['meta_value'];
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @param integer $value
*/
public function setBuildId($value)
{
$this->validateNotNull('build_id', $value);
$this->validateInt('build_id', $value);
if ($this->data['build_id'] === $value) {
return;
}
$this->data['build_id'] = $value;
$this->setModified('build_id');
}
/**
* @param string $value
*/
public function setMetaKey($value)
{
$this->validateNotNull('meta_key', $value);
$this->validateString('meta_key', $value);
if ($this->data['meta_key'] === $value) {
return;
}
$this->data['meta_key'] = $value;
$this->setModified('meta_key');
}
/**
* @param string $value
*/
public function setMetaValue($value)
{
$this->validateNotNull('meta_value', $value);
$this->validateString('meta_value', $value);
if ($this->data['meta_value'] === $value) {
return;
}
$this->data['meta_value'] = $value;
$this->setModified('meta_value');
}
/**
* Get the Build model for this BuildMeta by Id.
*
* @return \PHPCensor\Model\Build
*/
public function getBuild()
{
$buildId = $this->getBuildId();
if (empty($buildId)) {
return null;
}
return Factory::getStore('Build')->getById($buildId);
}
}

151
src/Model/Environment.php Normal file
View file

@ -0,0 +1,151 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Model;
class Environment extends Model
{
/**
* @var string
*/
protected $tableName = 'environment';
/**
* @var array
*/
protected $data = [
'id' => null,
'project_id' => null,
'name' => null,
'branches' => null,
];
/**
* @var array
*/
protected $getters = [
'id' => 'getId',
'project_id' => 'getProjectId',
'name' => 'getName',
'branches' => 'getBranches',
];
/**
* @var array
*/
protected $setters = [
'id' => 'setId',
'project_id' => 'setProjectId',
'name' => 'setName',
'branches' => 'setBranches',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @return integer
*/
public function getProjectId()
{
$rtn = $this->data['project_id'];
return $rtn;
}
/**
* @return string
*/
public function getName()
{
$rtn = $this->data['name'];
return $rtn;
}
/**
* @return array
*/
public function getBranches()
{
$rtn = array_filter(array_map('trim', explode("\n", $this->data['branches'])));
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @param integer $value
*/
public function setProjectId($value)
{
$this->validateNotNull('project_id', $value);
$this->validateInt('project_id', $value);
if ($this->data['project_id'] === $value) {
return;
}
$this->data['project_id'] = $value;
$this->setModified('project_id');
}
/**
* @param string $value
*/
public function setName($value)
{
$this->validateNotNull('name', $value);
$this->validateString('name', $value);
if ($this->data['name'] === $value) {
return;
}
$this->data['name'] = $value;
$this->setModified('name');
}
/**
* @param array $value
*/
public function setBranches($value)
{
$this->validateNotNull('branches', $value);
$value = implode("\n", $value);
if ($this->data['branches'] === $value) {
return;
}
$this->data['branches'] = $value;
$this->setModified('branches');
}
}

811
src/Model/Project.php Normal file
View file

@ -0,0 +1,811 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Model;
use PHPCensor\Store\Factory;
use PHPCensor\Store\EnvironmentStore;
use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Yaml\Dumper as YamlDumper;
/**
* @author Dan Cryer <dan@block8.co.uk>
*/
class Project extends Model
{
/**
* @var string
*/
protected $tableName = 'project';
/**
* @var array
*/
protected $data = [
'id' => null,
'title' => null,
'reference' => null,
'branch' => null,
'default_branch_only' => null,
'ssh_private_key' => null,
'type' => null,
'access_information' => null,
'last_commit' => null,
'build_config' => null,
'ssh_public_key' => null,
'allow_public_status' => null,
'archived' => null,
'group_id' => null,
'create_date' => null,
'user_id' => 0,
];
/**
* @var array
*/
protected $getters = [
// Direct property getters:
'id' => 'getId',
'title' => 'getTitle',
'reference' => 'getReference',
'branch' => 'getBranch',
'default_branch_only' => 'getDefaultBranchOnly',
'ssh_private_key' => 'getSshPrivateKey',
'type' => 'getType',
'access_information' => 'getAccessInformation',
'last_commit' => 'getLastCommit',
'build_config' => 'getBuildConfig',
'ssh_public_key' => 'getSshPublicKey',
'allow_public_status' => 'getAllowPublicStatus',
'archived' => 'getArchived',
'group_id' => 'getGroupId',
'create_date' => 'getCreateDate',
'user_id' => 'getUserId',
// Foreign key getters:
'Group' => 'getGroup',
];
/**
* @var array
*/
protected $setters = [
// Direct property setters:
'id' => 'setId',
'title' => 'setTitle',
'reference' => 'setReference',
'branch' => 'setBranch',
'default_branch_only' => 'setDefaultBranchOnly',
'ssh_private_key' => 'setSshPrivateKey',
'type' => 'setType',
'access_information' => 'setAccessInformation',
'last_commit' => 'setLastCommit',
'build_config' => 'setBuildConfig',
'ssh_public_key' => 'setSshPublicKey',
'allow_public_status' => 'setAllowPublicStatus',
'archived' => 'setArchived',
'group_id' => 'setGroupId',
'create_date' => 'setCreateDate',
'user_id' => 'setUserId',
// Foreign key setters:
'Group' => 'setGroup',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @return string
*/
public function getTitle()
{
$rtn = $this->data['title'];
return $rtn;
}
/**
* @return string
*/
public function getReference()
{
$rtn = $this->data['reference'];
return $rtn;
}
/**
* @return string
*/
public function getSshPrivateKey()
{
$rtn = $this->data['ssh_private_key'];
return $rtn;
}
/**
* @return string
*/
public function getType()
{
$rtn = $this->data['type'];
return $rtn;
}
/**
* @return string
*/
public function getLastCommit()
{
$rtn = $this->data['last_commit'];
return $rtn;
}
/**
* @return string
*/
public function getBuildConfig()
{
$rtn = $this->data['build_config'];
return $rtn;
}
/**
* @return string
*/
public function getSshPublicKey()
{
$rtn = $this->data['ssh_public_key'];
return $rtn;
}
/**
* @return integer
*/
public function getAllowPublicStatus()
{
$rtn = $this->data['allow_public_status'];
return $rtn;
}
/**
* @return integer
*/
public function getArchived()
{
$rtn = $this->data['archived'];
return $rtn;
}
/**
* @return integer
*/
public function getGroupId()
{
$rtn = $this->data['group_id'];
return $rtn;
}
/**
* @return integer
*/
public function getDefaultBranchOnly()
{
$rtn = $this->data['default_branch_only'];
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @param string $value
*/
public function setTitle($value)
{
$this->validateNotNull('title', $value);
$this->validateString('title', $value);
if ($this->data['title'] === $value) {
return;
}
$this->data['title'] = $value;
$this->setModified('title');
}
/**
* @param string $value
*/
public function setReference($value)
{
$this->validateNotNull('reference', $value);
$this->validateString('reference', $value);
if ($this->data['reference'] === $value) {
return;
}
$this->data['reference'] = $value;
$this->setModified('reference');
}
/**
* @param string $value
*/
public function setBranch($value)
{
$this->validateNotNull('branch', $value);
$this->validateString('branch', $value);
if ($this->data['branch'] === $value) {
return;
}
$this->data['branch'] = $value;
$this->setModified('branch');
}
/**
* @param integer $value
*/
public function setDefaultBranchOnly($value)
{
$this->validateNotNull('default_branch_only', $value);
$this->validateInt('default_branch_only', $value);
if ($this->data['default_branch_only'] === $value) {
return;
}
$this->data['default_branch_only'] = $value;
$this->setModified('default_branch_only');
}
/**
* @param string $value
*/
public function setSshPrivateKey($value)
{
$this->validateString('ssh_private_key', $value);
if ($this->data['ssh_private_key'] === $value) {
return;
}
$this->data['ssh_private_key'] = $value;
$this->setModified('ssh_private_key');
}
/**
* @param string $value
*/
public function setType($value)
{
$this->validateNotNull('type', $value);
$this->validateString('type', $value);
if ($this->data['type'] === $value) {
return;
}
$this->data['type'] = $value;
$this->setModified('type');
}
/**
* @param string $value
*/
public function setLastCommit($value)
{
$this->validateString('last_commit', $value);
if ($this->data['last_commit'] === $value) {
return;
}
$this->data['last_commit'] = $value;
$this->setModified('last_commit');
}
/**
* @param string $value
*/
public function setBuildConfig($value)
{
$this->validateString('build_config', $value);
if ($this->data['build_config'] === $value) {
return;
}
$this->data['build_config'] = $value;
$this->setModified('build_config');
}
/**
* @param string $value
*/
public function setSshPublicKey($value)
{
$this->validateString('ssh_public_key', $value);
if ($this->data['ssh_public_key'] === $value) {
return;
}
$this->data['ssh_public_key'] = $value;
$this->setModified('ssh_public_key');
}
/**
* @param integer $value
*/
public function setAllowPublicStatus($value)
{
$this->validateNotNull('allow_public_status', $value);
$this->validateInt('allow_public_status', $value);
if ($this->data['allow_public_status'] === $value) {
return;
}
$this->data['allow_public_status'] = $value;
$this->setModified('allow_public_status');
}
/**
* @param integer $value
*/
public function setArchived($value)
{
$this->validateNotNull('archived', $value);
$this->validateInt('archived', $value);
if ($this->data['archived'] === $value) {
return;
}
$this->data['archived'] = $value;
$this->setModified('archived');
}
/**
* @param integer $value
*/
public function setGroupId($value)
{
$this->validateNotNull('group_id', $value);
$this->validateInt('group_id', $value);
if ($this->data['group_id'] === $value) {
return;
}
$this->data['group_id'] = $value;
$this->setModified('group_id');
}
/**
* Get the ProjectGroup model for this Project by Id.
*
* @return \PHPCensor\Model\ProjectGroup
*/
public function getGroup()
{
$groupId = $this->getGroupId();
if (empty($groupId)) {
return null;
}
return Factory::getStore('ProjectGroup')->getById($groupId);
}
/**
* Get Build models by ProjectId for this Project.
*
* @return \PHPCensor\Model\Build[]
*/
public function getProjectBuilds()
{
return Factory::getStore('Build')->getByProjectId($this->getId());
}
/**
* Return the latest build from a specific branch, of a specific status, for this project.
*
* @param string $branch
* @param null $status
*
* @return mixed|null
*/
public function getLatestBuild($branch = 'master', $status = null)
{
$criteria = ['branch' => $branch, 'project_id' => $this->getId()];
if (isset($status)) {
$criteria['status'] = $status;
}
$order = ['id' => 'DESC'];
$builds = Factory::getStore('Build')->getWhere($criteria, 1, 0, $order);
if (is_array($builds['items']) && count($builds['items'])) {
$latest = array_shift($builds['items']);
if (isset($latest) && $latest instanceof Build) {
return $latest;
}
}
return null;
}
/**
* Return the previous build from a specific branch, for this project.
*
* @param string $branch
*
* @return mixed|null
*/
public function getPreviousBuild($branch = 'master')
{
$criteria = ['branch' => $branch, 'project_id' => $this->getId()];
$order = ['id' => 'DESC'];
$builds = Factory::getStore('Build')->getWhere($criteria, 1, 1, $order);
if (is_array($builds['items']) && count($builds['items'])) {
$previous = array_shift($builds['items']);
if (isset($previous) && $previous instanceof Build) {
return $previous;
}
}
return null;
}
/**
* @param string|array $value
*/
public function setAccessInformation($value)
{
if (is_array($value)) {
$value = json_encode($value);
}
$this->validateString('access_information', $value);
if ($this->data['access_information'] === $value) {
return;
}
$this->data['access_information'] = $value;
$this->setModified('access_information');
}
/**
* Get this project's access_information data. Pass a specific key or null for all data.
*
* @param string|null $key
*
* @return mixed|null|string
*/
public function getAccessInformation($key = null)
{
$info = $this->data['access_information'];
// Handle old-format (serialized) access information first:
if (!empty($info) && !in_array(substr($info, 0, 1), ['{', '['])) {
$data = unserialize($info);
} else {
$data = json_decode($info, true);
}
if (is_null($key)) {
$rtn = $data;
} elseif (isset($data[$key])) {
$rtn = $data[$key];
} else {
$rtn = null;
}
return $rtn;
}
/**
* @return \DateTime
*/
public function getCreateDate()
{
$rtn = $this->data['create_date'];
if (!empty($rtn)) {
$rtn = new \DateTime($rtn);
}
return $rtn;
}
/**
* @param \DateTime $value
*/
public function setCreateDate(\DateTime $value)
{
$stringValue = $value->format('Y-m-d H:i:s');
if ($this->data['create_date'] === $stringValue) {
return;
}
$this->data['create_date'] = $stringValue;
$this->setModified('create_date');
}
/**
* @return string
*/
public function getUserId()
{
$rtn = $this->data['user_id'];
return (integer)$rtn;
}
/**
* @param integer $value
*/
public function setUserId($value)
{
$this->validateNotNull('user_id', $value);
$this->validateInt('user_id', $value);
if ($this->data['user_id'] === $value) {
return;
}
$this->data['user_id'] = $value;
$this->setModified('user_id');
}
/**
* Get the value of branch.
*
* @return string
*/
public function getBranch()
{
if (empty($this->data['branch'])) {
$projectType = $this->getType();
switch ($projectType) {
case 'hg':
$branch = 'default';
break;
case 'svn':
$branch = 'trunk';
break;
default:
$branch = 'master';
}
return $branch;
} else {
return $this->data['branch'];
}
}
/**
* Return the name of a FontAwesome icon to represent this project, depending on its type.
*
* @return string
*/
public function getIcon()
{
switch ($this->getType()) {
case 'github':
$icon = 'github';
break;
case 'bitbucket':
case 'bitbucket-hg':
$icon = 'bitbucket';
break;
case 'git':
case 'gitlab':
case 'gogs':
default:
$icon = 'code-fork';
break;
}
return $icon;
}
/**
* @return EnvironmentStore
*/
protected function getEnvironmentStore()
{
/** @var EnvironmentStore $store */
$store = Factory::getStore('Environment');
return $store;
}
/**
* Get Environments
*
* @return array contain items with \PHPCensor\Model\Environment
*/
public function getEnvironmentsObjects()
{
$projectId = $this->getId();
if (empty($projectId)) {
return null;
}
return $this->getEnvironmentStore()->getByProjectId($projectId);
}
/**
* Get Environments
*
* @return string[]
*/
public function getEnvironmentsNames()
{
$environments = $this->getEnvironmentsObjects();
$environments_names = [];
foreach($environments['items'] as $environment) {
/** @var Environment $environment */
$environments_names[] = $environment->getName();
}
return $environments_names;
}
/**
* Get Environments
*
* @return string yaml
*/
public function getEnvironments()
{
$environments = $this->getEnvironmentsObjects();
$environments_config = [];
foreach($environments['items'] as $environment) {
/** @var Environment $environment */
$environments_config[$environment->getName()] = $environment->getBranches();
}
$yaml_dumper = new YamlDumper();
$value = $yaml_dumper->dump($environments_config, 10, 0, true, false);
return $value;
}
/**
* Set Environments
*
* @param string $value yaml
*/
public function setEnvironments($value)
{
$yaml_parser = new YamlParser();
$environments_config = $yaml_parser->parse($value);
$environments_names = !empty($environments_config) ? array_keys($environments_config) : [];
$current_environments = $this->getEnvironmentsObjects();
$store = $this->getEnvironmentStore();
foreach ($current_environments['items'] as $environment) {
/** @var Environment $environment */
$key = array_search($environment->getName(), $environments_names);
if ($key !== false) {
// already exist
unset($environments_names[$key]);
$environment->setBranches(!empty($environments_config[$environment->getName()]) ? $environments_config[$environment->getName()] : []);
$store->save($environment);
} else {
// remove
$store->delete($environment);
}
}
if (!empty($environments_names)) {
// add
foreach ($environments_names as $environment_name) {
$environment = new Environment();
$environment->setProjectId($this->getId());
$environment->setName($environment_name);
$environment->setBranches(!empty($environments_config[$environment->getName()]) ? $environments_config[$environment->getName()] : []);
$store->save($environment);
}
}
}
/**
* @param string $branch
*
* @return string[]
*/
public function getEnvironmentsNamesByBranch($branch)
{
$environments_names = [];
$environments = $this->getEnvironmentsObjects();
$default_branch = ($branch == $this->getBranch());
foreach($environments['items'] as $environment) {
/** @var Environment $environment */
if ($default_branch || in_array($branch, $environment->getBranches())) {
$environments_names[] = $environment->getName();
}
}
return $environments_names;
}
/**
* @param string $environment_name
*
* @return string[]
*/
public function getBranchesByEnvironment($environment_name)
{
$branches = [];
$environments = $this->getEnvironmentsObjects();
foreach($environments['items'] as $environment) {
/** @var Environment $environment */
if ($environment_name == $environment->getName()) {
return $environment->getBranches();
}
}
return $branches;
}
}

165
src/Model/ProjectGroup.php Normal file
View file

@ -0,0 +1,165 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Model;
use PHPCensor\Store\Factory;
class ProjectGroup extends Model
{
/**
* @var string
*/
protected $tableName = 'project_group';
/**
* @var array
*/
protected $data = [
'id' => null,
'title' => null,
'create_date' => null,
'user_id' => 0,
];
/**
* @var array
*/
protected $getters = [
'id' => 'getId',
'title' => 'getTitle',
'create_date' => 'getCreateDate',
'user_id' => 'getUserId',
];
/**
* @var array
*/
protected $setters = [
'id' => 'setId',
'title' => 'setTitle',
'create_date' => 'setCreateDate',
'user_id' => 'setUserId',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @return string
*/
public function getTitle()
{
$rtn = $this->data['title'];
return $rtn;
}
/**
* @param string $value
*/
public function setTitle($value)
{
$this->validateNotNull('title', $value);
$this->validateString('title', $value);
if ($this->data['title'] === $value) {
return;
}
$this->data['title'] = $value;
$this->setModified('title');
}
/**
* @return \DateTime
*/
public function getCreateDate()
{
$rtn = $this->data['create_date'];
if (!empty($rtn)) {
$rtn = new \DateTime($rtn);
}
return $rtn;
}
/**
* @param \DateTime $value
*/
public function setCreateDate(\DateTime $value)
{
$stringValue = $value->format('Y-m-d H:i:s');
if ($this->data['create_date'] === $stringValue) {
return;
}
$this->data['create_date'] = $stringValue;
$this->setModified('create_date');
}
/**
* @return string
*/
public function getUserId()
{
$rtn = $this->data['user_id'];
return (integer)$rtn;
}
/**
* @param integer $value
*/
public function setUserId($value)
{
$this->validateNotNull('user_id', $value);
$this->validateInt('user_id', $value);
if ($this->data['user_id'] === $value) {
return;
}
$this->data['user_id'] = $value;
$this->setModified('user_id');
}
/**
* Get Project models by GroupId for this ProjectGroup.
*
* @return \PHPCensor\Model\Project[]
*/
public function getGroupProjects()
{
return Factory::getStore('Project')->getByGroupId($this->getId(), false);
}
}

340
src/Model/User.php Normal file
View file

@ -0,0 +1,340 @@
<?php
namespace PHPCensor\Model;
use PHPCensor\Config;
use PHPCensor\Model;
/**
* @author Dan Cryer <dan@block8.co.uk>
*/
class User extends Model
{
/**
* @var string
*/
protected $tableName = 'user';
/**
* @var array
*/
protected $data = [
'id' => null,
'email' => null,
'hash' => null,
'is_admin' => null,
'name' => null,
'language' => null,
'per_page' => null,
'provider_key' => null,
'provider_data' => null,
'remember_key' => null,
];
/**
* @var array
*/
protected $getters = [
'id' => 'getId',
'email' => 'getEmail',
'hash' => 'getHash',
'is_admin' => 'getIsAdmin',
'name' => 'getName',
'language' => 'getLanguage',
'per_page' => 'getPerPage',
'provider_key' => 'getProviderKey',
'provider_data' => 'getProviderData',
'remember_key' => 'getRememberKey',
];
/**
* @var array
*/
protected $setters = [
'id' => 'setId',
'email' => 'setEmail',
'hash' => 'setHash',
'is_admin' => 'setIsAdmin',
'name' => 'setName',
'language' => 'setLanguage',
'per_page' => 'setPerPage',
'provider_key' => 'setProviderKey',
'provider_data' => 'setProviderData',
'remember_key' => 'setRememberKey',
];
/**
* @return integer
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* @return string
*/
public function getEmail()
{
$rtn = $this->data['email'];
return $rtn;
}
/**
* @return string
*/
public function getHash()
{
$rtn = $this->data['hash'];
return $rtn;
}
/**
* @return string
*/
public function getName()
{
$rtn = $this->data['name'];
return $rtn;
}
/**
* @return integer
*/
public function getIsAdmin()
{
$rtn = $this->data['is_admin'];
return $rtn;
}
/**
* @return string
*/
public function getProviderKey()
{
$rtn = $this->data['provider_key'];
return $rtn;
}
/**
* @return string
*/
public function getProviderData()
{
$rtn = $this->data['provider_data'];
return $rtn;
}
/**
* @return string
*/
public function getRememberKey()
{
$rtn = $this->data['remember_key'];
return $rtn;
}
/**
* @return string
*/
public function getLanguage()
{
$rtn = $this->data['language'];
return $rtn;
}
/**
* @return string
*/
public function getPerPage()
{
$rtn = $this->data['per_page'];
return $rtn;
}
/**
* @param integer $value
*/
public function setId($value)
{
$this->validateNotNull('id', $value);
$this->validateInt('id', $value);
if ($this->data['id'] === $value) {
return;
}
$this->data['id'] = $value;
$this->setModified('id');
}
/**
* @param string $value
*/
public function setEmail($value)
{
$this->validateNotNull('email', $value);
$this->validateString('email', $value);
if ($this->data['email'] === $value) {
return;
}
$this->data['email'] = $value;
$this->setModified('email');
}
/**
* @param string $value
*/
public function setHash($value)
{
$this->validateNotNull('hash', $value);
$this->validateString('hash', $value);
if ($this->data['hash'] === $value) {
return;
}
$this->data['hash'] = $value;
$this->setModified('hash');
}
/**
* @param string $value
*/
public function setName($value)
{
$this->validateNotNull('name', $value);
$this->validateString('name', $value);
if ($this->data['name'] === $value) {
return;
}
$this->data['name'] = $value;
$this->setModified('name');
}
/**
* @param integer $value
*/
public function setIsAdmin($value)
{
$this->validateNotNull('is_admin', $value);
$this->validateInt('is_admin', $value);
if ($this->data['is_admin'] === $value) {
return;
}
$this->data['is_admin'] = $value;
$this->setModified('is_admin');
}
/**
* @param string $value
*/
public function setProviderKey($value)
{
$this->validateNotNull('provider_key', $value);
$this->validateString('provider_key', $value);
if ($this->data['provider_key'] === $value) {
return;
}
$this->data['provider_key'] = $value;
$this->setModified('provider_key');
}
/**
* @param string $value
*/
public function setProviderData($value)
{
$this->validateString('provider_data', $value);
if ($this->data['provider_data'] === $value) {
return;
}
$this->data['provider_data'] = $value;
$this->setModified('provider_data');
}
/**
* @param string $value
*/
public function setRememberKey($value)
{
$this->validateString('remember_key', $value);
if ($this->data['remember_key'] === $value) {
return;
}
$this->data['remember_key'] = $value;
$this->setModified('remember_key');
}
/**
* @param string $value
*/
public function setLanguage($value)
{
if ($this->data['language'] === $value) {
return;
}
$this->data['language'] = $value;
$this->setModified('language');
}
/**
* @param string $value
*/
public function setPerPage($value)
{
if ($this->data['per_page'] === $value) {
return;
}
$this->data['per_page'] = $value;
$this->setModified('per_page');
}
/**
* @return integer
*/
public function getFinalPerPage()
{
$perPage = $this->getPerPage();
if ($perPage) {
return (integer)$perPage;
}
return (integer)Config::getInstance()->get('php-censor.per_page', 10);
}
}