Compare commits

..

33 commits

Author SHA1 Message Date
Marco Vito Moscaritolo d22211c4b4 Improved docs. 2015-07-19 20:09:27 +02:00
Marco Vito Moscaritolo da17482a80 Move BuildFactory to factory.build service. 2015-07-19 20:08:25 +02:00
Marco Vito Moscaritolo 6aba86e018 Improved docBlock 2015-05-31 18:19:52 +02:00
Marco Vito Moscaritolo be651b3576 Fixed parameter. 2015-05-31 17:48:09 +02:00
Marco Vito Moscaritolo 7693993df8 Fixed PHPCI in plugins. 2015-05-31 17:44:52 +02:00
Marco Vito Moscaritolo 4fe62ea248 Fixed PHPCS. 2015-05-31 17:39:52 +02:00
Marco Vito Moscaritolo e0803df283 Fixed dockblock. 2015-05-31 17:32:03 +02:00
Marco Vito Moscaritolo 9d03112aed Fixed indendentation. 2015-05-31 17:26:53 +02:00
Marco Vito Moscaritolo b1e387e195 Shields.io integration cleanup. 2015-05-31 17:09:17 +02:00
Marco Vito Moscaritolo f125047951 Use a HttpClient service to get the shield.io badge. 2015-05-31 16:56:42 +02:00
Marco Vito Moscaritolo e977360083 Added BuildStatus::ccxml tests. 2015-05-31 16:32:50 +02:00
Marco Vito Moscaritolo 180bdcf4fe Improve CS. 2015-05-31 16:01:51 +02:00
Marco Vito Moscaritolo 7d9e065963 Fixed tests after DIC introduction refactoring. 2015-05-31 15:19:20 +02:00
Marco Vito Moscaritolo 98221397b5 Check about bootstrap for test phase. 2015-05-31 15:15:38 +02:00
Marco Vito Moscaritolo 4b957e8d5d Daemon application using DIC. 2015-05-31 15:06:45 +02:00
Marco Vito Moscaritolo 56082f201b Controller are now services. 2015-05-31 13:31:34 +02:00
Marco Vito Moscaritolo b6f25e77c3 Load controller as services. 2015-05-31 13:31:16 +02:00
Marco Vito Moscaritolo 601d42ea6e Added container service into application. 2015-05-31 13:30:38 +02:00
Marco Vito Moscaritolo 7e71e2ec7b User services in rebuild command. 2015-05-31 11:43:21 +02:00
Marco Vito Moscaritolo 6a43003f24 User services in rebuild command. 2015-05-31 11:41:18 +02:00
Marco Vito Moscaritolo a461fb580d Update poll command to use services. 2015-05-31 11:33:44 +02:00
Marco Vito Moscaritolo 86de54b658 Use config as service. 2015-05-31 11:20:31 +02:00
Marco Vito Moscaritolo 455f9a59a8 Remove unrequired parameters from CLI command constructors. 2015-05-31 11:20:18 +02:00
Marco Vito Moscaritolo bfe21bc687 Remove unrequired parameters from CLI command constructors. 2015-05-31 11:18:04 +02:00
Marco Vito Moscaritolo 5a516732ed Move process controlll initialization in config. 2015-05-31 11:13:16 +02:00
Marco Vito Moscaritolo e4e08e32b0 Use user service to manage user on admin command. 2015-05-31 11:06:19 +02:00
Marco Vito Moscaritolo 74ed1b14e1 Use user service to manage user on admin command. 2015-05-31 11:05:49 +02:00
Marco Vito Moscaritolo 063bec407d Move CLI app to use DIC. 2015-05-31 11:01:40 +02:00
Marco Vito Moscaritolo 3eb1648e13 Swtich DIC to symfony container. 2015-05-31 10:33:27 +02:00
Marco Vito Moscaritolo a0e72b9bc7 Remove new instance of each store. 2015-05-30 23:24:14 +02:00
Marco Vito Moscaritolo a9545e4104 Added store.entity services and fixed application to use it. 2015-05-30 23:20:13 +02:00
Marco Vito Moscaritolo ebf5a5dd7b First draft of DIC initialization with config. 2015-05-30 23:04:47 +02:00
Marco Vito Moscaritolo 65aba6b3c6 Update pimple to version 3. 2015-05-30 21:33:48 +02:00
984 changed files with 21529 additions and 168065 deletions

View file

@ -1,41 +0,0 @@
Contributions to PHPCI are very much encouraged, and we do our best to make it as welcoming and simple as possible.
### Before You Start
Before you start, please make sure that you are aware of, and agree to, the following conditions of contribution:
* By making a contribution to PHPCI, you accept that you are granting copyright ownership for that contribution to Block 8 Limited - the company responsible for PHPCI. In countries where copyright reassignment is not permitted, you grant Block 8 Limited a perpetual, non-exclusive licence to use your contribution in any way and for any purpose.
* By making a contribution to PHPCI, you accept that your code will be released under the open-source [BSD 2-Clause Licence](https://github.com/Block8/PHPCI/blob/master/LICENSE.md).
Block 8 are committed to PHPCI being a truly free and open source project, providing easy to use continuous integration and testing to as many developers as possible. We may, at our sole discretion, provide paid services based upon PHPCI - but PHPCI will always remain free (as in cost, and freedom) and open source.
### The Contribution Process
1. If you are thinking of making a large change or feature addition, [open an issue](/Block8/PHPCI/issues) titled "Intent to implement: <Your Feature>". Describe your idea in detail and discuss it with the community. It might be that someone already has a plan, could help you out, or your idea may simply not be suitable for the project at this time.
2. Fork the PHPCI project on Github
3. Add a feature or fix a bug - We recommend that you do this on a branch within your repository.
4. Create a pull request containing just the one change you want to contribute back to PHPCI. If you have more than one feature or bug fix, please create separate branches within your repository, and then submit a separate pull request for each one. Your pull request should use the template detailed below.
5. We'll then review your pull request and give any necessary feedback, this could be:
* Suggestions to improve your implementation
* Questions
* Issues/bugs related to the change
* Coding standards pointers
6. Once everyone is happy with the submission, we'll merge it back into PHPCI. Your change will then be included in the next project release.
### Not sure what to start with?
We maintain two labels within our issue tracker that may be of interest to new contributors:
* [The "Easy Fix" List](https://github.com/Block8/PHPCI/labels/flag:easy-fix)
* [The "Priority" List](https://github.com/Block8/PHPCI/labels/flag:priority)
### Coding Standards
We require that all contributions meet at least the following guidelines:
* PSR-1 & PSR-2 compliance for all code
* Doc-blocks for all classes and methods
* All files must contain the standard file-level docblock, including the copyright, license and link tags.
All pull requests will be checked against these standards. If you're modifying a file as part of your change which does not comply with the above, please make the necessary changes to bring it into compliance prior to submitting the pull request.
### Other Requirements
When you're adding new features or functionality, or you're updating existing functionality, please ensure that the relevant documentation is also either created or updated on the Wiki.

View file

@ -1,28 +0,0 @@
Before submitting your issue, please make sure that you've checked all of the checkboxes below.
- [ ] You're running the [latest release](https://github.com/Block8/PHPCI/releases/latest) version of PHPCI.
- [ ] Ensure that you're running at least PHP 5.3.6, you can check this by running `php -v`
- [ ] You've run `composer install --no-dev -o` from the root of your installation.
- [ ] You have set up either the PHPCI [Worker](https://github.com/Block8/PHPCI/wiki/Run-Builds-Using-a-Worker), [Daemon](https://github.com/Block8/PHPCI/wiki/Run-Builds-Using-a-Daemon) or [Cron Job](https://github.com/Block8/PHPCI/wiki/Run-Builds-Using-Cron) to run builds.
To help us better understand your issue, please answer the following.
### Expected behaviour
*Please describe what you're expecting to see happen.*
### Actual behaviour
*Please describe what you're actually seeing happen.*
### Steps to reproduce
*If your issue requires any specific steps to reproduce, please outline them here.*
### Environment info
Operating System:
PHP Version:
MySQL Version:
### Logs or other output that would be helpful
(If logs are large, please upload as attachment).

View file

@ -1,23 +0,0 @@
Contribution Type: bug fix | new plugin | new feature | refactor | cosmetic
Link to Intent to Implement:
Link to Bug:
This pull request affects the following areas:
* [ ] Front-End
* [ ] Builder
* [ ] Build Plugins
**In raising this pull request, I confirm the following (please check boxes):**
- [ ] I have read and understood the [contributing guidelines](/.github/CONTRIBUTING.md)?
- [ ] I have checked that another pull request for this purpose does not exist.
- [ ] I have considered, and confirmed that this submission will be valuable to others.
- [ ] I have created or updated the relevant documentation for this change on the PHPCI Wiki.
- [ ] Do the PHPCI tests pass?
Detailed description of change:

View file

@ -11,9 +11,14 @@ namespace PHPCI;
use b8;
use b8\Exception\HttpException;
use b8\Http\Request;
use b8\Http\Response;
use b8\Http\Response\RedirectResponse;
use b8\Http\Router;
use b8\View;
use PHPCI\Store\UserStore;
use PHPCI\Store\ProjectStore;
use Symfony\Component\DependencyInjection\Container;
/**
* PHPCI Front Controller
@ -26,6 +31,46 @@ class Application extends b8\Application
*/
protected $controller;
/**
* @var \PHPCI\Store\UserStore
*/
protected $userStore;
/**
* @var \PHPCI\Store\ProjectStore
*/
protected $projectStore;
/**
* Create the PHPCI web application.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param UserStore $userStore
* @param ProjectStore $projectStore
* @param Container $container
*/
public function __construct(
Config $config,
Request $request,
Response $response,
UserStore $userStore,
ProjectStore $projectStore,
Container $container
) {
$this->config = $config;
$this->response = $response;
$this->request = $request;
$this->userStore = $userStore;
$this->projectStore = $projectStore;
$this->container = $container;
$this->router = new Router($this, $this->request, $this->config);
$this->init();
}
/**
* Initialise PHPCI - Handles session verification, routing, etc.
*/
@ -38,7 +83,7 @@ class Application extends b8\Application
// Inlined as a closure to fix "using $this when not in object context" on 5.3
$validateSession = function () {
if (!empty($_SESSION['phpci_user_id'])) {
$user = b8\Store\Factory::getStore('User')->getByPrimaryKey($_SESSION['phpci_user_id']);
$user = $this->userStore->getByPrimaryKey($_SESSION['phpci_user_id']);
if ($user) {
$_SESSION['phpci_user'] = $user;
@ -106,8 +151,7 @@ class Application extends b8\Application
if ($this->response->hasLayout() && $this->controller->layout) {
$this->setLayoutVariables($this->controller->layout);
$this->controller->layout->content = $this->response->getContent();
$this->controller->layout->content = $this->response->getContent();
$this->response->setContent($this->controller->layout->render());
}
@ -115,53 +159,69 @@ class Application extends b8\Application
}
/**
* Loads a particular controller, and injects our layout view into it.
* @param $class
* @return mixed
* @return \PHPCI\Controller
*/
protected function loadController($class)
public function getController()
{
$controller = parent::loadController($class);
$controller->layout = new View('layout');
$controller->layout->title = 'PHPCI';
$controller->layout->breadcrumb = array();
if (empty($this->controller)) {
$this->controller = $this->container->get($this->getControllerId($this->route));
}
return $controller;
return $this->controller;
}
/**
* Check if the specified controller exist.
*
* @param array $route
*
* @return boolean
*/
public function controllerExists($route)
{
return $this->container->has($this->getControllerId($route));
}
/**
* Create controller service Id based on specified route.
*
* @param array $route
*
* @return string
*/
protected function getControllerId($route)
{
return 'application.controller.' . strtolower($route['controller']);
}
/**
* Injects variables into the layout before rendering it.
*
* @param View $layout
*/
protected function setLayoutVariables(View &$layout)
{
$groups = array();
$groupStore = b8\Store\Factory::getStore('ProjectGroup');
$groupList = $groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
foreach ($groupList['items'] as $group) {
$thisGroup = array('title' => $group->getTitle());
$projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$groups[] = $thisGroup;
}
$layout->groups = $groups;
$layout->projects = $this->projectStore->getWhere(
array('archived' => (int)isset($_GET['archived'])),
50,
0,
array(),
array('title' => 'ASC')
);
}
/**
* Check whether we should skip auth (because it is disabled)
*
* @return bool
*/
protected function shouldSkipAuth()
{
$config = b8\Config::getInstance();
$state = (bool)$config->get('phpci.authentication_settings.state', false);
$userId = $config->get('phpci.authentication_settings.user_id', 0);
$state = (bool) $this->config->get('phpci.authentication_settings.state', false);
$userId = $this->config->get('phpci.authentication_settings.user_id', 0);
if (false !== $state && 0 != (int)$userId) {
$user = b8\Store\Factory::getStore('User')
->getByPrimaryKey($userId);
$user = $this->userStore->getByPrimaryKey($userId);
if ($user) {
$_SESSION['phpci_user'] = $user;

View file

@ -11,6 +11,7 @@ namespace PHPCI;
use b8\Store\Factory;
use PHPCI\Model\Build;
use PHPCI\Store\BuildStore;
/**
* PHPCI Build Factory - Takes in a generic "Build" and returns a type-specific build model.
@ -18,62 +19,66 @@ use PHPCI\Model\Build;
*/
class BuildFactory
{
/**
* @var BuildStore
*/
protected $buildStore;
public function __construct(BuildStore $buildStore)
{
$this->buildStore = $buildStore;
}
/**
* @param $buildId
* @return Build
* @throws \Exception
*/
public static function getBuildById($buildId)
public function getBuildById($buildId)
{
$build = Factory::getStore('Build')->getById($buildId);
$build = $this->buildStore->getById($buildId);
if (empty($build)) {
throw new \Exception('Build ID ' . $buildId . ' does not exist.');
}
return self::getBuild($build);
return $this->getBuild($build);
}
/**
* Takes a generic build and returns a type-specific build model.
* @param Build $build The build from which to get a more specific build type.
* @param Build $base The build from which to get a more specific build type.
* @return Build
*/
public static function getBuild(Build $build)
public function getBuild(Build $base)
{
$project = $build->getProject();
if (!empty($project)) {
switch ($project->getType()) {
case 'remote':
$type = 'RemoteGitBuild';
break;
case 'local':
$type = 'LocalBuild';
break;
case 'github':
$type = 'GithubBuild';
break;
case 'bitbucket':
$type = 'BitbucketBuild';
break;
case 'gitlab':
$type = 'GitlabBuild';
break;
case 'hg':
$type = 'MercurialBuild';
break;
case 'svn':
$type = 'SubversionBuild';
break;
default:
return $build;
}
$class = '\\PHPCI\\Model\\Build\\' . $type;
$build = new $class($build->getDataArray());
switch($base->getProject()->getType())
{
case 'remote':
$type = 'RemoteGitBuild';
break;
case 'local':
$type = 'LocalBuild';
break;
case 'github':
$type = 'GithubBuild';
break;
case 'bitbucket':
$type = 'BitbucketBuild';
break;
case 'gitlab':
$type = 'GitlabBuild';
break;
case 'hg':
$type = 'MercurialBuild';
break;
case 'svn':
$type = 'SubversionBuild';
break;
}
return $build;
$type = '\\PHPCI\\Model\\Build\\' . $type;
return new $type($base->getDataArray());
}
}

View file

@ -99,6 +99,7 @@ class Builder implements LoggerAwareInterface
/**
* Set up the builder.
*
* @param \PHPCI\Model\Build $build
* @param LoggerInterface $logger
*/
@ -130,6 +131,7 @@ class Builder implements LoggerAwareInterface
/**
* Set the config array, as read from phpci.yml
*
* @param array|null $config
* @throws \Exception
*/
@ -144,6 +146,7 @@ class Builder implements LoggerAwareInterface
/**
* Access a variable from the phpci.yml file.
*
* @param string
* @return mixed
*/
@ -160,6 +163,7 @@ class Builder implements LoggerAwareInterface
/**
* Access a variable from the config.yml
*
* @param $key
* @return mixed
*/
@ -188,14 +192,6 @@ class Builder implements LoggerAwareInterface
$this->build->sendStatusPostback();
$success = true;
$previous_build = $this->build->getProject()->getPreviousBuild($this->build->getBranch());
$previous_state = Build::STATUS_NEW;
if ($previous_build) {
$previous_state = $previous_build->getStatus();
}
try {
// Set up the build:
$this->setupBuild();
@ -213,30 +209,19 @@ class Builder implements LoggerAwareInterface
$this->build->setStatus(Build::STATUS_FAILED);
}
// Complete stage plugins are always run
$this->pluginExecutor->executePlugins($this->config, 'complete');
if ($success) {
$this->pluginExecutor->executePlugins($this->config, 'success');
if ($previous_state == Build::STATUS_FAILED) {
$this->pluginExecutor->executePlugins($this->config, 'fixed');
}
$this->buildLogger->logSuccess(Lang::get('build_success'));
} else {
$this->pluginExecutor->executePlugins($this->config, 'failure');
if ($previous_state == Build::STATUS_SUCCESS || $previous_state == Build::STATUS_NEW) {
$this->pluginExecutor->executePlugins($this->config, 'broken');
}
$this->buildLogger->logFailure(Lang::get('build_failed'));
}
} catch (\Exception $ex) {
$this->build->setStatus(Build::STATUS_FAILED);
$this->buildLogger->logFailure(Lang::get('exception') . $ex->getMessage());
}finally{
// Complete stage plugins are always run
$this->pluginExecutor->executePlugins($this->config, 'complete');
}
@ -278,6 +263,7 @@ class Builder implements LoggerAwareInterface
/**
* Find a binary required by a plugin.
*
* @param string $binary
* @param bool $quiet
*
@ -291,6 +277,7 @@ class Builder implements LoggerAwareInterface
/**
* Replace every occurrence of the interpolation vars in the given string
* Example: "This is build %PHPCI_BUILD%" => "This is build 182"
*
* @param string $input
* @return string
*/
@ -304,7 +291,8 @@ class Builder implements LoggerAwareInterface
*/
protected function setupBuild()
{
$this->buildPath = $this->build->getBuildPath();
$this->buildPath = $this->build->getBuildPath() . '/';
$this->build->currentBuildPath = $this->buildPath;
$this->interpolator->setupInterpolationVars(
$this->build,
@ -346,6 +334,7 @@ class Builder implements LoggerAwareInterface
/**
* Write to the build log.
*
* @param $message
* @param string $level
* @param array $context
@ -357,6 +346,7 @@ class Builder implements LoggerAwareInterface
/**
* Add a success-coloured message to the log.
*
* @param string
*/
public function logSuccess($message)
@ -366,6 +356,7 @@ class Builder implements LoggerAwareInterface
/**
* Add a failure-coloured message to the log.
*
* @param string $message
* @param \Exception $exception The exception that caused the error.
*/
@ -377,6 +368,7 @@ class Builder implements LoggerAwareInterface
* Returns a configured instance of the plugin factory.
*
* @param Build $build
*
* @return PluginFactory
*/
private function buildPluginFactory(Build $build)

View file

@ -11,7 +11,6 @@ namespace PHPCI\Command;
use PHPCI\Service\UserService;
use PHPCI\Helper\Lang;
use PHPCI\Store\UserStore;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@ -25,18 +24,18 @@ use Symfony\Component\Console\Output\OutputInterface;
class CreateAdminCommand extends Command
{
/**
* @var UserStore
* @var UserService
*/
protected $userStore;
protected $userService;
/**
* @param UserStore $userStore
* @param UserService $userService
*/
public function __construct(UserStore $userStore)
public function __construct(UserService $userService)
{
parent::__construct();
$this->userStore = $userStore;
$this->userService = $userService;
}
protected function configure()
@ -53,8 +52,6 @@ class CreateAdminCommand extends Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$userService = new UserService($this->userStore);
/** @var $dialog \Symfony\Component\Console\Helper\DialogHelper */
$dialog = $this->getHelperSet()->get('dialog');
@ -72,7 +69,7 @@ class CreateAdminCommand extends Command
$adminPass = $dialog->askHiddenResponse($output, Lang::get('enter_password'));
try {
$userService->createUser($adminName, $adminEmail, $adminPass, true);
$this->userService->createUser($adminName, $adminEmail, $adminPass, true);
$output->writeln(Lang::get('user_created'));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>%s</error>', Lang::get('failed_to_create')));

View file

@ -48,11 +48,12 @@ class DaemonCommand extends Command
*/
protected $processControl;
public function __construct(Logger $logger, ProcessControlInterface $processControl = null, $name = null)
public function __construct(Logger $logger, ProcessControlInterface $processControl)
{
parent::__construct($name);
parent::__construct();
$this->logger = $logger;
$this->processControl = $processControl ?: Factory::getInstance();
$this->processControl = $processControl;
}
protected function configure()

View file

@ -47,9 +47,9 @@ class DaemoniseCommand extends Command
* @param \Monolog\Logger $logger
* @param string $name
*/
public function __construct(Logger $logger, $name = null)
public function __construct(Logger $logger)
{
parent::__construct($name);
parent::__construct();
$this->logger = $logger;
}

View file

@ -16,12 +16,10 @@ use b8\Config;
use b8\Store\Factory;
use PHPCI\Helper\Lang;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use PHPCI\Service\UserService;
use Symfony\Component\Console\Question\ConfirmationQuestion;
/**
* Install console command - Installs PHPCI.
@ -48,9 +46,6 @@ class InstallCommand extends Command
->addOption('admin-pass', null, InputOption::VALUE_OPTIONAL, Lang::get('admin_pass'))
->addOption('admin-mail', null, InputOption::VALUE_OPTIONAL, Lang::get('admin_email'))
->addOption('config-path', null, InputOption::VALUE_OPTIONAL, Lang::get('config_path'), $defaultPath)
->addOption('queue-disabled', null, InputOption::VALUE_NONE, 'Don\'t ask for queue details')
->addOption('queue-server', null, InputOption::VALUE_OPTIONAL, 'Beanstalkd queue server hostname')
->addOption('queue-name', null, InputOption::VALUE_OPTIONAL, 'Beanstalkd queue name')
->setDescription(Lang::get('install_phpci'));
}
@ -234,45 +229,10 @@ class InstallCommand extends Command
}
$phpci['url'] = $url;
$phpci['worker'] = $this->getQueueInformation($input, $output, $dialog);
return $phpci;
}
/**
* If the user wants to use a queue, get the necessary details.
* @param InputInterface $input
* @param OutputInterface $output
* @param DialogHelper $dialog
* @return array
*/
protected function getQueueInformation(InputInterface $input, OutputInterface $output, DialogHelper $dialog)
{
if ($input->getOption('queue-disabled')) {
return null;
}
$rtn = [];
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('Use beanstalkd to manage build queue? ', true);
if (!$helper->ask($input, $output, $question)) {
$output->writeln('<error>Skipping beanstalkd configuration.</error>');
return null;
}
if (!$rtn['host'] = $input->getOption('queue-server')) {
$rtn['host'] = $dialog->ask($output, 'Enter your beanstalkd hostname [localhost]: ', 'localhost');
}
if (!$rtn['queue'] = $input->getOption('queue-name')) {
$rtn['queue'] = $dialog->ask($output, 'Enter the queue (tube) name to use [phpci]: ', 'phpci');
}
return $rtn;
}
/**
* Load configuration for DB form CLI options or ask info to user.
*

View file

@ -9,15 +9,16 @@
namespace PHPCI\Command;
use b8\Store\Factory;
use b8\HttpClient;
use Monolog\Logger;
use PHPCI\Helper\Lang;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Parser;
use PHPCI\Config;
use PHPCI\Model\Build;
use PHPCI\Store\BuildStore;
use PHPCI\Store\ProjectStore;
/**
* Run console command - Poll github for latest commit id
@ -28,14 +29,39 @@ use PHPCI\Model\Build;
class PollCommand extends Command
{
/**
* @var \Monolog\Logger
* @var Config
*/
protected $config;
/**
* @var Logger
*/
protected $logger;
public function __construct(Logger $logger, $name = null)
/**
* @var BuildStore
*/
protected $buildStore;
/**
* @var ProjectStore
*/
protected $projectStore;
/**
* @var HttpClient
*/
protected $githubClient;
public function __construct(Config $config, Logger $logger, BuildStore $buildStore, ProjectStore $projectStore, HttpClient $githubClient)
{
parent::__construct($name);
parent::__construct();
$this->config = $config;
$this->logger = $logger;
$this->buildStore = $buildStore;
$this->projectStore = $projectStore;
$this->githubClient = $githubClient;
}
protected function configure()
@ -50,27 +76,19 @@ class PollCommand extends Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$parser = new Parser();
$yaml = file_get_contents(APPLICATION_PATH . 'PHPCI/config.yml');
$this->settings = $parser->parse($yaml);
$token = $this->settings['phpci']['github']['token'];
$token = $this->config->get('phpci.github.token');
if (!$token) {
$this->logger->error(Lang::get('no_token'));
return;
}
$buildStore = Factory::getStore('Build');
$this->logger->addInfo(Lang::get('finding_projects'));
$projectStore = Factory::getStore('Project');
$result = $projectStore->getWhere();
$result = $this->projectStore->getWhere();
$this->logger->addInfo(Lang::get('found_n_projects', count($result['items'])));
foreach ($result['items'] as $project) {
$http = new HttpClient('https://api.github.com');
$commits = $http->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token));
$commits = $this->githubClient->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token));
$last_commit = $commits['body'][0]['sha'];
$last_committer = $commits['body'][0]['commit']['committer']['email'];
@ -89,14 +107,14 @@ class PollCommand extends Command
$build->setStatus(Build::STATUS_NEW);
$build->setBranch($project->getBranch());
$build->setCreated(new \DateTime());
$build->setCommitMessage($message);
$build->setCommitMessage($message);
if (!empty($last_committer)) {
$build->setCommitterEmail($last_committer);
}
$buildStore->save($build);
$this->buildStore->save($build);
$project->setLastCommit($last_commit);
$projectStore->save($project);
$this->projectStore->save($project);
}
}

View file

@ -12,6 +12,7 @@ namespace PHPCI\Command;
use b8\Store\Factory;
use Monolog\Logger;
use PHPCI\Service\BuildService;
use PHPCI\Store\BuildStore;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
@ -46,13 +47,28 @@ class RebuildCommand extends Command
protected $sleep;
/**
* @param \Monolog\Logger $logger
* @param string $name
* @param BuildStore
*/
public function __construct(Logger $logger, $name = null)
protected $buildStore;
/**
* @param BuildService
*/
protected $buildService;
/**
* @param RunCommand
*/
protected $runCommand;
public function __construct(Logger $logger, BuildStore $buildStore, BuildService $buildService, RunCommand $runCommand)
{
parent::__construct($name);
parent::__construct();
$this->logger = $logger;
$this->buildStore = $buildStore;
$this->buildService = $buildService;
$this->runCommand = $runCommand;
}
protected function configure()
@ -67,17 +83,12 @@ class RebuildCommand extends Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$runner = new RunCommand($this->logger);
$runner->setMaxBuilds(1);
$runner->setDaemon(false);
$this->runCommand->setMaxBuilds(1);
$this->runCommand->setDaemon(false);
/** @var \PHPCI\Store\BuildStore $store */
$store = Factory::getStore('Build');
$service = new BuildService($store);
$builds = $store->getLatestBuilds(null, 1);
$builds = $this->buildStore->getLatestBuilds(null, 1);
$lastBuild = array_shift($builds);
$service->createDuplicateBuild($lastBuild);
$this->buildService->createDuplicateBuild($lastBuild);
$runner->run(new ArgvInput(array()), $output);
}

View file

@ -1,85 +0,0 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Command;
use b8\Config;
use b8\Store\Factory;
use Monolog\Logger;
use PHPCI\BuildFactory;
use PHPCI\Helper\Lang;
use PHPCI\Logging\OutputLogHandler;
use PHPCI\Service\BuildService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Console
*/
class RebuildQueueCommand extends Command
{
/**
* @var OutputInterface
*/
protected $output;
/**
* @var Logger
*/
protected $logger;
/**
* @param \Monolog\Logger $logger
* @param string $name
*/
public function __construct(Logger $logger, $name = null)
{
parent::__construct($name);
$this->logger = $logger;
}
protected function configure()
{
$this
->setName('phpci:rebuild-queue')
->setDescription('Rebuilds the PHPCI worker queue.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
// For verbose mode we want to output all informational and above
// messages to the symphony output interface.
if ($input->hasOption('verbose') && $input->getOption('verbose')) {
$this->logger->pushHandler(
new OutputLogHandler($this->output, Logger::INFO)
);
}
$store = Factory::getStore('Build');
$result = $store->getByStatus(0);
$this->logger->addInfo(Lang::get('found_n_builds', count($result['items'])));
$buildService = new BuildService($store);
while (count($result['items'])) {
$build = array_shift($result['items']);
$build = BuildFactory::getBuild($build);
$this->logger->addInfo('Added build #' . $build->getId() . ' to queue.');
$buildService->addBuildToQueue($build);
}
}
}

View file

@ -41,6 +41,11 @@ class RunCommand extends Command
*/
protected $logger;
/**
* @var BuildFactory
*/
protected $buildFactory;
/**
* @var int
*/
@ -52,12 +57,14 @@ class RunCommand extends Command
protected $isFromDaemon = false;
/**
* @param \Monolog\Logger $logger
* @param string $name
* @param BuildFactory $buildFactory
* @param Logger $logger
*/
public function __construct(Logger $logger, $name = null)
public function __construct(BuildFactory $buildFactory, Logger $logger)
{
parent::__construct($name);
parent::__construct();
$this->buildFactory = $buildFactory;
$this->logger = $logger;
}
@ -95,7 +102,7 @@ class RunCommand extends Command
while (count($result['items'])) {
$build = array_shift($result['items']);
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
// Skip build (for now) if there's already a build running in that project:
if (!$this->isFromDaemon && in_array($build->getProjectId(), $running)) {
@ -156,7 +163,7 @@ class RunCommand extends Command
foreach ($running['items'] as $build) {
/** @var \PHPCI\Model\Build $build */
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
$now = time();
$start = $build->getStarted()->getTimestamp();

View file

@ -9,7 +9,7 @@
namespace PHPCI\Command;
use b8\Config;
use PHPCI\Config;
use Monolog\Logger;
use PHPCI\Helper\Lang;
use Symfony\Component\Console\Command\Command;
@ -29,10 +29,17 @@ class UpdateCommand extends Command
*/
protected $logger;
public function __construct(Logger $logger, $name = null)
/**
* @var Config
*/
protected $config;
public function __construct(Logger $logger, Config $config)
{
parent::__construct($name);
parent::__construct();
$this->logger = $logger;
$this->config = $config;
}
protected function configure()
@ -60,8 +67,7 @@ class UpdateCommand extends Command
protected function verifyInstalled(OutputInterface $output)
{
$config = Config::getInstance();
$phpciUrl = $config->get('phpci.url');
$phpciUrl = $this->config->get('phpci.url');
return !empty($phpciUrl);
}

View file

@ -1,87 +0,0 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Command;
use b8\Config;
use Monolog\Logger;
use PHPCI\Logging\OutputLogHandler;
use PHPCI\Worker\BuildWorker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Worker Command - Starts the BuildWorker, which pulls jobs from beanstalkd
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Console
*/
class WorkerCommand extends Command
{
/**
* @var OutputInterface
*/
protected $output;
/**
* @var Logger
*/
protected $logger;
/**
* @param \Monolog\Logger $logger
* @param string $name
*/
public function __construct(Logger $logger, $name = null)
{
parent::__construct($name);
$this->logger = $logger;
}
protected function configure()
{
$this
->setName('phpci:worker')
->setDescription('Runs the PHPCI build worker.')
->addOption('debug', null, null, 'Run PHPCI in Debug Mode');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
// For verbose mode we want to output all informational and above
// messages to the symphony output interface.
if ($input->hasOption('verbose') && $input->getOption('verbose')) {
$this->logger->pushHandler(
new OutputLogHandler($this->output, Logger::INFO)
);
}
// Allow PHPCI to run in "debug mode"
if ($input->hasOption('debug') && $input->getOption('debug')) {
$output->writeln('<comment>Debug mode enabled.</comment>');
define('PHPCI_DEBUG_MODE', true);
}
$config = Config::getInstance()->get('phpci.worker', []);
if (empty($config['host']) || empty($config['queue'])) {
$error = 'The worker is not configured. You must set a host and queue in your config.yml file.';
throw new \Exception($error);
}
$worker = new BuildWorker($config['host'], $config['queue']);
$worker->setLogger($this->logger);
$worker->setMaxJobs(Config::getInstance()->get('phpci.worker.max_jobs', -1));
$worker->startWorker();
}
}

View file

@ -9,7 +9,6 @@
namespace PHPCI;
use b8\Config;
use b8\Exception\HttpException\ForbiddenException;
use b8\Http\Request;
use b8\Http\Response;
@ -53,6 +52,10 @@ class Controller extends \b8\Controller
{
parent::__construct($config, $request, $response);
$this->layout = new View('layout');
$this->layout->title = 'PHPCI';
$this->layout->breadcrumb = array();
$class = explode('\\', get_class($this));
$this->className = substr(array_pop($class), 0, -10);
$this->setControllerView();

View file

@ -12,11 +12,15 @@ namespace PHPCI\Controller;
use b8;
use b8\Exception\HttpException\NotFoundException;
use b8\Http\Response\JsonResponse;
use b8\Http\Request;
use b8\Http\Response;
use PHPCI\Config;
use PHPCI\BuildFactory;
use PHPCI\Helper\AnsiConverter;
use PHPCI\Helper\Lang;
use PHPCI\Model\Build;
use PHPCI\Model\Project;
use PHPCI\Store\BuildStore;
use PHPCI\Service\BuildService;
/**
@ -28,22 +32,42 @@ use PHPCI\Service\BuildService;
class BuildController extends \PHPCI\Controller
{
/**
* @var \PHPCI\Store\BuildStore
* @var BuildStore
*/
protected $buildStore;
/**
* @var \PHPCI\Service\BuildService
* @var BuildService
*/
protected $buildService;
/**
* Initialise the controller, set up stores and services.
* @var BuildFactory
*/
public function init()
{
$this->buildStore = b8\Store\Factory::getStore('Build');
$this->buildService = new BuildService($this->buildStore);
protected $buildFactory;
/**
* Create the Build controller
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param BuildStore $buildStore
* @param BuildService $buildService
*/
public function __construct(
Config $config,
Request $request,
Response $response,
BuildStore $buildStore,
BuildService $buildService,
BuildFactory $buildFactory
) {
parent::__construct($config, $request, $response);
$this->buildStore = $buildStore;
$this->buildService = $buildService;
$this->buildFactory = $buildFactory;
}
/**
@ -52,7 +76,7 @@ class BuildController extends \PHPCI\Controller
public function view($buildId)
{
try {
$build = BuildFactory::getBuildById($buildId);
$build = $this->buildFactory->getBuildById($buildId);
} catch (\Exception $ex) {
$build = null;
}
@ -63,42 +87,24 @@ class BuildController extends \PHPCI\Controller
$this->view->plugins = $this->getUiPlugins();
$this->view->build = $build;
$this->view->data = $this->getBuildData($build);
$this->view->data = json_encode($this->getBuildData($build));
$this->layout->title = Lang::get('build_n', $buildId);
$this->layout->subtitle = $build->getProjectTitle();
switch ($build->getStatus()) {
case 0:
$this->layout->skin = 'blue';
break;
case 1:
$this->layout->skin = 'yellow';
break;
case 2:
$this->layout->skin = 'green';
break;
case 3:
$this->layout->skin = 'red';
break;
}
$rebuild = Lang::get('rebuild_now');
$rebuildLink = PHPCI_URL . 'build/rebuild/' . $build->getId();
$delete = Lang::get('delete_build');
$deleteLink = PHPCI_URL . 'build/delete/' . $build->getId();
$actions = "<a class=\"btn btn-default\" href=\"{$rebuildLink}\">{$rebuild}</a> ";
$nav = array(
'title' => Lang::get('build_n', $buildId),
'icon' => 'cog',
'links' => array(
'build/rebuild/' . $build->getId() => Lang::get('rebuild_now'),
),
);
if ($this->currentUserIsAdmin()) {
$actions .= " <a class=\"btn btn-danger\" href=\"{$deleteLink}\">{$delete}</a>";
$nav['links']['build/delete/' . $build->getId()] = Lang::get('delete_build');
}
$this->layout->actions = $actions;
$this->layout->nav = $nav;
}
/**
@ -128,7 +134,7 @@ class BuildController extends \PHPCI\Controller
public function data($buildId)
{
$response = new JsonResponse();
$build = BuildFactory::getBuildById($buildId);
$build = $this->buildFactory->getBuildById($buildId);
if (!$build) {
$response->setResponseCode(404);
@ -145,7 +151,7 @@ class BuildController extends \PHPCI\Controller
*/
public function meta($buildId)
{
$build = BuildFactory::getBuildById($buildId);
$build = $this->buildFactory->getBuildById($buildId);
$key = $this->getParam('key', null);
$numBuilds = $this->getParam('num_builds', 1);
$data = null;
@ -162,7 +168,7 @@ class BuildController extends \PHPCI\Controller
/**
* Get build data from database and json encode it:
*/
protected function getBuildData(Build $build)
protected function getBuildData($build)
{
$data = array();
$data['status'] = (int)$build->getStatus();
@ -170,19 +176,6 @@ class BuildController extends \PHPCI\Controller
$data['created'] = !is_null($build->getCreated()) ? $build->getCreated()->format('Y-m-d H:i:s') : null;
$data['started'] = !is_null($build->getStarted()) ? $build->getStarted()->format('Y-m-d H:i:s') : null;
$data['finished'] = !is_null($build->getFinished()) ? $build->getFinished()->format('Y-m-d H:i:s') : null;
$data['duration'] = $build->getDuration();
/** @var \PHPCI\Store\BuildErrorStore $errorStore */
$errorStore = b8\Store\Factory::getStore('BuildError');
$errors = $errorStore->getErrorsForBuild($build->getId(), $this->getParam('since', null));
$errorView = new b8\View('Build/errors');
$errorView->build = $build;
$errorView->errors = $errors;
$data['errors'] = $errorStore->getErrorTotalForBuild($build->getId());
$data['error_html'] = $errorView->render();
$data['since'] = (new \DateTime())->format('Y-m-d H:i:s');
return $data;
}
@ -192,7 +185,7 @@ class BuildController extends \PHPCI\Controller
*/
public function rebuild($buildId)
{
$copy = BuildFactory::getBuildById($buildId);
$copy = $this->buildFactory->getBuildById($buildId);
if (empty($copy)) {
throw new NotFoundException(Lang::get('build_x_not_found', $buildId));
@ -200,10 +193,6 @@ class BuildController extends \PHPCI\Controller
$build = $this->buildService->createDuplicateBuild($copy);
if ($this->buildService->queueError) {
$_SESSION['global_error'] = Lang::get('add_to_queue_failed');
}
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL.'build/view/' . $build->getId());
return $response;
@ -216,7 +205,7 @@ class BuildController extends \PHPCI\Controller
{
$this->requireAdmin();
$build = BuildFactory::getBuildById($buildId);
$build = $this->buildFactory->getBuildById($buildId);
if (empty($build)) {
throw new NotFoundException(Lang::get('build_x_not_found', $buildId));
@ -249,6 +238,7 @@ class BuildController extends \PHPCI\Controller
$response = new JsonResponse();
$response->setContent($rtn);
return $response;
}

View file

@ -11,11 +11,20 @@ namespace PHPCI\Controller;
use b8;
use b8\Exception\HttpException\NotFoundException;
use b8\Exception\HttpException\NotAuthorizedException;
use b8\Store;
use b8\HttpClient;
use b8\Http\Request;
use b8\Http\Response;
use Exception;
use PHPCI\Config;
use PHPCI\BuildFactory;
use PHPCI\Helper\Lang;
use PHPCI\Model\Project;
use PHPCI\Model\Build;
use PHPCI\Service\BuildStatusService;
use PHPCI\Store\BuildStore;
use PHPCI\Store\ProjectStore;
/**
* Build Status Controller - Allows external access to build status information / images.
@ -25,69 +34,73 @@ use PHPCI\Service\BuildStatusService;
*/
class BuildStatusController extends \PHPCI\Controller
{
/* @var \PHPCI\Store\ProjectStore */
protected $projectStore;
/* @var \PHPCI\Store\BuildStore */
/**
* @var BuildStore
*/
protected $buildStore;
/**
* Initialise the controller, set up stores and services.
* @var ProjectStore
*/
public function init()
{
$this->response->disableLayout();
$this->buildStore = Store\Factory::getStore('Build');
$this->projectStore = Store\Factory::getStore('Project');
}
protected $projectStore;
/**
* Returns status of the last build
* @param $projectId
* @return string
* @var BuildFactory
*/
protected function getStatus($projectId)
{
$branch = $this->getParam('branch', 'master');
try {
$project = $this->projectStore->getById($projectId);
$status = 'passing';
protected $buildFactory;
if (!$project->getAllowPublicStatus()) {
return null;
}
/**
* Create the BuildStatus controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param BuildStore $buildStore
* @param ProjectStore $projectStore
* @param HttpClient $shieldsClient
* @param BuildFactory $buildFactory
*/
public function __construct(
Config $config,
Request $request,
Response $response,
BuildStore $buildStore,
ProjectStore $projectStore,
HttpClient $shieldsClient,
BuildFactory $buildFactory
) {
parent::__construct($config, $request, $response);
if (isset($project) && $project instanceof Project) {
$build = $project->getLatestBuild($branch, array(2,3));
if (isset($build) && $build instanceof Build && $build->getStatus() != 2) {
$status = 'failed';
}
}
} catch (\Exception $e) {
$status = 'error';
}
return $status;
$this->buildStore = $buildStore;
$this->projectStore = $projectStore;
$this->shieldsClient = $shieldsClient;
$this->buildFactory = $buildFactory;
}
/**
* Displays projects information in ccmenu format
*
* @param $projectId
* @return bool
* @throws \Exception
* @throws b8\Exception\HttpException
* @param int $projectId
*
* @return Response
*
* @throws Exception
* @throws HttpException
*/
public function ccxml($projectId)
{
/* @var Project $project */
$project = $this->projectStore->getById($projectId);
$xml = new \SimpleXMLElement('<Projects/>');
if (!$project instanceof Project || !$project->getAllowPublicStatus()) {
return $this->renderXml($xml);
if (!$project instanceof Project) {
throw new NotFoundException(Lang::get('project_x_not_found', $projectId));
}
if (!$project->getAllowPublicStatus()) {
throw new NotAuthorizedException();
}
$xml = new \SimpleXMLElement('<Projects/>');
try {
$branchList = $this->buildStore->getBuildBranches($projectId);
@ -108,51 +121,47 @@ class BuildStatusController extends \PHPCI\Controller
$xml = new \SimpleXMLElement('<projects/>');
}
return $this->renderXml($xml);
}
/**
* @param \SimpleXMLElement $xml
* @return bool
*/
protected function renderXml(\SimpleXMLElement $xml = null)
{
$this->response->disableLayout();
$this->response->setHeader('Content-Type', 'text/xml');
$this->response->setContent($xml->asXML());
$this->response->flush();
echo $xml->asXML();
return true;
return $this->response;
}
/**
* Returns the appropriate build status image in SVG format for a given project.
*
* @param int $projectId
*
* @return Response
*/
public function image($projectId)
{
$style = $this->getParam('style', 'plastic');
$label = $this->getParam('label', 'build');
$project = $this->projectStore->getById($projectId);
$status = $this->getStatus($projectId);
if (is_null($status)) {
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', '/');
return $response;
if (empty($project)) {
throw new NotFoundException(Lang::get('project_x_not_found', $projectId));
}
if (!$project->getAllowPublicStatus()) {
throw new NotAuthorizedException();
}
$style = $this->getParam('style', 'plastic');
$label = $this->getParam('label', 'build');
$branch = $this->getParam('branch', 'master');
$status = $this->getStatus($project, $branch);
$color = ($status == 'passing') ? 'green' : 'red';
$image = file_get_contents(sprintf(
'http://img.shields.io/badge/%s-%s-%s.svg?style=%s',
$label,
$status,
$color,
$style
));
$image = $this->shieldsClient->get(
sprintf('/badge/%s-%s-%s.svg', $label, $status, $color),
array('style' => $style)
);
$this->response->disableLayout();
$this->response->setHeader('Content-Type', 'image/svg+xml');
$this->response->setContent($image);
$this->response->setContent($image['body']);
return $this->response;
}
@ -167,11 +176,11 @@ class BuildStatusController extends \PHPCI\Controller
$project = $this->projectStore->getById($projectId);
if (empty($project)) {
throw new NotFoundException('Project with id: ' . $projectId . ' not found');
throw new NotFoundException(Lang::get('project_x_not_found', $projectId));
}
if (!$project->getAllowPublicStatus()) {
throw new NotFoundException('Project with id: ' . $projectId . ' not found');
throw new NotAuthorizedException();
}
$builds = $this->getLatestBuilds($projectId);
@ -196,9 +205,33 @@ class BuildStatusController extends \PHPCI\Controller
$builds = $this->buildStore->getWhere($criteria, 10, 0, array(), $order);
foreach ($builds['items'] as &$build) {
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
}
return $builds['items'];
}
/**
* Returns status of the last build
*
* @param int $projectId
*
* @return string
*
* @throws Exception
*/
protected function getStatus($project, $branch)
{
try {
$build = $project->getLatestBuild($branch, array(2,3));
if (isset($build) && $build instanceof Build && $build->getStatus() != 2) {
return 'failed';
}
} catch (Exception $e) {
return 'error';
}
return 'passing';
}
}

View file

@ -1,120 +0,0 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Controller;
use b8;
use b8\Form;
use b8\Store;
use PHPCI\Controller;
use PHPCI\Model\ProjectGroup;
/**
* Project Controller - Allows users to create, edit and view projects.
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Web
*/
class GroupController extends Controller
{
/**
* @var \PHPCI\Store\ProjectGroupStore
*/
protected $groupStore;
/**
* Set up this controller.
*/
public function init()
{
$this->groupStore = b8\Store\Factory::getStore('ProjectGroup');
}
/**
* List project groups.
*/
public function index()
{
$this->requireAdmin();
$groups = array();
$groupList = $this->groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
foreach ($groupList['items'] as $group) {
$thisGroup = array(
'title' => $group->getTitle(),
'id' => $group->getId(),
);
$projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$groups[] = $thisGroup;
}
$this->view->groups = $groups;
}
/**
* Add or edit a project group.
* @param null $groupId
* @return void|b8\Http\Response\RedirectResponse
*/
public function edit($groupId = null)
{
$this->requireAdmin();
if (!is_null($groupId)) {
$group = $this->groupStore->getById($groupId);
} else {
$group = new ProjectGroup();
}
if ($this->request->getMethod() == 'POST') {
$group->setTitle($this->getParam('title'));
$this->groupStore->save($group);
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL.'group');
return $response;
}
$form = new Form();
$form->setMethod('POST');
$form->setAction(PHPCI_URL . 'group/edit' . (!is_null($groupId) ? '/' . $groupId : ''));
$title = new Form\Element\Text('title');
$title->setContainerClass('form-group');
$title->setClass('form-control');
$title->setLabel('Group Title');
$title->setValue($group->getTitle());
$submit = new Form\Element\Submit();
$submit->setValue('Save Group');
$form->addField($title);
$form->addField($submit);
$this->view->form = $form;
}
/**
* Delete a project group.
* @param $groupId
* @return b8\Http\Response\RedirectResponse
*/
public function delete($groupId)
{
$this->requireAdmin();
$group = $this->groupStore->getById($groupId);
$this->groupStore->delete($group);
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL.'group');
return $response;
}
}

View file

@ -10,9 +10,14 @@
namespace PHPCI\Controller;
use b8;
use b8\Http\Request;
use b8\Http\Response;
use PHPCI\Config;
use PHPCI\BuildFactory;
use PHPCI\Helper\Lang;
use PHPCI\Model\Build;
use PHPCI\Store\BuildStore;
use PHPCI\Store\ProjectStore;
/**
* Home Controller - Displays the PHPCI Dashboard.
@ -23,28 +28,43 @@ use PHPCI\Model\Build;
class HomeController extends \PHPCI\Controller
{
/**
* @var \PHPCI\Store\BuildStore
* @var BuildStore
*/
protected $buildStore;
/**
* @var \PHPCI\Store\ProjectStore
* @var BuildFactory
*/
protected $buildFactory;
/**
* @var ProjectStore
*/
protected $projectStore;
/**
* @var \PHPCI\Store\ProjectGroupStore
* Create the Home controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param BuildStore $buildStore
* @param ProjectStore $projectStore
* @param BuildFactory $buildFactory
*/
protected $groupStore;
public function __construct(
Config $config,
Request $request,
Response $response,
BuildStore $buildStore,
ProjectStore $projectStore,
BuildFactory $buildFactory
) {
parent::__construct($config, $request, $response);
/**
* Initialise the controller, set up stores and services.
*/
public function init()
{
$this->buildStore = b8\Store\Factory::getStore('Build');
$this->projectStore = b8\Store\Factory::getStore('Project');
$this->groupStore = b8\Store\Factory::getStore('ProjectGroup');
$this->buildStore = $buildStore;
$this->projectStore = $projectStore;
$this->buildFactory = $buildFactory;
}
/**
@ -53,14 +73,24 @@ class HomeController extends \PHPCI\Controller
public function index()
{
$this->layout->title = Lang::get('dashboard');
$projects = $this->projectStore->getWhere(
array('archived' => (int)isset($_GET['archived'])),
50,
0,
array(),
array('title' => 'ASC')
);
$builds = $this->buildStore->getLatestBuilds(null, 10);
foreach ($builds as &$build) {
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
}
$this->view->builds = $builds;
$this->view->groups = $this->getGroupInfo();
$this->view->projects = $projects['items'];
$this->view->summary = $this->getSummaryHtml($projects);
return $this->view->render();
}
@ -98,7 +128,7 @@ class HomeController extends \PHPCI\Controller
$failures = array();
$counts = array();
foreach ($projects as $project) {
foreach ($projects['items'] as $project) {
$summaryBuilds[$project->getId()] = $this->buildStore->getLatestBuilds($project->getId());
$count = $this->buildStore->getWhere(
@ -118,7 +148,7 @@ class HomeController extends \PHPCI\Controller
}
$summaryView = new b8\View('SummaryTable');
$summaryView->projects = $projects;
$summaryView->projects = $projects['items'];
$summaryView->builds = $summaryBuilds;
$summaryView->successful = $successes;
$summaryView->failed = $failures;
@ -136,31 +166,11 @@ class HomeController extends \PHPCI\Controller
$view = new b8\View('BuildsTable');
foreach ($builds['items'] as &$build) {
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
}
$view->builds = $builds['items'];
return $view->render();
}
/**
* Get a summary of the project groups we have, and what projects they have in them.
* @return array
*/
protected function getGroupInfo()
{
$rtn = array();
$groups = $this->groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
foreach ($groups['items'] as $group) {
$thisGroup = array('title' => $group->getTitle());
$projects = $this->projectStore->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$thisGroup['summary'] = $this->getSummaryHtml($thisGroup['projects']);
$rtn[] = $thisGroup;
}
return $rtn;
}
}

View file

@ -23,6 +23,24 @@ use PHPCI\Plugin\Util\PluginInformationCollection;
*/
class PluginController extends \PHPCI\Controller
{
protected $required = array(
'php',
'ext-pdo',
'ext-pdo_mysql',
'block8/b8framework',
'ircmaxell/password-compat',
'swiftmailer/swiftmailer',
'symfony/yaml',
'symfony/console',
'psr/log',
'monolog/monolog',
'pimple/pimple',
'robmorgan/phinx',
);
protected $canInstall;
protected $composerPath;
/**
* List all enabled plugins, installed and recommend packages.
* @return string
@ -31,8 +49,12 @@ class PluginController extends \PHPCI\Controller
{
$this->requireAdmin();
$this->view->canWrite = is_writable(APPLICATION_PATH . 'composer.json');
$this->view->required = $this->required;
$json = $this->getComposerJson();
$this->view->installedPackages = $json['require'];
$this->view->suggestedPackages = $json['suggest'];
$pluginInfo = new PluginInformationCollection();
$pluginInfo->add(FilesPluginInformation::newFromDir(
@ -49,6 +71,49 @@ class PluginController extends \PHPCI\Controller
return $this->view->render();
}
/**
* Remove a given package.
*/
public function remove()
{
$this->requireAdmin();
$package = $this->getParam('package', null);
$json = $this->getComposerJson();
$response = new b8\Http\Response\RedirectResponse();
if (!in_array($package, $this->required)) {
unset($json['require'][$package]);
$this->setComposerJson($json);
$response->setHeader('Location', PHPCI_URL . 'plugin?r=' . $package);
return $response;
}
$response->setHeader('Location', PHPCI_URL);
return $response;
}
/**
* Install a given package.
*/
public function install()
{
$this->requireAdmin();
$package = $this->getParam('package', null);
$version = $this->getParam('version', '*');
$json = $this->getComposerJson();
$json['require'][$package] = $version;
$this->setComposerJson($json);
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL . 'plugin?w=' . $package);
return $response;
}
/**
* Get the json-decoded contents of the composer.json file.
* @return mixed
@ -58,4 +123,83 @@ class PluginController extends \PHPCI\Controller
$json = file_get_contents(APPLICATION_PATH . 'composer.json');
return json_decode($json, true);
}
/**
* Convert array to json and save composer.json
*
* @param $array
*/
protected function setComposerJson($array)
{
if (defined('JSON_PRETTY_PRINT')) {
$json = json_encode($array, JSON_PRETTY_PRINT);
} else {
$json = json_encode($array);
}
file_put_contents(APPLICATION_PATH . 'composer.json', $json);
}
/**
* Find a system binary.
* @param $binary
* @return null|string
*/
protected function findBinary($binary)
{
if (is_string($binary)) {
$binary = array($binary);
}
foreach ($binary as $bin) {
// Check project root directory:
if (is_file(APPLICATION_PATH . $bin)) {
return APPLICATION_PATH . $bin;
}
// Check Composer bin dir:
if (is_file(APPLICATION_PATH . 'vendor/bin/' . $bin)) {
return APPLICATION_PATH . 'vendor/bin/' . $bin;
}
// Use "which"
$which = trim(shell_exec('which ' . $bin));
if (!empty($which)) {
return $which;
}
}
return null;
}
/**
* Perform a search on packagist.org.
*/
public function packagistSearch()
{
$searchQuery = $this->getParam('q', '');
$http = new \b8\HttpClient();
$http->setHeaders(array('User-Agent: PHPCI/1.0 (+https://www.phptesting.org)'));
$res = $http->get('https://packagist.org/search.json', array('q' => $searchQuery));
$response = new b8\Http\Response\JsonResponse();
$response->setContent($res['body']);
return $response;
}
/**
* Look up available versions of a given package on packagist.org
*/
public function packagistVersions()
{
$name = $this->getParam('p', '');
$http = new \b8\HttpClient();
$http->setHeaders(array('User-Agent: PHPCI/1.0 (+https://www.phptesting.org)'));
$res = $http->get('https://packagist.org/packages/'.$name.'.json');
$response = new b8\Http\Response\JsonResponse();
$response->setContent($res['body']);
return $response;
}
}

View file

@ -13,11 +13,16 @@ use b8;
use b8\Form;
use b8\Exception\HttpException\NotFoundException;
use b8\Store;
use b8\Http\Request;
use b8\Http\Response;
use PHPCI;
use PHPCI\Config;
use PHPCI\BuildFactory;
use PHPCI\Helper\Github;
use PHPCI\Helper\Lang;
use PHPCI\Helper\SshKey;
use PHPCI\Store\BuildStore;
use PHPCI\Store\ProjectStore;
use PHPCI\Service\BuildService;
use PHPCI\Service\ProjectService;
@ -30,34 +35,59 @@ use PHPCI\Service\ProjectService;
class ProjectController extends PHPCI\Controller
{
/**
* @var \PHPCI\Store\ProjectStore
* @var ProjectStore
*/
protected $projectStore;
/**
* @var \PHPCI\Service\ProjectService
* @var ProjectService
*/
protected $projectService;
/**
* @var \PHPCI\Store\BuildStore
* @var BuildStore
*/
protected $buildStore;
/**
* @var \PHPCI\Service\BuildService
* @var BuildService
*/
protected $buildService;
/**
* Initialise the controller, set up stores and services.
* @var BuildFactory
*/
public function init()
{
$this->buildStore = Store\Factory::getStore('Build');
$this->projectStore = Store\Factory::getStore('Project');
$this->projectService = new ProjectService($this->projectStore);
$this->buildService = new BuildService($this->buildStore);
protected $buildFactory;
/**
* Create the Project controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param BuildStore $buildStore
* @param ProjectStore $projectStore
* @param ProjectService $projectService
* @param BuildService $buildService
* @param BuildFactory $buildFactory
*/
public function __construct(
Config $config,
Request $request,
Response $response,
BuildStore $buildStore,
ProjectStore $projectStore,
ProjectService $projectService,
BuildService $buildService,
BuildFactory $buildFactory
) {
parent::__construct($config, $request, $response);
$this->buildStore = $buildStore;
$this->projectStore = $projectStore;
$this->projectService = $projectService;
$this->buildService = $buildService;
$this->buildFactory = $buildFactory;
}
/**
@ -116,18 +146,18 @@ class ProjectController extends PHPCI\Controller
$email = $_SESSION['phpci_user']->getEmail();
$build = $this->buildService->createBuild($project, null, urldecode($branch), $email);
if ($this->buildService->queueError) {
$_SESSION['global_error'] = Lang::get('add_to_queue_failed');
}
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL.'build/view/' . $build->getId());
return $response;
}
/**
* Delete a project.
*/
* Delete a project.
*
* @param int $projectId
*
* @return Response
*/
public function delete($projectId)
{
$this->requireAdmin();
@ -173,7 +203,7 @@ class ProjectController extends PHPCI\Controller
$view = new b8\View('BuildsTable');
foreach ($builds['items'] as &$build) {
$build = BuildFactory::getBuild($build);
$build = $this->buildFactory->getBuild($build);
}
$view->builds = $builds['items'];
@ -224,7 +254,6 @@ class ProjectController extends PHPCI\Controller
'build_config' => $this->getParam('build_config', null),
'allow_public_status' => $this->getParam('allow_public_status', 0),
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
);
$project = $this->projectService->createProject($title, $type, $reference, $options);
@ -289,7 +318,6 @@ class ProjectController extends PHPCI\Controller
'allow_public_status' => $this->getParam('allow_public_status', 0),
'archived' => $this->getParam('archived', 0),
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
);
$project = $this->projectService->updateProject($project, $title, $type, $reference, $options);
@ -319,7 +347,7 @@ class ProjectController extends PHPCI\Controller
'local' => Lang::get('local'),
'hg' => Lang::get('hg'),
'svn' => Lang::get('svn'),
);
);
$field = Form\Element\Select::create('type', Lang::get('where_hosted'), true);
$field->setPattern('^(github|bitbucket|gitlab|remote|local|hg|svn)');
@ -358,20 +386,6 @@ class ProjectController extends PHPCI\Controller
$field->setClass('form-control')->setContainerClass('form-group')->setValue('master');
$form->addField($field);
$field = Form\Element\Select::create('group_id', 'Project Group', true);
$field->setClass('form-control')->setContainerClass('form-group')->setValue(1);
$groups = array();
$groupStore = b8\Store\Factory::getStore('ProjectGroup');
$groupList = $groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
foreach ($groupList['items'] as $group) {
$groups[$group->getId()] = $group->getTitle();
}
$field->setOptions($groups);
$form->addField($field);
$field = Form\Element\Checkbox::create('allow_public_status', Lang::get('allow_public_status'), false);
$field->setContainerClass('form-group');
$field->setCheckedValue(1);

View file

@ -10,8 +10,12 @@
namespace PHPCI\Controller;
use b8;
use b8\Http\Request;
use b8\Http\Response;
use PHPCI\Config;
use PHPCI\Helper\Email;
use PHPCI\Helper\Lang;
use PHPCI\Store\UserStore;
/**
* Session Controller - Handles user login / logout.
@ -22,22 +26,33 @@ use PHPCI\Helper\Lang;
class SessionController extends \PHPCI\Controller
{
/**
* @var \PHPCI\Store\UserStore
* @var UserStore
*/
protected $userStore;
/**
* Initialise the controller, set up stores and services.
* Create the Sesssion controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param UserStore $userStore
*/
public function init()
{
public function __construct(
Config $config,
Request $request,
Response $response,
UserStore $userStore
) {
parent::__construct($config, $request, $response);
$this->response->disableLayout();
$this->userStore = b8\Store\Factory::getStore('User');
$this->userStore = $userStore;
}
/**
* Handles user login (form and processing)
*/
* Handles user login (form and processing)
*/
public function login()
{
$isLoginFailure = false;
@ -49,7 +64,7 @@ class SessionController extends \PHPCI\Controller
} else {
unset($_SESSION['login_token']);
$user = $this->userStore->getByEmail($this->getParam('email'));
$user = $this->userStore->getByLoginOrEmail($this->getParam('email'));
if ($user && password_verify($this->getParam('password', ''), $user->getHash())) {
session_regenerate_id(true);
@ -68,7 +83,7 @@ class SessionController extends \PHPCI\Controller
$form->setAction(PHPCI_URL.'session/login');
$email = new b8\Form\Element\Email('email');
$email->setLabel(Lang::get('email_address'));
$email->setLabel(Lang::get('login'));
$email->setRequired(true);
$email->setContainerClass('form-group');
$email->setClass('form-control');

View file

@ -444,7 +444,7 @@ class SettingsController extends Controller
$field->setClass('form-control');
$field->setContainerClass('form-group');
$field->setOptions(Lang::getLanguageOptions());
$field->setValue(Lang::getLanguage());
$field->setValue('en');
$form->addField($field);

View file

@ -12,8 +12,12 @@ namespace PHPCI\Controller;
use b8;
use b8\Exception\HttpException\NotFoundException;
use b8\Form;
use b8\Http\Request;
use b8\Http\Response;
use PHPCI\Config;
use PHPCI\Controller;
use PHPCI\Helper\Lang;
use PHPCI\Store\UserStore;
use PHPCI\Service\UserService;
/**
@ -25,22 +29,35 @@ use PHPCI\Service\UserService;
class UserController extends Controller
{
/**
* @var \PHPCI\Store\UserStore
* @var UserStore
*/
protected $userStore;
/**
* @var \PHPCI\Service\UserService
* @var UserService
*/
protected $userService;
/**
* Initialise the controller, set up stores and services.
* Create the User controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param UserStore $userStore
* @param UserService $userService
*/
public function init()
{
$this->userStore = b8\Store\Factory::getStore('User');
$this->userService = new UserService($this->userStore);
public function __construct(
Config $config,
Request $request,
Response $response,
UserStore $userStore,
UserService $userService
) {
parent::__construct($config, $request, $response);
$this->userStore = $userStore;
$this->userService = $userService;
}
/**
@ -48,8 +65,8 @@ class UserController extends Controller
*/
public function index()
{
$users = $this->userStore->getWhere(array(), 1000, 0, array(), array('email' => 'ASC'));
$this->view->users = $users;
$users = $this->userStore->getWhere(array(), 1000, 0, array(), array('email' => 'ASC'));
$this->view->users = $users;
$this->layout->title = Lang::get('manage_users');
@ -275,8 +292,14 @@ class UserController extends Controller
}
/**
* Delete a user.
*/
* Delete a user.
*
* @param int $userId
*
* @return Response
*
* @throws NotFoundException
*/
public function delete($userId)
{
$this->requireAdmin();
@ -291,6 +314,7 @@ class UserController extends Controller
$response = new b8\Http\Response\RedirectResponse();
$response->setHeader('Location', PHPCI_URL . 'user');
return $response;
}
}

View file

@ -11,7 +11,10 @@ namespace PHPCI\Controller;
use b8;
use b8\Store;
use b8\Http\Request;
use b8\Http\Response;
use Exception;
use PHPCI\Config;
use PHPCI\BuildFactory;
use PHPCI\Model\Project;
use PHPCI\Service\BuildService;
@ -27,8 +30,6 @@ use PHPCI\Store\ProjectStore;
* @author Guillaume Perréal <adirelle@gmail.com>
* @package PHPCI
* @subpackage Web
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class WebhookController extends \b8\Controller
{
@ -48,13 +49,36 @@ class WebhookController extends \b8\Controller
protected $buildService;
/**
* Initialise the controller, set up stores and services.
* @var BuildFactory
*/
public function init()
{
$this->buildStore = Store\Factory::getStore('Build');
$this->projectStore = Store\Factory::getStore('Project');
$this->buildService = new BuildService($this->buildStore);
protected $buildFactory;
/**
* Create the Webhook controller.
*
* @param Config $config
* @param Request $request
* @param Response $response
* @param BuildStore $buildStore
* @param ProjectStore $projectStore
* @param BuildService $buildService
* @param BuildFactory $buildFactory
*/
public function __construct(
Config $config,
Request $request,
Response $response,
BuildStore $buildStore,
ProjectStore $projectStore,
BuildService $buildService,
BuildFactory $buildFactory
) {
parent::__construct($config, $request, $response);
$this->buildStore = $buildStore;
$this->projectStore = $projectStore;
$this->buildService = $buildService;
$this->buildFactory = $buildFactory;
}
/** Handle the action, Ensuring to return a JsonResponse.
@ -82,64 +106,11 @@ class WebhookController extends \b8\Controller
}
/**
* Called by Bitbucket.
* Called by Bitbucket POST service.
*/
public function bitbucket($projectId)
{
$project = $this->fetchProject($projectId, 'bitbucket');
// Support both old services and new webhooks
if ($payload = $this->getParam('payload')) {
return $this->bitbucketService(json_decode($payload, true), $project);
}
$payload = json_decode(file_get_contents("php://input"), true);
if (empty($payload['push']['changes'])) {
// Invalid event from bitbucket
return [
'status' => 'failed',
'commits' => []
];
}
return $this->bitbucketWebhook($payload, $project);
}
/**
* Bitbucket webhooks.
*/
protected function bitbucketWebhook($payload, $project)
{
$results = array();
$status = 'failed';
foreach ($payload['push']['changes'] as $commit) {
try {
$email = $commit['new']['target']['author']['raw'];
$email = substr($email, 0, strpos($email, '>'));
$email = substr($email, strpos($email, '<') + 1);
$results[$commit['new']['target']['hash']] = $this->createBuild(
$project,
$commit['new']['target']['hash'],
$commit['new']['name'],
$email,
$commit['new']['target']['message']
);
$status = 'ok';
} catch (Exception $ex) {
$results[$commit['new']['target']['hash']] = array('status' => 'failed', 'error' => $ex->getMessage());
}
}
return array('status' => $status, 'commits' => $results);
}
/**
* Bitbucket POST service.
*/
protected function bitbucketService($payload, $project)
{
$payload = json_decode($this->getParam('payload'), true);
$results = array();
@ -225,7 +196,7 @@ class WebhookController extends \b8\Controller
protected function githubCommitRequest(Project $project, array $payload)
{
// Github sends a payload when you close a pull request with a
// non-existent commit. We don't want this.
// non-existant commit. We don't want this.
if (array_key_exists('after', $payload) && $payload['after'] === '0000000000000000000000000000000000000000') {
return array('status' => 'ignored');
}
@ -419,6 +390,10 @@ class WebhookController extends \b8\Controller
// If not, create a new build job for it:
$build = $this->buildService->createBuild($project, $commitId, $branch, $committer, $commitMessage, $extra);
$build = $this->buildFactory->getBuild($build);
// Send a status postback if the build type provides one:
$build->sendStatusPostback();
return array('status' => 'ok', 'buildID' => $build->getID());
}

View file

@ -21,7 +21,7 @@ final class AnsiConverter
static private $converter = null;
/**
* Initialize the singleton.
* Initialize the singletion.
*
* @return AnsiToHtmlConverter
*/
@ -35,7 +35,7 @@ final class AnsiConverter
}
/**
* Convert a text containing ANSI color sequences into HTML code.
* Convert a text containing ANSI colr sequences into HTML code.
*
* @param string $text The text to convert
*
@ -47,7 +47,7 @@ final class AnsiConverter
}
/**
* Do not instantiate this class.
* Do not instanciate this class.
*/
private function __construct()
{

View file

@ -34,9 +34,19 @@ abstract class BaseCommandExecutor implements CommandExecutor
*/
protected $verbose;
/**
* @var string
*/
protected $lastOutput;
/**
* @var string
*/
protected $lastError;
/**
* @var bool
*/
public $logExecOutput = true;
/**
@ -76,7 +86,6 @@ abstract class BaseCommandExecutor implements CommandExecutor
$this->lastOutput = array();
$command = call_user_func_array('sprintf', $args);
$this->logger->logDebug($command);
if ($this->quiet) {
$this->logger->log('Executing: ' . $command);
@ -90,6 +99,7 @@ abstract class BaseCommandExecutor implements CommandExecutor
);
$pipes = array();
$process = proc_open($command, $descriptorSpec, $pipes, $this->buildPath, null);
if (is_resource($process)) {

View file

@ -38,7 +38,6 @@ class BuildInterpolator
$this->interpolation_vars['%COMMIT%'] = $build->getCommitId();
$this->interpolation_vars['%SHORT_COMMIT%'] = substr($build->getCommitId(), 0, 7);
$this->interpolation_vars['%COMMIT_EMAIL%'] = $build->getCommitterEmail();
$this->interpolation_vars['%COMMIT_MESSAGE%'] = $build->getCommitMessage();
$this->interpolation_vars['%COMMIT_URI%'] = $build->getCommitLink();
$this->interpolation_vars['%BRANCH%'] = $build->getBranch();
$this->interpolation_vars['%BRANCH_URI%'] = $build->getBranchLink();
@ -50,7 +49,6 @@ class BuildInterpolator
$this->interpolation_vars['%BUILD_URI%'] = $phpCiUrl . "build/view/" . $build->getId();
$this->interpolation_vars['%PHPCI_COMMIT%'] = $this->interpolation_vars['%COMMIT%'];
$this->interpolation_vars['%PHPCI_SHORT_COMMIT%'] = $this->interpolation_vars['%SHORT_COMMIT%'];
$this->interpolation_vars['%PHPCI_COMMIT_MESSAGE%'] = $this->interpolation_vars['%COMMIT_MESSAGE%'];
$this->interpolation_vars['%PHPCI_COMMIT_EMAIL%'] = $this->interpolation_vars['%COMMIT_EMAIL%'];
$this->interpolation_vars['%PHPCI_COMMIT_URI%'] = $this->interpolation_vars['%COMMIT_URI%'];
$this->interpolation_vars['%PHPCI_PROJECT%'] = $this->interpolation_vars['%PROJECT%'];
@ -63,7 +61,6 @@ class BuildInterpolator
putenv('PHPCI=1');
putenv('PHPCI_COMMIT=' . $this->interpolation_vars['%COMMIT%']);
putenv('PHPCI_SHORT_COMMIT=' . $this->interpolation_vars['%SHORT_COMMIT%']);
putenv('PHPCI_COMMIT_MESSAGE=' . $this->interpolation_vars['%COMMIT_MESSAGE%']);
putenv('PHPCI_COMMIT_EMAIL=' . $this->interpolation_vars['%COMMIT_EMAIL%']);
putenv('PHPCI_COMMIT_URI=' . $this->interpolation_vars['%COMMIT_URI%']);
putenv('PHPCI_PROJECT=' . $this->interpolation_vars['%PROJECT%']);

View file

@ -12,15 +12,17 @@ namespace PHPCI\Helper;
use b8\Config;
/**
* Login Is Disabled Helper - Checks if login is disabled in the view
* @author Stephen Ball <phpci@stephen.rebelinblue.com>
* @package PHPCI
* @subpackage Web
*/
* Login Is Disabled Helper - Checks if login is disalbed in the view
*
* @author Stephen Ball <phpci@stephen.rebelinblue.com>
* @package PHPCI
* @subpackage Web
*/
class LoginIsDisabled
{
/**
* Checks if
*
* @param $method
* @param array $params
* @return mixed|null
@ -28,7 +30,7 @@ class LoginIsDisabled
public function __call($method, $params = array())
{
unset($method, $params);
$config = Config::getInstance();
$state = (bool) $config->get('phpci.authentication_settings.state', false);

View file

@ -11,6 +11,7 @@ namespace PHPCI\Helper;
/**
* Class MailerFactory helps to set up and configure a SwiftMailer object.
*
* @package PHPCI\Helper
*/
class MailerFactory
@ -22,6 +23,7 @@ class MailerFactory
/**
* Set the mailer factory configuration.
*
* @param array $config
*/
public function __construct($config = array())
@ -34,7 +36,8 @@ class MailerFactory
}
/**
* Returns an instance of Swift_Mailer based on the config.s
* Returns an instance of Swift_Mailer based on the config.
*
* @return \Swift_Mailer
*/
public function getSwiftMailerFromConfig()
@ -61,7 +64,9 @@ class MailerFactory
/**
* Return a specific configuration value by key.
*
* @param $configName
*
* @return null|string
*/
public function getMailConfig($configName)
@ -70,8 +75,7 @@ class MailerFactory
return $this->emailConfig[$configName];
} else {
// Check defaults
switch ($configName) {
switch($configName) {
case 'smtp_address':
return "localhost";
case 'default_mailto_address':

View file

@ -114,7 +114,6 @@ i din foretrukne hosting-platform.',
'default_branch' => 'Default branch navn',
'allow_public_status' => 'Tillad offentlig status-side og -billede for dette projekt?',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Gem Projekt',
'error_mercurial' => 'Mercurial repository-URL skal starte med http:// eller https://',
@ -204,7 +203,7 @@ Services</a> sektionen under dit Bitbucket-repository.',
'build_finished' => 'Build Afsluttet',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',

View file

@ -39,7 +39,7 @@ PHPCI',
'reset_email_title' => 'PHPCI Passwort zurücksetzen für %s',
'reset_invalid' => 'Fehlerhafte Anfrage für das Zurücksetzen eines Passwortes',
'email_address' => 'Emailadresse',
'login' => 'Login / Emailadresse',
'login' => 'Login / Email Address',
'password' => 'Passwort',
'log_in' => 'Einloggen',
@ -103,7 +103,7 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'local' => 'Lokaler Pfad',
'hg' => 'Mercurial',
'svn' => 'Subversion',
'where_hosted' => 'Wo wird Ihr Projekt gehostet?',
'choose_github' => 'Wählen Sie ein GitHub Repository:',
@ -115,8 +115,7 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
(falls Sie Ihrem Projektrepository kein phpci.yml hinzufügen können)',
'default_branch' => 'Name des Standardbranches',
'allow_public_status' => 'Öffentliche Statusseite und -bild für dieses Projekt einschalten?',
'archived' => 'Archiviert',
'archived_menu' => 'Archiviert',
'archived' => 'Archived',
'save_project' => 'Projekt speichern',
'error_mercurial' => 'Mercurial Repository-URL muss mit http://, oder https:// beginnen',
@ -130,7 +129,7 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'all_branches' => 'Alle Branches',
'builds' => 'Builds',
'id' => 'ID',
'date' => 'Datum',
'date' => 'Date',
'project' => 'Projekt',
'commit' => 'Commit',
'branch' => 'Branch',
@ -151,9 +150,6 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'webhooks_help_bitbucket' => 'Um für dieses Projekt automatisch einen Build zu starten, wenn neue Commits gepushed werden, fügen Sie die untenstehende URL als "POST" Service in der <a href="https://bitbucket.org/%s/admin/services">Services</a>-Sektion Ihres Bitbucket Repositories hinzu.',
// View Build
'errors' => 'Fehler',
'information' => 'Information',
'build_x_not_found' => 'Build mit ID %d existiert nicht.',
'build_n' => 'Build %d',
'rebuild_now' => 'Build neu starten',
@ -195,8 +191,8 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'codeception_suite' => 'Suite',
'codeception_time' => 'Zeit',
'codeception_synopsis' => '<strong>%1$d</strong> Tests in <strong>%2$f</strong> Sekunden ausgeführt.
<strong>%3$d</strong> Fehler.',
<strong>%3$d</strong> Fehler.',
'file' => 'Datei',
'line' => 'Zeile',
'class' => 'Klasse',
@ -212,14 +208,14 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'build_created' => 'Build erstellt',
'build_started' => 'Build gestartet',
'build_finished' => 'Build abgeschlossen',
'test_message' => 'Nachricht',
'test_no_message' => 'Keine Nachricht',
'test_success' => 'Erfolgreich: %d',
'test_fail' => 'Fehlschläge: %d',
'test_skipped' => 'Übersprungen: %d',
'test_error' => 'Fehler: %d',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',
'test_todo' => 'Todos: %d',
'test_total' => '%d Test(s)',
'test_total' => '%d test(s)',
// Users
'name' => 'Name',
@ -295,19 +291,6 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'search_packagist_for_more' => 'Packagist nach mehr Packages durchsuchen',
'search' => 'Suchen &raquo;',
// Summary plugin
'build-summary' => 'Zusammenfassung',
'stage' => 'Abschnitt',
'duration' => 'Dauer',
'plugin' => 'Plugin',
'stage_setup' => 'Vorbereitung',
'stage_test' => 'Test',
'stage_complete' => 'Vollständig',
'stage_success' => 'Erfolg',
'stage_failure' => 'Fehlschlag',
'stage_broken' => 'Defekt',
'stage_fixed' => 'Behoben',
// Installer
'installation_url' => 'PHPCI Installations-URL',
'db_host' => 'Datenbankserver',
@ -416,18 +399,5 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'build_file_missing' => 'Angegebene Builddatei existiert nicht.',
'property_file_missing' => 'Angegebene Eigenschaftsdatei existiert nicht.',
'could_not_process_report' => 'Konnte den von diesem Tool erstellten Bericht nicht verarbeiten.',
'shell_not_enabled' => 'Das Shell-Plugin ist nicht aktiviert. Bitte aktivieren Sie es via config.yml.',
// Error Levels:
'critical' => 'Kritisch',
'high' => 'Hoch',
'normal' => 'Normal',
'low' => 'Niedrig',
// Plugins that generate errors:
'php_mess_detector' => 'PHP Mess Detector',
'php_code_sniffer' => 'PHP Code Sniffer',
'php_unit' => 'PHP Unit',
'php_cpd' => 'PHP Copy/Paste Detector',
'php_docblock_checker' => 'PHP Docblock Checker',
'shell_not_enabled' => 'Das Shell-Plugin ist nicht aktiviert. Bitte aktivieren Sie es via config.yml.'
);

View file

@ -115,7 +115,6 @@ PHPCI',
'default_branch' => 'Προκαθορισμένο όνομα διακλάδωσης',
'allow_public_status' => 'Ενεργοποίηση της σελίδας δημόσιας κατάστασης και την εικόνα για το έργο αυτό;',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Αποθήκευση έργου',
'error_mercurial' => 'Ο σύνδεσμος URL του ευμετάβλητου αποθετηρίου πρέπει να ξεκινάει με http:// ή https://',
@ -205,7 +204,7 @@ Services</a> του Bitbucket αποθετηρίου σας.',
'build_finished' => 'Η κατασκευή ολοκληρώθηκε',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',

View file

@ -116,7 +116,6 @@ PHPCI',
'default_branch' => 'Default branch name',
'allow_public_status' => 'Enable public status page and image for this project?',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Save Project',
'error_mercurial' => 'Mercurial repository URL must be start with http:// or https://',
@ -154,9 +153,6 @@ PHPCI',
Services</a> section of your Bitbucket repository.',
// View Build
'errors' => 'Errors',
'information' => 'Information',
'build_x_not_found' => 'Build with ID %d does not exist.',
'build_n' => 'Build %d',
'rebuild_now' => 'Rebuild Now',
@ -217,7 +213,7 @@ PHPCI',
'build_finished' => 'Build Finished',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',
@ -309,8 +305,6 @@ PHPCI',
'stage_complete' => 'Complete',
'stage_success' => 'Success',
'stage_failure' => 'Failure',
'stage_broken' => 'Broken',
'stage_fixed' => 'Fixed',
// Installer
'installation_url' => 'PHPCI Installation URL',
@ -372,9 +366,6 @@ PHPCI',
'project_id_argument' => 'A project ID',
'commit_id_option' => 'Commit ID to build',
'branch_name_option' => 'Branch to build',
'add_to_queue_failed' => 'Build created successfully, but failed to add to build queue. This usually happens
when PHPCI is set to use a beanstalkd server that does not exist,
or your beanstalkd server has stopped.',
// Run Command
'run_all_pending' => 'Run all pending PHPCI builds.',
@ -423,22 +414,5 @@ PHPCI',
'build_file_missing' => 'Specified build file does not exist.',
'property_file_missing' => 'Specified property file does not exist.',
'could_not_process_report' => 'Could not process the report generated by this tool.',
'shell_not_enabled' => 'The shell plugin is not enabled. Please enable it via config.yml.',
// Error Levels:
'critical' => 'Critical',
'high' => 'High',
'normal' => 'Normal',
'low' => 'Low',
// Plugins that generate errors:
'php_mess_detector' => 'PHP Mess Detector',
'php_code_sniffer' => 'PHP Code Sniffer',
'php_unit' => 'PHP Unit',
'php_cpd' => 'PHP Copy/Paste Detector',
'php_docblock_checker' => 'PHP Docblock Checker',
'behat' => 'Behat',
'technical_debt' => 'Technical Debt',
'shell_not_enabled' => 'The shell plugin is not enabled. Please enable it via config.yml.'
);

View file

@ -115,7 +115,6 @@ PHPCI',
'default_branch' => 'Nombre de la rama por defecto',
'allow_public_status' => '¿Activar página pública con el estado del proyecto?',
'archived' => 'Archivado',
'archived_menu' => 'Archivado',
'save_project' => 'Guardar Proyecto',
'error_mercurial' => 'La URL del repositorio de Mercurial debe comenzar con http:// or https://',

View file

@ -115,7 +115,6 @@ PHPCI',
'default_branch' => 'Nom de la branche par défaut',
'allow_public_status' => 'Activer la page de statut publique et l\'image pour ce projet&nbsp;?',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Enregistrer le projet',
'error_mercurial' => 'Les URLs de dépôt Mercurial doivent commencer par http:// ou https://',

View file

@ -113,9 +113,8 @@ PHPCI',
(se non puoi aggiungere il file phpci.yml nel repository di questo progetto)',
'default_branch' => 'Nome del branch di default',
'allow_public_status' => 'Vuoi rendere pubblica la pagina dello stato e l\'immagine per questo progetto?',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Salva il Progetto',
'archived' => 'Archived',
'error_mercurial' => 'L\'URL del repository Mercurial URL deve iniziare con http:// o https://',
'error_remote' => 'L\'URL del repository deve iniziare con git://, http:// o https://',
@ -207,7 +206,7 @@ PHPCI',
'build_finished' => 'Build Terminata',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',

View file

@ -115,7 +115,6 @@ van je gekozen source code hosting platform',
'default_branch' => 'Standaard branch naam',
'allow_public_status' => 'Publieke statuspagina en afbeelding beschikbaar maken voor dit project?',
'archived' => 'Archived',
'archived_menu' => 'Archived',
'save_project' => 'Project opslaan',
'error_mercurial' => 'Mercurial repository URL dient te starten met http:// of https://',
@ -205,7 +204,7 @@ Services</a> sectie van je Bitbucket repository toegevoegd worden.',
'build_finished' => 'Build beëindigd',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',

View file

@ -116,7 +116,6 @@ od wybranego kodu źródłowego platformy hostingowej.',
'default_branch' => 'Domyślna nazwa gałęzi',
'allow_public_status' => 'Włączyć status publiczny dla tego projektu?',
'archived' => 'W archiwum',
'archived_menu' => 'W archiwum',
'save_project' => 'Zachowaj Projekt',
'error_mercurial' => 'URL repozytorium Mercurialnego powinno zaczynać się od http:// and https://',
@ -130,7 +129,7 @@ od wybranego kodu źródłowego platformy hostingowej.',
'all_branches' => 'Wszystkie Gałęzie',
'builds' => 'Budowania',
'id' => 'ID',
'date' => 'Data',
'date' => 'Date',
'project' => 'Projekt',
'commit' => 'Commit',
'branch' => 'Gałąź',
@ -206,14 +205,14 @@ Services</a> repozytoria Bitbucket.',
'build_created' => 'Budowanie Stworzone',
'build_started' => 'Budowanie Rozpoczęte',
'build_finished' => 'Budowanie Zakończone',
'test_message' => 'Wiadomość',
'test_no_message' => 'Brak wiadomości',
'test_success' => 'Powodzenie: %d',
'test_fail' => 'Niepowodzenia: %d',
'test_skipped' => 'Pominęte: %d',
'test_error' => 'Błędy: %d',
'test_todo' => 'Do zrobienia: %d',
'test_total' => '%d test(ów)',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',
'test_todo' => 'Todos: %d',
'test_total' => '%d test(s)',
// Users
'name' => 'Nazwa',
@ -344,10 +343,10 @@ Przejrzyj powyższą listę błędów przed kontynuowaniem.',
'incorrect_format' => 'Niepoprawny format',
// Create Build Command
'create_build_project' => 'Utwórz budowanie dla projektu',
'project_id_argument' => 'ID projektu',
'commit_id_option' => 'ID Commita do budowania',
'branch_name_option' => 'Gałąź do budowania',
'create_build_project' => 'Create a build for a project',
'project_id_argument' => 'A project ID',
'commit_id_option' => 'Commit ID to build',
'branch_name_option' => 'Branch to build',
// Run Command
'run_all_pending' => 'Uruchom wszystkie oczekujące budowy w PHPCI',

View file

@ -42,6 +42,7 @@ PHPCI',
'password' => 'Пароль',
'log_in' => 'Войти',
// Top Nav
'toggle_navigation' => 'Скрыть/показать панель навигации',
'n_builds_pending' => '%d сборок ожидает',
@ -107,13 +108,12 @@ PHPCI',
'repo_name' => 'Репозиторий / Внешний URL / Локальный путь',
'project_title' => 'Название проекта',
'project_private_key' => 'Приватный ключ для доступа к репозиторию
(оставьте поле пустым для локального использования и/или анонимного доступа)',
(оставьте поле пустым для локального использования и/или анонимного доступа)',
'build_config' => 'Конфигурация сборки проекта для PHPCI
(если вы не добавили файл phpci.yml в репозиторий вашего проекта)',
(если вы не добавили файл phpci.yml в репозиторий вашего проекта)',
'default_branch' => 'Ветка по умолчанию',
'allow_public_status' => 'Разрешить публичный статус и изображение (статуса) для проекта',
'archived' => 'Архивный',
'archived_menu' => 'Архив',
'archived' => 'Запакован',
'save_project' => 'Сохранить проект',
'error_mercurial' => 'URL репозитория Mercurial должен начинаться с http:// или https://',
@ -139,13 +139,13 @@ PHPCI',
'webhooks' => 'Webhooks',
'webhooks_help_github' => 'Чтобы Автоматически собирать этот проект при публикации новых коммитов, добавьте URL ниже в качестве нового хука в разделе настроек <a href="https://github.com/%s/settings/hooks">Webhooks
and Services</a> вашего GitHub репозитория.',
and Services</a> вашего GitHub репозитория.',
'webhooks_help_gitlab' => 'Чтобы Автоматически собирать этот проект при публикации новых коммитов, добавьте URL ниже в качестве "WebHook URL"
в разделе "Web Hooks" вашего GitLab репозитория.',
'webhooks_help_bitbucket' => 'Чтобы Автоматически собирать этот проект при публикации новых коммитов, добавьте URL ниже как "POST" сервис в разделе <a href="https://bitbucket.org/%s/admin/services">
Services</a> вашего Bitbucket репозитория.',
Services</a> вашего Bitbucket репозитория.',
// View Build
'build_x_not_found' => 'Сборки с ID %d не существует.',
@ -185,11 +185,6 @@ PHPCI',
'technical_debt' => 'Технические долги',
'behat' => 'Behat',
'codeception_feature' => 'Свойство',
'codeception_suite' => 'Набор',
'codeception_time' => 'Время',
'codeception_synopsis' => 'Тестов выполнено: <strong>%1$d</strong> (за <strong>%2$f</strong> сек.). Провалов: <strong>%3$d</strong>.',
'file' => 'Файл',
'line' => 'Строка',
'class' => 'Класс',
@ -207,12 +202,12 @@ PHPCI',
'build_finished' => 'Сборка окончена',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Успешно: %d',
'test_fail' => 'Провалено: %d',
'test_skipped' => 'Пропущено: %d',
'test_error' => 'Ошибок: %d',
'test_todo' => 'Todo: %d',
'test_total' => 'Тестов: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',
'test_todo' => 'Todos: %d',
'test_total' => '%d test(s)',
// Users
'name' => 'Имя',
@ -287,19 +282,6 @@ PHPCI',
'search_packagist_for_more' => 'Искать на Packagist',
'search' => 'Искать &raquo;',
// Summary plugin
'build-summary' => 'Сводка',
'stage' => 'Этап',
'duration' => 'Продолжительность',
'plugin' => 'Плагин',
'stage_setup' => 'Установка',
'stage_test' => 'тестирование',
'stage_complete' => 'Завершение',
'stage_success' => 'Успешное завершение',
'stage_failure' => 'Провал',
'stage_broken' => 'Поломка',
'stage_fixed' => 'Исправление',
// Installer
'installation_url' => 'URL-адрес PHPCI для установки',
'db_host' => 'Хост базы данных',

View file

@ -113,8 +113,7 @@ PHPCI',
(якщо ви не додали файл phpci.yml до репозиторію вашого проекту)',
'default_branch' => 'Назва гілки за замовчуванням',
'allow_public_status' => 'Увімкнути публічну сторінку статусу та зображення для цього проекта?',
'archived' => 'Архівний',
'archived_menu' => 'Архів',
'archived' => 'Archived',
'save_project' => 'Зберегти проект',
'error_mercurial' => 'URL репозиторію Mercurial повинен починатись із http:// або https://',
@ -205,7 +204,7 @@ PHPCI',
'build_finished' => 'Збірка завершена',
'test_message' => 'Message',
'test_no_message' => 'No message',
'test_success' => 'Successful: %d',
'test_success' => 'Succesfull: %d',
'test_fail' => 'Failures: %d',
'test_skipped' => 'Skipped: %d',
'test_error' => 'Errors: %d',

View file

@ -67,7 +67,7 @@ class BuildLogger implements LoggerAwareInterface
}
}
/**
/**
* Add a success-coloured message to the log.
* @param string
*/
@ -98,17 +98,6 @@ class BuildLogger implements LoggerAwareInterface
);
}
/**
* Add a debug message to the log.
* @param string
*/
public function logDebug($message)
{
if (defined('PHPCI_DEBUG_MODE') && PHPCI_DEBUG_MODE) {
$this->log("\033[0;33m" . $message . "\033[0m");
}
}
/**
* Sets a logger instance on the object
*

View file

@ -20,7 +20,7 @@ class FixDatabaseColumns extends AbstractMigration
$build->changeColumn('project_id', 'integer', array('null' => false));
$build->changeColumn('commit_id', 'string', array('limit' => 50, 'null' => false));
$build->changeColumn('status', 'integer', array('null' => false));
$build->changeColumn('log', 'text', array('null' => true));
$build->changeColumn('log', 'text', array('null' => true, 'default' => ''));
$build->changeColumn('branch', 'string', array('limit' => 50, 'null' => false, 'default' => 'master'));
$build->changeColumn('created', 'datetime', array('null' => true));
$build->changeColumn('started', 'datetime', array('null' => true));

View file

@ -14,6 +14,7 @@ class FixColumnTypes extends AbstractMigration
$build = $this->table('build');
$build->changeColumn('log', 'text', array(
'null' => true,
'default' => '',
'limit' => MysqlAdapter::TEXT_MEDIUM,
));

View file

@ -1,29 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
class AddProjectGroups extends AbstractMigration
{
public function change()
{
$table = $this->table('project_group');
$table->addColumn('title', 'string', array('limit' => 100, 'null' => false));
$table->save();
$group = new \PHPCI\Model\ProjectGroup();
$group->setTitle('Projects');
/** @var \PHPCI\Model\ProjectGroup $group */
$group = \b8\Store\Factory::getStore('ProjectGroup')->save($group);
$table = $this->table('project');
$table->addColumn('group_id', 'integer', array(
'signed' => true,
'null' => false,
'default' => $group->getId(),
));
$table->addForeignKey('group_id', 'project_group', 'id', array('delete'=> 'RESTRICT', 'update' => 'CASCADE'));
$table->save();
}
}

View file

@ -1,40 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
class RemoveUniqueNameIndex extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$user = $this->table('user');
if ($user->hasIndex('name', array('unique' => true))) {
$user->removeIndex('name', array('unique' => true));
$user->save();
}
$user->addIndex('name', array('unique' => false));
$user->save();
}
}

View file

@ -1,24 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;
class ErrorsTable extends AbstractMigration
{
public function change()
{
$table = $this->table('build_error');
$table->addColumn('build_id', 'integer', array('signed' => true));
$table->addColumn('plugin', 'string', array('limit' => 100));
$table->addColumn('file', 'string', array('limit' => 250, 'null' => true));
$table->addColumn('line_start', 'integer', array('signed' => false, 'null' => true));
$table->addColumn('line_end', 'integer', array('signed' => false, 'null' => true));
$table->addColumn('severity', 'integer', array('signed' => false, 'limit' => MysqlAdapter::INT_TINY));
$table->addColumn('message', 'string', array('limit' => 250));
$table->addColumn('created_date', 'datetime');
$table->addIndex(array('build_id', 'created_date'), array('unique' => false));
$table->addForeignKey('build_id', 'build', 'id', array('delete'=> 'CASCADE', 'update' => 'CASCADE'));
$table->save();
}
}

View file

@ -1,183 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
use PHPCI\Model\BuildMeta;
use PHPCI\Model\BuildError;
class ConvertErrors extends AbstractMigration
{
/**
* @var \PHPCI\Store\BuildMetaStore
*/
protected $metaStore;
/**
* @var \PHPCI\Store\BuildErrorStore
*/
protected $errorStore;
public function change()
{
$count = 100;
$this->metaStore = \b8\Store\Factory::getStore('BuildMeta');
$this->errorStore = \b8\Store\Factory::getStore('BuildError');
while ($count == 100) {
$data = $this->metaStore->getErrorsForUpgrade(100);
$count = count($data);
/** @var \PHPCI\Model\BuildMeta $meta */
foreach ($data as $meta) {
try {
switch ($meta->getMetaKey()) {
case 'phpmd-data':
$this->processPhpMdMeta($meta);
break;
case 'phpcs-data':
$this->processPhpCsMeta($meta);
break;
case 'phpdoccheck-data':
$this->processPhpDocCheckMeta($meta);
break;
case 'phpcpd-data':
$this->processPhpCpdMeta($meta);
break;
case 'technicaldebt-data':
$this->processTechnicalDebtMeta($meta);
break;
}
} catch (\Exception $ex) {}
$this->metaStore->delete($meta);
}
}
}
protected function processPhpMdMeta(BuildMeta $meta)
{
$data = json_decode($meta->getMetaValue(), true);
if (is_array($data) && count($data)) {
foreach ($data as $error) {
$buildError = new BuildError();
$buildError->setBuildId($meta->getBuildId());
$buildError->setPlugin('php_mess_detector');
$buildError->setCreatedDate(new \DateTime());
$buildError->setFile($error['file']);
$buildError->setLineStart($error['line_start']);
$buildError->setLineEnd($error['line_end']);
$buildError->setSeverity(BuildError::SEVERITY_HIGH);
$buildError->setMessage($error['message']);
$this->errorStore->save($buildError);
}
}
}
protected function processPhpCsMeta(BuildMeta $meta)
{
$data = json_decode($meta->getMetaValue(), true);
if (is_array($data) && count($data)) {
foreach ($data as $error) {
$buildError = new BuildError();
$buildError->setBuildId($meta->getBuildId());
$buildError->setPlugin('php_code_sniffer');
$buildError->setCreatedDate(new \DateTime());
$buildError->setFile($error['file']);
$buildError->setLineStart($error['line']);
$buildError->setLineEnd($error['line']);
$buildError->setMessage($error['message']);
switch ($error['type']) {
case 'ERROR':
$buildError->setSeverity(BuildError::SEVERITY_HIGH);
break;
case 'WARNING':
$buildError->setSeverity(BuildError::SEVERITY_LOW);
break;
}
$this->errorStore->save($buildError);
}
}
}
protected function processPhpDocCheckMeta(BuildMeta $meta)
{
$data = json_decode($meta->getMetaValue(), true);
if (is_array($data) && count($data)) {
foreach ($data as $error) {
$buildError = new BuildError();
$buildError->setBuildId($meta->getBuildId());
$buildError->setPlugin('php_docblock_checker');
$buildError->setCreatedDate(new \DateTime());
$buildError->setFile($error['file']);
$buildError->setLineStart($error['line']);
$buildError->setLineEnd($error['line']);
switch ($error['type']) {
case 'method':
$buildError->setMessage($error['class'] . '::' . $error['method'] . ' is missing a docblock.');
$buildError->setSeverity(BuildError::SEVERITY_NORMAL);
break;
case 'class':
$buildError->setMessage('Class ' . $error['class'] . ' is missing a docblock.');
$buildError->setSeverity(BuildError::SEVERITY_LOW);
break;
}
$this->errorStore->save($buildError);
}
}
}
protected function processPhpCpdMeta(BuildMeta $meta)
{
$data = json_decode($meta->getMetaValue(), true);
if (is_array($data) && count($data)) {
foreach ($data as $error) {
$buildError = new BuildError();
$buildError->setBuildId($meta->getBuildId());
$buildError->setPlugin('php_cpd');
$buildError->setCreatedDate(new \DateTime());
$buildError->setFile($error['file']);
$buildError->setLineStart($error['line_start']);
$buildError->setLineEnd($error['line_end']);
$buildError->setSeverity(BuildError::SEVERITY_NORMAL);
$buildError->setMessage('Copy and paste detected.');
$this->errorStore->save($buildError);
}
}
}
protected function processTechnicalDebtMeta(BuildMeta $meta)
{
$data = json_decode($meta->getMetaValue(), true);
if (is_array($data) && count($data)) {
foreach ($data as $error) {
$buildError = new BuildError();
$buildError->setBuildId($meta->getBuildId());
$buildError->setPlugin('technical_debt');
$buildError->setCreatedDate(new \DateTime());
$buildError->setFile($error['file']);
$buildError->setLineStart($error['line']);
$buildError->setSeverity(BuildError::SEVERITY_NORMAL);
$buildError->setMessage($error['message']);
$this->errorStore->save($buildError);
}
}
}
}

View file

@ -1,18 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
use Phinx\Db\Adapter\MysqlAdapter;
class ProjectTableDefaults extends AbstractMigration
{
public function change()
{
$this->table('project')
->changeColumn('build_config', MysqlAdapter::PHINX_TYPE_TEXT, array('null' => true))
->changeColumn('archived', MysqlAdapter::PHINX_TYPE_INTEGER, array(
'length' => MysqlAdapter::INT_TINY,
'default' => 0,
))
->save();
}
}

View file

@ -118,7 +118,7 @@ class BuildBase extends Model
'default' => null,
),
'log' => array(
'type' => 'mediumtext',
'type' => 'text',
'nullable' => true,
'default' => null,
),
@ -621,18 +621,6 @@ class BuildBase extends Model
return $this->setProjectId($value->getId());
}
/**
* Get BuildError models by BuildId for this Build.
*
* @uses \PHPCI\Store\BuildErrorStore::getByBuildId()
* @uses \PHPCI\Model\BuildError
* @return \PHPCI\Model\BuildError[]
*/
public function getBuildBuildErrors()
{
return Factory::getStore('BuildError', 'PHPCI')->getByBuildId($this->getId());
}
/**
* Get BuildMeta models by BuildId for this Build.
*

View file

@ -1,503 +0,0 @@
<?php
/**
* BuildError base model for table: build_error
*/
namespace PHPCI\Model\Base;
use PHPCI\Model;
use b8\Store\Factory;
/**
* BuildError Base Model
*/
class BuildErrorBase extends Model
{
/**
* @var array
*/
public static $sleepable = array();
/**
* @var string
*/
protected $tableName = 'build_error';
/**
* @var string
*/
protected $modelName = 'BuildError';
/**
* @var array
*/
protected $data = array(
'id' => null,
'build_id' => null,
'plugin' => null,
'file' => null,
'line_start' => null,
'line_end' => null,
'severity' => null,
'message' => null,
'created_date' => null,
);
/**
* @var array
*/
protected $getters = array(
// Direct property getters:
'id' => 'getId',
'build_id' => 'getBuildId',
'plugin' => 'getPlugin',
'file' => 'getFile',
'line_start' => 'getLineStart',
'line_end' => 'getLineEnd',
'severity' => 'getSeverity',
'message' => 'getMessage',
'created_date' => 'getCreatedDate',
// Foreign key getters:
'Build' => 'getBuild',
);
/**
* @var array
*/
protected $setters = array(
// Direct property setters:
'id' => 'setId',
'build_id' => 'setBuildId',
'plugin' => 'setPlugin',
'file' => 'setFile',
'line_start' => 'setLineStart',
'line_end' => 'setLineEnd',
'severity' => 'setSeverity',
'message' => 'setMessage',
'created_date' => 'setCreatedDate',
// Foreign key setters:
'Build' => 'setBuild',
);
/**
* @var array
*/
public $columns = array(
'id' => array(
'type' => 'int',
'length' => 11,
'primary_key' => true,
'auto_increment' => true,
'default' => null,
),
'build_id' => array(
'type' => 'int',
'length' => 11,
'default' => null,
),
'plugin' => array(
'type' => 'varchar',
'length' => 100,
'default' => null,
),
'file' => array(
'type' => 'varchar',
'length' => 250,
'nullable' => true,
'default' => null,
),
'line_start' => array(
'type' => 'int',
'length' => 11,
'nullable' => true,
'default' => null,
),
'line_end' => array(
'type' => 'int',
'length' => 11,
'nullable' => true,
'default' => null,
),
'severity' => array(
'type' => 'tinyint',
'length' => 3,
'default' => null,
),
'message' => array(
'type' => 'varchar',
'length' => 250,
'default' => null,
),
'created_date' => array(
'type' => 'datetime',
'default' => null,
),
);
/**
* @var array
*/
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
'build_id' => array('columns' => 'build_id, created_date'),
);
/**
* @var array
*/
public $foreignKeys = array(
'build_error_ibfk_1' => array(
'local_col' => 'build_id',
'update' => 'CASCADE',
'delete' => 'CASCADE',
'table' => 'build',
'col' => 'id'
),
);
/**
* Get the value of Id / id.
*
* @return int
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* Get the value of BuildId / build_id.
*
* @return int
*/
public function getBuildId()
{
$rtn = $this->data['build_id'];
return $rtn;
}
/**
* Get the value of Plugin / plugin.
*
* @return string
*/
public function getPlugin()
{
$rtn = $this->data['plugin'];
return $rtn;
}
/**
* Get the value of File / file.
*
* @return string
*/
public function getFile()
{
$rtn = $this->data['file'];
return $rtn;
}
/**
* Get the value of LineStart / line_start.
*
* @return int
*/
public function getLineStart()
{
$rtn = $this->data['line_start'];
return $rtn;
}
/**
* Get the value of LineEnd / line_end.
*
* @return int
*/
public function getLineEnd()
{
$rtn = $this->data['line_end'];
return $rtn;
}
/**
* Get the value of Severity / severity.
*
* @return int
*/
public function getSeverity()
{
$rtn = $this->data['severity'];
return $rtn;
}
/**
* Get the value of Message / message.
*
* @return string
*/
public function getMessage()
{
$rtn = $this->data['message'];
return $rtn;
}
/**
* Get the value of CreatedDate / created_date.
*
* @return \DateTime
*/
public function getCreatedDate()
{
$rtn = $this->data['created_date'];
if (!empty($rtn)) {
$rtn = new \DateTime($rtn);
}
return $rtn;
}
/**
* Set the value of Id / id.
*
* Must not be null.
* @param $value int
*/
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');
}
/**
* Set the value of BuildId / build_id.
*
* Must not be null.
* @param $value int
*/
public function setBuildId($value)
{
$this->_validateNotNull('BuildId', $value);
$this->_validateInt('BuildId', $value);
if ($this->data['build_id'] === $value) {
return;
}
$this->data['build_id'] = $value;
$this->_setModified('build_id');
}
/**
* Set the value of Plugin / plugin.
*
* Must not be null.
* @param $value string
*/
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');
}
/**
* Set the value of File / file.
*
* @param $value string
*/
public function setFile($value)
{
$this->_validateString('File', $value);
if ($this->data['file'] === $value) {
return;
}
$this->data['file'] = $value;
$this->_setModified('file');
}
/**
* Set the value of LineStart / line_start.
*
* @param $value int
*/
public function setLineStart($value)
{
$this->_validateInt('LineStart', $value);
if ($this->data['line_start'] === $value) {
return;
}
$this->data['line_start'] = $value;
$this->_setModified('line_start');
}
/**
* Set the value of LineEnd / line_end.
*
* @param $value int
*/
public function setLineEnd($value)
{
$this->_validateInt('LineEnd', $value);
if ($this->data['line_end'] === $value) {
return;
}
$this->data['line_end'] = $value;
$this->_setModified('line_end');
}
/**
* Set the value of Severity / severity.
*
* Must not be null.
* @param $value int
*/
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');
}
/**
* Set the value of Message / message.
*
* Must not be null.
* @param $value string
*/
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');
}
/**
* Set the value of CreatedDate / created_date.
*
* Must not be null.
* @param $value \DateTime
*/
public function setCreatedDate($value)
{
$this->_validateNotNull('CreatedDate', $value);
$this->_validateDate('CreatedDate', $value);
if ($this->data['created_date'] === $value) {
return;
}
$this->data['created_date'] = $value;
$this->_setModified('created_date');
}
/**
* Get the Build model for this BuildError by Id.
*
* @uses \PHPCI\Store\BuildStore::getById()
* @uses \PHPCI\Model\Build
* @return \PHPCI\Model\Build
*/
public function getBuild()
{
$key = $this->getBuildId();
if (empty($key)) {
return null;
}
$cacheKey = 'Cache.Build.' . $key;
$rtn = $this->cache->get($cacheKey, null);
if (empty($rtn)) {
$rtn = Factory::getStore('Build', 'PHPCI')->getById($key);
$this->cache->set($cacheKey, $rtn);
}
return $rtn;
}
/**
* Set Build - Accepts an ID, an array representing a Build or a Build model.
*
* @param $value mixed
*/
public function setBuild($value)
{
// Is this an instance of Build?
if ($value instanceof \PHPCI\Model\Build) {
return $this->setBuildObject($value);
}
// Is this an array representing a Build item?
if (is_array($value) && !empty($value['id'])) {
return $this->setBuildId($value['id']);
}
// Is this a scalar value representing the ID of this foreign key?
return $this->setBuildId($value);
}
/**
* Set Build - Accepts a Build model.
*
* @param $value \PHPCI\Model\Build
*/
public function setBuildObject(\PHPCI\Model\Build $value)
{
return $this->setBuildId($value->getId());
}
}

View file

@ -99,7 +99,7 @@ class BuildMetaBase extends Model
'default' => null,
),
'meta_value' => array(
'type' => 'mediumtext',
'type' => 'text',
'default' => null,
),
);

View file

@ -45,7 +45,6 @@ class ProjectBase extends Model
'ssh_public_key' => null,
'allow_public_status' => null,
'archived' => null,
'group_id' => null,
);
/**
@ -65,10 +64,8 @@ class ProjectBase extends Model
'ssh_public_key' => 'getSshPublicKey',
'allow_public_status' => 'getAllowPublicStatus',
'archived' => 'getArchived',
'group_id' => 'getGroupId',
// Foreign key getters:
'Group' => 'getGroup',
);
/**
@ -88,10 +85,8 @@ class ProjectBase extends Model
'ssh_public_key' => 'setSshPublicKey',
'allow_public_status' => 'setAllowPublicStatus',
'archived' => 'setArchived',
'group_id' => 'setGroupId',
// Foreign key setters:
'Group' => 'setGroup',
);
/**
@ -158,14 +153,10 @@ class ProjectBase extends Model
),
'archived' => array(
'type' => 'tinyint',
'length' => 1,
'length' => 4,
'nullable' => true,
'default' => null,
),
'group_id' => array(
'type' => 'int',
'length' => 11,
'default' => 1,
),
);
/**
@ -174,20 +165,12 @@ class ProjectBase extends Model
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
'idx_project_title' => array('columns' => 'title'),
'group_id' => array('columns' => 'group_id'),
);
/**
* @var array
*/
public $foreignKeys = array(
'project_ibfk_1' => array(
'local_col' => 'group_id',
'update' => 'CASCADE',
'delete' => '',
'table' => 'project_group',
'col' => 'id'
),
);
/**
@ -334,18 +317,6 @@ class ProjectBase extends Model
return $rtn;
}
/**
* Get the value of GroupId / group_id.
*
* @return int
*/
public function getGroupId()
{
$rtn = $this->data['group_id'];
return $rtn;
}
/**
* Set the value of Id / id.
*
@ -559,12 +530,10 @@ class ProjectBase extends Model
/**
* Set the value of Archived / archived.
*
* Must not be null.
* @param $value int
*/
public function setArchived($value)
{
$this->_validateNotNull('Archived', $value);
$this->_validateInt('Archived', $value);
if ($this->data['archived'] === $value) {
@ -576,83 +545,6 @@ class ProjectBase extends Model
$this->_setModified('archived');
}
/**
* Set the value of GroupId / group_id.
*
* Must not be null.
* @param $value int
*/
public function setGroupId($value)
{
$this->_validateNotNull('GroupId', $value);
$this->_validateInt('GroupId', $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.
*
* @uses \PHPCI\Store\ProjectGroupStore::getById()
* @uses \PHPCI\Model\ProjectGroup
* @return \PHPCI\Model\ProjectGroup
*/
public function getGroup()
{
$key = $this->getGroupId();
if (empty($key)) {
return null;
}
$cacheKey = 'Cache.ProjectGroup.' . $key;
$rtn = $this->cache->get($cacheKey, null);
if (empty($rtn)) {
$rtn = Factory::getStore('ProjectGroup', 'PHPCI')->getById($key);
$this->cache->set($cacheKey, $rtn);
}
return $rtn;
}
/**
* Set Group - Accepts an ID, an array representing a ProjectGroup or a ProjectGroup model.
*
* @param $value mixed
*/
public function setGroup($value)
{
// Is this an instance of ProjectGroup?
if ($value instanceof \PHPCI\Model\ProjectGroup) {
return $this->setGroupObject($value);
}
// Is this an array representing a ProjectGroup item?
if (is_array($value) && !empty($value['id'])) {
return $this->setGroupId($value['id']);
}
// Is this a scalar value representing the ID of this foreign key?
return $this->setGroupId($value);
}
/**
* Set Group - Accepts a ProjectGroup model.
*
* @param $value \PHPCI\Model\ProjectGroup
*/
public function setGroupObject(\PHPCI\Model\ProjectGroup $value)
{
return $this->setGroupId($value->getId());
}
/**
* Get Build models by ProjectId for this Project.
*

View file

@ -1,168 +0,0 @@
<?php
/**
* ProjectGroup base model for table: project_group
*/
namespace PHPCI\Model\Base;
use PHPCI\Model;
use b8\Store\Factory;
/**
* ProjectGroup Base Model
*/
class ProjectGroupBase extends Model
{
/**
* @var array
*/
public static $sleepable = array();
/**
* @var string
*/
protected $tableName = 'project_group';
/**
* @var string
*/
protected $modelName = 'ProjectGroup';
/**
* @var array
*/
protected $data = array(
'id' => null,
'title' => null,
);
/**
* @var array
*/
protected $getters = array(
// Direct property getters:
'id' => 'getId',
'title' => 'getTitle',
// Foreign key getters:
);
/**
* @var array
*/
protected $setters = array(
// Direct property setters:
'id' => 'setId',
'title' => 'setTitle',
// Foreign key setters:
);
/**
* @var array
*/
public $columns = array(
'id' => array(
'type' => 'int',
'length' => 11,
'primary_key' => true,
'auto_increment' => true,
'default' => null,
),
'title' => array(
'type' => 'varchar',
'length' => 100,
'default' => null,
),
);
/**
* @var array
*/
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
);
/**
* @var array
*/
public $foreignKeys = array(
);
/**
* Get the value of Id / id.
*
* @return int
*/
public function getId()
{
$rtn = $this->data['id'];
return $rtn;
}
/**
* Get the value of Title / title.
*
* @return string
*/
public function getTitle()
{
$rtn = $this->data['title'];
return $rtn;
}
/**
* Set the value of Id / id.
*
* Must not be null.
* @param $value int
*/
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');
}
/**
* Set the value of Title / title.
*
* Must not be null.
* @param $value string
*/
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');
}
/**
* Get Project models by GroupId for this ProjectGroup.
*
* @uses \PHPCI\Store\ProjectStore::getByGroupId()
* @uses \PHPCI\Model\Project
* @return \PHPCI\Model\Project[]
*/
public function getGroupProjects()
{
return Factory::getStore('Project', 'PHPCI')->getByGroupId($this->getId());
}
}

View file

@ -106,8 +106,6 @@ class UserBase extends Model
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
'idx_email' => array('unique' => true, 'columns' => 'email'),
'email' => array('unique' => true, 'columns' => 'email'),
'name' => array('columns' => 'name'),
);
/**

View file

@ -28,7 +28,7 @@ class Build extends BuildBase
const STATUS_SUCCESS = 2;
const STATUS_FAILED = 3;
public $currentBuildPath;
public $currentBuildPath = null;
/**
* Get link to commit from another source (i.e. Github)
@ -99,21 +99,16 @@ class Build extends BuildBase
{
$build_config = null;
// Try phpci.yml first:
if (is_file($buildPath . '/phpci.yml')) {
$build_config = file_get_contents($buildPath . '/phpci.yml');
}
// Try getting the project build config from the database:
if (empty($build_config)) {
$build_config = $this->getProject()->getBuildConfig();
}
// Try .phpci.yml
if (is_file($buildPath . '/.phpci.yml')) {
$build_config = file_get_contents($buildPath . '/.phpci.yml');
}
// Try phpci.yml first:
if (empty($build_config) && is_file($buildPath . '/phpci.yml')) {
$build_config = file_get_contents($buildPath . '/phpci.yml');
}
// Fall back to zero config plugins:
if (empty($build_config)) {
$build_config = $this->getZeroConfigPlugins($builder);
@ -213,36 +208,14 @@ class Build extends BuildBase
/**
* Allows specific build types (e.g. Github) to report violations back to their respective services.
* @param Builder $builder
* @param $plugin
* @param $file
* @param $line
* @param $message
* @param int $severity
* @param null $file
* @param null $lineStart
* @param null $lineEnd
* @return BuildError
* @return mixed
*/
public function reportError(
Builder $builder,
$plugin,
$message,
$severity = BuildError::SEVERITY_NORMAL,
$file = null,
$lineStart = null,
$lineEnd = null
) {
unset($builder);
$error = new BuildError();
$error->setBuild($this);
$error->setCreatedDate(new \DateTime());
$error->setPlugin($plugin);
$error->setMessage($message);
$error->setSeverity($severity);
$error->setFile($file);
$error->setLineStart($lineStart);
$error->setLineEnd($lineEnd);
return Factory::getStore('BuildError')->save($error);
public function reportError(Builder $builder, $file, $line, $message)
{
return array($builder, $file, $line, $message);
}
/**
@ -255,13 +228,7 @@ class Build extends BuildBase
if (!$this->getId()) {
return null;
}
if (empty($this->currentBuildPath)) {
$buildDirectory = $this->getId() . '_' . substr(md5(microtime(true)), 0, 5);
$this->currentBuildPath = PHPCI_BUILD_ROOT_DIR . $buildDirectory . DIRECTORY_SEPARATOR;
}
return $this->currentBuildPath;
return PHPCI_BUILD_ROOT_DIR . $this->getId();
}
/**
@ -277,25 +244,4 @@ class Build extends BuildBase
exec(sprintf(IS_WIN ? 'rmdir /S /Q "%s"' : 'rm -Rf "%s"', $buildPath));
}
/**
* Get the number of seconds a build has been running for.
* @return int
*/
public function getDuration()
{
$start = $this->getStarted();
if (empty($start)) {
return 0;
}
$end = $this->getFinished();
if (empty($end)) {
$end = new \DateTime();
}
return $end->getTimestamp() - $start->getTimestamp();
}
}

View file

@ -45,52 +45,39 @@ class GithubBuild extends RemoteGitBuild
{
$token = \b8\Config::getInstance()->get('phpci.github.token');
if (empty($token) || empty($this->data['id'])) {
if (empty($token)) {
return;
}
$project = $this->getProject();
if (empty($project)) {
return;
}
$url = 'https://api.github.com/repos/'.$project->getReference().'/statuses/'.$this->getCommitId();
$http = new \b8\HttpClient();
switch ($this->getStatus()) {
switch($this->getStatus())
{
case 0:
case 1:
$status = 'pending';
$description = 'PHPCI build running.';
break;
case 2:
$status = 'success';
$description = 'PHPCI build passed.';
break;
case 3:
$status = 'failure';
$description = 'PHPCI build failed.';
break;
default:
$status = 'error';
$description = 'PHPCI build failed to complete.';
break;
}
$phpciUrl = \b8\Config::getInstance()->get('phpci.url');
$params = array(
'state' => $status,
'target_url' => $phpciUrl . '/build/view/' . $this->getId(),
'description' => $description,
'context' => 'PHPCI',
);
$params = array( 'state' => $status,
'target_url' => $phpciUrl . '/build/view/' . $this->getId());
$headers = array(
'Authorization: token ' . $token,
'Content-Type: application/x-www-form-urlencoded'
);
);
$http->setHeaders($headers);
$http->request('POST', $url, json_encode($params));
@ -118,14 +105,10 @@ class GithubBuild extends RemoteGitBuild
{
$rtn = parent::getCommitMessage($this->data['commit_message']);
$project = $this->getProject();
if (!is_null($project)) {
$reference = $project->getReference();
$commitLink = '<a target="_blank" href="https://github.com/' . $reference . '/issues/$1">#$1</a>';
$rtn = preg_replace('/\#([0-9]+)/', $commitLink, $rtn);
$rtn = preg_replace('/\@([a-zA-Z0-9_]+)/', '<a target="_blank" href="https://github.com/$1">@$1</a>', $rtn);
}
$reference = $this->getProject()->getReference();
$commitLink = '<a target="_blank" href="https://github.com/' . $reference . '/issues/$1">#$1</a>';
$rtn = preg_replace('/\#([0-9]+)/', $commitLink, $rtn);
$rtn = preg_replace('/\@([a-zA-Z0-9_]+)/', '<a target="_blank" href="https://github.com/$1">@$1</a>', $rtn);
return $rtn;
}
@ -151,7 +134,7 @@ class GithubBuild extends RemoteGitBuild
$link = 'https://github.com/' . $reference . '/';
$link .= 'blob/' . $branch . '/';
$link .= '{FILE}';
$link .= '#L{LINE}-L{LINE_END}';
$link .= '#L{LINE}';
return $link;
}
@ -190,16 +173,9 @@ class GithubBuild extends RemoteGitBuild
/**
* @inheritDoc
*/
public function reportError(
Builder $builder,
$plugin,
$message,
$severity = BuildError::SEVERITY_NORMAL,
$file = null,
$lineStart = null,
$lineEnd = null
) {
$diffLineNumber = $this->getDiffLineNumber($builder, $file, $lineStart);
public function reportError(Builder $builder, $file, $line, $message)
{
$diffLineNumber = $this->getDiffLineNumber($builder, $file, $line);
if (!is_null($diffLineNumber)) {
$helper = new Github();
@ -214,8 +190,6 @@ class GithubBuild extends RemoteGitBuild
$helper->createCommitComment($repo, $commit, $file, $diffLineNumber, $message);
}
}
return parent::reportError($builder, $plugin, $message, $severity, $file, $lineStart, $lineEnd);
}
/**
@ -227,8 +201,6 @@ class GithubBuild extends RemoteGitBuild
*/
protected function getDiffLineNumber(Builder $builder, $file, $line)
{
$line = (integer)$line;
$builder->logExecOutput(false);
$prNumber = $this->getExtra('pull_request_number');
@ -249,6 +221,6 @@ class GithubBuild extends RemoteGitBuild
$helper = new Diff();
$lines = $helper->getLinePositions($diff);
return isset($lines[$line]) ? $lines[$line] : null;
return $lines[$line];
}
}

View file

@ -1,63 +0,0 @@
<?php
/**
* BuildError model for table: build_error
*/
namespace PHPCI\Model;
use PHPCI\Model\Base\BuildErrorBase;
/**
* BuildError Model
* @uses PHPCI\Model\Base\BuildErrorBase
*/
class BuildError extends BuildErrorBase
{
const SEVERITY_CRITICAL = 0;
const SEVERITY_HIGH = 1;
const SEVERITY_NORMAL = 2;
const SEVERITY_LOW = 3;
/**
* 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 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';
}
}
}

View file

@ -50,29 +50,6 @@ class Project extends ProjectBase
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 = array('branch' => $branch, 'project_id' => $this->getId());
$order = array('id' => 'DESC');
$builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 1, array(), $order);
if (is_array($builds['items']) && count($builds['items'])) {
$previous = array_shift($builds['items']);
if (isset($previous) && $previous instanceof Build) {
return $previous;
}
}
return null;
}
/**
* Store this project's access_information data
* @param string|array $value
@ -96,7 +73,7 @@ class Project extends ProjectBase
$info = $this->data['access_information'];
// Handle old-format (serialized) access information first:
if (!empty($info) && !in_array(substr($info, 0, 1), array('{', '['))) {
if (!empty($info) && substr($info, 0, 1) != '{') {
$data = unserialize($info);
} else {
$data = json_decode($info, true);

View file

@ -1,18 +0,0 @@
<?php
/**
* ProjectGroup model for table: project_group
*/
namespace PHPCI\Model;
use PHPCI\Model\Base\ProjectGroupBase;
/**
* ProjectGroup Model
* @uses PHPCI\Model\Base\ProjectGroupBase
*/
class ProjectGroup extends ProjectGroupBase
{
// This class has been left blank so that you can modify it - changes in this file will not be overwritten.
}

View file

@ -12,7 +12,6 @@ namespace PHPCI\Plugin;
use PHPCI\Builder;
use PHPCI\Helper\Lang;
use PHPCI\Model\Build;
use PHPCI\Model\BuildError;
/**
* Behat BDD Plugin
@ -120,14 +119,7 @@ class Behat implements \PHPCI\Plugin
'line' => $lineParts[1]
);
$this->build->reportError(
$this->phpci,
'behat',
'Behat scenario failed.',
BuildError::SEVERITY_HIGH,
$lineParts[0],
$lineParts[1]
);
$this->build->reportError($this->phpci, $lineParts[0], $lineParts[1], 'Behat scenario failed.');
}
}

View file

@ -38,19 +38,19 @@ class Campfire implements \PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$this->phpci = $phpci;
$this->build = $build;
$this->message = $options['message'];
$this->phpci = $phpci;
$this->build = $build;
$this->message = $options['message'];
$this->userAgent = "PHPCI/1.0 (+http://www.phptesting.org/)";
$this->cookie = "phpcicookie";
$this->cookie = "phpcicookie";
$buildSettings = $phpci->getConfig('build_settings');
if (isset($buildSettings['campfire'])) {
$campfire = $buildSettings['campfire'];
$this->url = $campfire['url'];
$campfire = $buildSettings['campfire'];
$this->url = $campfire['url'];
$this->authToken = $campfire['authToken'];
$this->roomId = $campfire['roomId'];
$this->roomId = $campfire['roomId'];
} else {
throw new \Exception(Lang::get('no_campfire_settings'));
}
@ -63,7 +63,7 @@ class Campfire implements \PHPCI\Plugin
*/
public function execute()
{
$url = PHPCI_URL . "build/view/" . $this->build->getId();
$url = PHPCI_URL."build/view/".$this->build->getId();
$message = str_replace("%buildurl%", $url, $this->message);
$this->joinRoom($this->roomId);
$status = $this->speak($message, $this->roomId);
@ -101,7 +101,6 @@ class Campfire implements \PHPCI\Plugin
public function speak($message, $roomId, $isPaste = false)
{
$page = '/room/'.$roomId.'/speak.json';
if ($isPaste) {
$type = 'PasteMessage';
} else {
@ -144,12 +143,10 @@ class Campfire implements \PHPCI\Plugin
// We tend to get one space with an otherwise blank response
$output = trim($output);
if (strlen($output)) {
/* Responses are JSON. Decode it to a data structure */
return json_decode($output);
}
// Simple 200 OK response (such as for joining a room)
return true;
}

View file

@ -39,9 +39,9 @@ class CleanBuild implements \PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$this->phpci = $phpci;
$this->build = $build;
$this->remove = isset($options['remove']) && is_array($options['remove']) ? $options['remove'] : array();
$this->phpci = $phpci;
$this->build = $build;
$this->remove = isset($options['remove']) && is_array($options['remove']) ? $options['remove'] : array();
}
/**
@ -57,7 +57,7 @@ class CleanBuild implements \PHPCI\Plugin
$this->phpci->executeCommand($cmd, $this->phpci->buildPath . 'composer.lock');
$success = true;
foreach ($this->remove as $file) {
$ok = $this->phpci->executeCommand($cmd, $this->phpci->buildPath . $file);

View file

@ -83,7 +83,7 @@ class Codeception implements \PHPCI\Plugin, \PHPCI\ZeroConfigPlugin
{
$this->phpci = $phpci;
$this->build = $build;
$this->path = 'tests' . DIRECTORY_SEPARATOR . '_output' . DIRECTORY_SEPARATOR;
$this->path = 'tests/_output/';
if (empty($options['config'])) {
$this->ymlConfigFile = self::findConfigFile($this->phpci->buildPath);
@ -99,7 +99,7 @@ class Codeception implements \PHPCI\Plugin, \PHPCI\ZeroConfigPlugin
}
/**
* Runs Codeception tests
* Runs Codeception tests, optionally using specified config file(s).
*/
public function execute()
{
@ -130,7 +130,6 @@ class Codeception implements \PHPCI\Plugin, \PHPCI\ZeroConfigPlugin
}
$cmd = 'cd "%s" && ' . $codecept . ' run -c "%s" --xml ' . $this->args;
if (IS_WIN) {
$cmd = 'cd /d "%s" && ' . $codecept . ' run -c "%s" --xml ' . $this->args;
}
@ -142,20 +141,21 @@ class Codeception implements \PHPCI\Plugin, \PHPCI\ZeroConfigPlugin
'Codeception XML path: '. $this->phpci->buildPath . $this->path . 'report.xml',
Loglevel::DEBUG
);
$xml = file_get_contents($this->phpci->buildPath . $this->path . 'report.xml', false);
$parser = new Parser($this->phpci, $xml);
$output = $parser->parse();
$meta = array(
'tests' => $parser->getTotalTests(),
'tests' => $parser->getTotalTests(),
'timetaken' => $parser->getTotalTimeTaken(),
'failures' => $parser->getTotalFailures()
'failures' => $parser->getTotalFailures()
);
$this->build->storeMeta('codeception-meta', $meta);
$this->build->storeMeta('codeception-data', $output);
$this->build->storeMeta('codeception-errors', $parser->getTotalFailures());
$this->phpci->logExecOutput(true);
return $success;

View file

@ -38,7 +38,7 @@ class Composer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
*/
public static function canExecute($stage, Builder $builder, Build $build)
{
$path = $builder->buildPath . DIRECTORY_SEPARATOR . 'composer.json';
$path = $builder->buildPath . '/composer.json';
if (file_exists($path) && $stage == 'setup') {
return true;
@ -55,17 +55,16 @@ class Composer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$path = $phpci->buildPath;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = $path;
$this->action = 'install';
$path = $phpci->buildPath;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = $path;
$this->action = 'install';
$this->preferDist = false;
$this->preferSource = false;
$this->nodev = false;
$this->nodev = false;
if (array_key_exists('directory', $options)) {
$this->directory = $path . DIRECTORY_SEPARATOR . $options['directory'];
$this->directory = $path . '/' . $options['directory'];
}
if (array_key_exists('action', $options)) {
@ -76,11 +75,6 @@ class Composer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$this->preferDist = (bool)$options['prefer_dist'];
}
if (array_key_exists('prefer_source', $options)) {
$this->preferDist = false;
$this->preferSource = (bool)$options['prefer_source'];
}
if (array_key_exists('no_dev', $options)) {
$this->nodev = (bool)$options['no_dev'];
}
@ -103,12 +97,10 @@ class Composer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
if ($this->preferDist) {
$this->phpci->log('Using --prefer-dist flag');
$cmd .= ' --prefer-dist';
}
if ($this->preferSource) {
$cmd .= '--prefer-dist';
} else {
$this->phpci->log('Using --prefer-source flag');
$cmd .= ' --prefer-source';
$cmd .= '--prefer-source';
}
if ($this->nodev) {

View file

@ -35,12 +35,12 @@ class CopyBuild implements \PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$path = $phpci->buildPath;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = isset($options['directory']) ? $options['directory'] : $path;
$this->wipe = isset($options['wipe']) ? (bool)$options['wipe'] : false;
$this->ignore = isset($options['respect_ignore']) ? (bool)$options['respect_ignore'] : false;
$path = $phpci->buildPath;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = isset($options['directory']) ? $options['directory'] : $path;
$this->wipe = isset($options['wipe']) ? (bool)$options['wipe'] : false;
$this->ignore = isset($options['respect_ignore']) ? (bool)$options['respect_ignore'] : false;
}
/**

View file

@ -1,73 +0,0 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Plugin;
use b8\HttpClient;
use PHPCI\Builder;
use PHPCI\Model\Build;
/**
* Integrates PHPCI with Deployer: https://github.com/rebelinblue/deployer
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Plugins
*/
class Deployer implements \PHPCI\Plugin
{
protected $webhookUrl;
protected $reason;
protected $updateOnly;
/**
* Set up the plugin, configure options, etc.
* @param Builder $phpci
* @param Build $build
* @param array $options
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$this->phpci = $phpci;
$this->build = $build;
$this->reason = 'PHPCI Build #%BUILD% - %COMMIT_MESSAGE%';
if (isset($options['webhook_url'])) {
$this->webhookUrl = $options['webhook_url'];
}
if (isset($options['reason'])) {
$this->reason = $options['reason'];
}
$this->updateOnly = isset($options['update_only']) ? (bool) $options['update_only'] : true;
}
/**
* Copies files from the root of the build directory into the target folder
*/
public function execute()
{
if (empty($this->webhookUrl)) {
$this->phpci->logFailure('You must specify a webhook URL.');
return false;
}
$http = new HttpClient();
$response = $http->post($this->webhookUrl, array(
'reason' => $this->phpci->interpolate($this->reason),
'source' => 'PHPCI',
'url' => $this->phpci->interpolate('%BUILD_URI%'),
'branch' => $this->phpci->interpolate('%BRANCH%'),
'update_only' => $this->updateOnly
));
return $response['success'];
}
}

View file

@ -52,9 +52,9 @@ class Email implements \PHPCI\Plugin
Build $build,
array $options = array()
) {
$this->phpci = $phpci;
$this->build = $build;
$this->options = $options;
$this->phpci = $phpci;
$this->build = $build;
$this->options = $options;
}
/**
@ -134,7 +134,7 @@ class Email implements \PHPCI\Plugin
* Send an email to a list of specified subjects.
*
* @param array $toAddresses
* List of destination addresses for message.
* List of destinatary of message.
* @param string $subject
* Mail subject
* @param string $body

View file

@ -52,7 +52,7 @@ class Env implements \PHPCI\Plugin
// This allows the standard syntax: "FOO: bar"
$env_var = "$key=$value";
}
if (!putenv($this->phpci->interpolate($env_var))) {
$success = false;
$this->phpci->logFailure(Lang::get('unable_to_set_env'));

View file

@ -52,7 +52,7 @@ class Grunt implements \PHPCI\Plugin
// Handle options:
if (isset($options['directory'])) {
$this->directory = $path . DIRECTORY_SEPARATOR . $options['directory'];
$this->directory = $path . '/' . $options['directory'];
}
if (isset($options['task'])) {

View file

@ -52,7 +52,7 @@ class Gulp implements \PHPCI\Plugin
// Handle options:
if (isset($options['directory'])) {
$this->directory = $path . DIRECTORY_SEPARATOR . $options['directory'];
$this->directory = $path . '/' . $options['directory'];
}
if (isset($options['task'])) {

View file

@ -41,9 +41,9 @@ class Lint implements PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$this->phpci = $phpci;
$this->phpci = $phpci;
$this->build = $build;
$this->directories = array('');
$this->directories = array('');
$this->ignore = $phpci->ignore;
if (!empty($options['directory'])) {
@ -93,7 +93,7 @@ class Lint implements PHPCI\Plugin
if ($item->isFile() && $item->getExtension() == 'php' && !$this->lintFile($php, $itemPath)) {
$success = false;
} elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($php, $itemPath . DIRECTORY_SEPARATOR)) {
} elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($php, $itemPath . '/')) {
$success = false;
}

View file

@ -166,11 +166,10 @@ class Mysql implements \PHPCI\Plugin
$args = array(
':import_file' => escapeshellarg($import_file),
':decomp_cmd' => $decomp_cmd,
':host' => escapeshellarg($this->host),
':user' => escapeshellarg($this->user),
':pass' => escapeshellarg($this->pass),
':database' => ($database === null)? '': escapeshellarg($database),
);
return strtr('cat :import_file :decomp_cmd | mysql -h:host -u:user -p:pass :database', $args);
return strtr('cat :import_file :decomp_cmd | mysql -u:user -p:pass :database', $args);
}
}

View file

@ -33,12 +33,12 @@ class PackageBuild implements \PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$path = $phpci->buildPath;
$this->build = $build;
$this->phpci = $phpci;
$this->directory = isset($options['directory']) ? $options['directory'] : $path;
$this->filename = isset($options['filename']) ? $options['filename'] : 'build';
$this->format = isset($options['format']) ? $options['format'] : 'zip';
$path = $phpci->buildPath;
$this->build = $build;
$this->phpci = $phpci;
$this->directory = isset($options['directory']) ? $options['directory'] : $path;
$this->filename = isset($options['filename']) ? $options['filename'] : 'build';
$this->format = isset($options['format']) ? $options['format'] : 'zip';
}
/**
@ -46,7 +46,7 @@ class PackageBuild implements \PHPCI\Plugin
*/
public function execute()
{
$path = $this->phpci->buildPath;
$path = $this->phpci->buildPath;
$build = $this->build;
if ($this->directory == $path) {
@ -69,7 +69,8 @@ class PackageBuild implements \PHPCI\Plugin
}
foreach ($this->format as $format) {
switch ($format) {
switch($format)
{
case 'tar':
$cmd = 'tar cfz "%s/%s.tar.gz" ./*';
break;

View file

@ -73,11 +73,8 @@ class Pdepend implements \PHPCI\Plugin
*/
public function execute()
{
if (!file_exists($this->location)) {
mkdir($this->location);
}
if (!is_writable($this->location)) {
throw new \Exception(sprintf('The location %s is not writable or does not exist.', $this->location));
throw new \Exception(sprintf('The location %s is not writable.', $this->location));
}
$pdepend = $this->phpci->findBinary('pdepend');

View file

@ -73,9 +73,9 @@ class Pgsql implements \PHPCI\Plugin
}
/**
* Connects to PgSQL and runs a specified set of queries.
* @return boolean
*/
* Connects to PgSQL and runs a specified set of queries.
* @return boolean
*/
public function execute()
{
try {

View file

@ -213,7 +213,7 @@ class Phar implements \PHPCI\Plugin
$content = '';
$filename = $this->getStub();
if ($filename) {
$content = file_get_contents($this->getPHPCI()->buildPath . DIRECTORY_SEPARATOR . $this->getStub());
$content = file_get_contents($this->getPHPCI()->buildPath . '/' . $this->getStub());
}
return $content;
}
@ -227,8 +227,7 @@ class Phar implements \PHPCI\Plugin
$success = false;
try {
$file = $this->getDirectory() . DIRECTORY_SEPARATOR . $this->getFilename();
$phar = new PHPPhar($file, 0, $this->getFilename());
$phar = new PHPPhar($this->getDirectory() . '/' . $this->getFilename(), 0, $this->getFilename());
$phar->buildFromDirectory($this->getPHPCI()->buildPath, $this->getRegExp());
$stub = $this->getStubContent();
@ -237,6 +236,7 @@ class Phar implements \PHPCI\Plugin
}
$success = true;
} catch (Exception $e) {
$this->getPHPCI()->log(Lang::get('phar_internal_error'));
$this->getPHPCI()->log($e->getMessage());

View file

@ -47,7 +47,7 @@ class Phing implements \PHPCI\Plugin
* Set working directory
*/
if (isset($options['directory'])) {
$directory = $phpci->buildPath . DIRECTORY_SEPARATOR . $options['directory'];
$directory = $phpci->buildPath . '/' . $options['directory'];
} else {
$directory = $phpci->buildPath;
}
@ -255,7 +255,7 @@ class Phing implements \PHPCI\Plugin
*/
public function setPropertyFile($propertyFile)
{
if (!file_exists($this->getDirectory() . DIRECTORY_SEPARATOR . $propertyFile)) {
if (!file_exists($this->getDirectory() . '/' . $propertyFile)) {
throw new \Exception(Lang::get('property_file_missing'));
}

View file

@ -12,7 +12,6 @@ namespace PHPCI\Plugin;
use PHPCI;
use PHPCI\Builder;
use PHPCI\Model\Build;
use PHPCI\Model\BuildError;
/**
* PHP Code Sniffer Plugin - Allows PHP Code Sniffer testing.
@ -164,13 +163,14 @@ class PhpCodeSniffer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
);
$output = $this->phpci->getLastOutput();
list($errors, $warnings) = $this->processReport($output);
list($errors, $warnings, $data) = $this->processReport($output);
$this->phpci->logExecOutput(true);
$success = true;
$this->build->storeMeta('phpcs-warnings', $warnings);
$this->build->storeMeta('phpcs-errors', $errors);
$this->build->storeMeta('phpcs-data', $data);
if ($this->allowed_warnings != -1 && $warnings > $this->allowed_warnings) {
$success = false;
@ -226,21 +226,23 @@ class PhpCodeSniffer implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$errors = $data['totals']['errors'];
$warnings = $data['totals']['warnings'];
$rtn = array();
foreach ($data['files'] as $fileName => $file) {
$fileName = str_replace($this->phpci->buildPath, '', $fileName);
foreach ($file['messages'] as $message) {
$this->build->reportError(
$this->phpci,
'php_code_sniffer',
'PHPCS: ' . $message['message'],
$message['type'] == 'ERROR' ? BuildError::SEVERITY_HIGH : BuildError::SEVERITY_LOW,
$fileName,
$message['line']
$this->build->reportError($this->phpci, $fileName, $message['line'], 'PHPCS: ' . $message['message']);
$rtn[] = array(
'file' => $fileName,
'line' => $message['line'],
'type' => $message['type'],
'message' => $message['message'],
);
}
}
return array($errors, $warnings);
return array($errors, $warnings, $rtn);
}
}

37
PHPCI/Plugin/PhpCpd.php Executable file → Normal file
View file

@ -12,7 +12,6 @@ namespace PHPCI\Plugin;
use PHPCI\Builder;
use PHPCI\Helper\Lang;
use PHPCI\Model\Build;
use PHPCI\Model\BuildError;
/**
* PHP Copy / Paste Detector - Allows PHP Copy / Paste Detector testing.
@ -29,7 +28,7 @@ class PhpCpd implements \PHPCI\Plugin
/**
* @var string, based on the assumption the root may not hold the code to be
* tested, extends the base path
* tested, exteds the base path
*/
protected $path;
@ -50,12 +49,17 @@ class PhpCpd implements \PHPCI\Plugin
$this->build = $build;
$this->path = $phpci->buildPath;
$this->standard = 'PSR1';
$this->ignore = $phpci->ignore;
if (!empty($options['path'])) {
$this->path = $phpci->buildPath . $options['path'];
}
if (!empty($options['standard'])) {
$this->standard = $options['standard'];
}
if (!empty($options['ignore'])) {
$this->ignore = $options['ignore'];
}
@ -70,9 +74,9 @@ class PhpCpd implements \PHPCI\Plugin
if (count($this->ignore)) {
$map = function ($item) {
// remove the trailing slash
$item = rtrim($item, DIRECTORY_SEPARATOR);
$item = (substr($item, -1) == '/' ? substr($item, 0, -1) : $item);
if (is_file(rtrim($this->path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $item)) {
if (is_file($this->path . '/' . $item)) {
return ' --names-exclude ' . $item;
} else {
return ' --exclude ' . $item;
@ -93,8 +97,9 @@ class PhpCpd implements \PHPCI\Plugin
print $this->phpci->getLastOutput();
$errorCount = $this->processReport(file_get_contents($tmpfilename));
list($errorCount, $data) = $this->processReport(file_get_contents($tmpfilename));
$this->build->storeMeta('phpcpd-warnings', $errorCount);
$this->build->storeMeta('phpcpd-data', $data);
unlink($tmpfilename);
@ -117,11 +122,20 @@ class PhpCpd implements \PHPCI\Plugin
}
$warnings = 0;
$data = array();
foreach ($xml->duplication as $duplication) {
foreach ($duplication->file as $file) {
$fileName = (string)$file['path'];
$fileName = str_replace($this->phpci->buildPath, '', $fileName);
$data[] = array(
'file' => $fileName,
'line_start' => (int) $file['line'],
'line_end' => (int) $file['line'] + (int) $duplication['lines'],
'code' => (string) $duplication->codefragment
);
$message = <<<CPD
Copy and paste detected:
@ -130,20 +144,13 @@ Copy and paste detected:
```
CPD;
$this->build->reportError(
$this->phpci,
'php_cpd',
$message,
BuildError::SEVERITY_NORMAL,
$fileName,
$file['line'],
(int) $file['line'] + (int) $duplication['lines']
);
$this->build->reportError($this->phpci, $fileName, $file['line'], $message);
}
$warnings++;
}
return $warnings;
return array($warnings, $data);
}
}

View file

@ -14,7 +14,7 @@ use PHPCI\Helper\Lang;
use PHPCI\Model\Build;
/**
* PHP CS Fixer - Works with the PHP Coding Standards Fixer for testing coding standards.
* PHP CS Fixer - Works with the PHP CS Fixer for testing coding standards.
* @author Gabriel Baker <gabriel@autonomicpilot.co.uk>
* @package PHPCI
* @subpackage Plugins
@ -32,10 +32,10 @@ class PhpCsFixer implements \PHPCI\Plugin
protected $build;
protected $workingDir = '';
protected $level = ' --level=psr2';
protected $verbose = '';
protected $diff = '';
protected $levels = array('psr0', 'psr1', 'psr2', 'symfony');
protected $level = ' --level=all';
protected $verbose = '';
protected $diff = '';
protected $levels = array('psr0', 'psr1', 'psr2', 'all');
/**
* Standard Constructor

View file

@ -143,6 +143,7 @@ class PhpDocblockChecker implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$success = true;
$this->build->storeMeta('phpdoccheck-warnings', $errors);
$this->build->storeMeta('phpdoccheck-data', $output);
$this->reportErrors($output);
if ($this->allowed_warnings != -1 && $errors > $this->allowed_warnings) {
@ -159,22 +160,13 @@ class PhpDocblockChecker implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
protected function reportErrors($output)
{
foreach ($output as $error) {
$message = 'Class ' . $error['class'] . ' is missing a docblock.';
$severity = PHPCI\Model\BuildError::SEVERITY_LOW;
$message = 'Class ' . $error['class'] . ' does not have a Docblock comment.';
if ($error['type'] == 'method') {
$message = $error['class'] . '::' . $error['method'] . ' is missing a docblock.';
$severity = PHPCI\Model\BuildError::SEVERITY_NORMAL;
$message = 'Method ' . $error['class'] . '::' . $error['method'] . ' does not have a Docblock comment.';
}
$this->build->reportError(
$this->phpci,
'php_docblock_checker',
$message,
$severity,
$error['file'],
$error['line']
);
$this->build->reportError($this->phpci, $error['file'], $error['line'], $message);
}
}
}

View file

@ -69,20 +69,19 @@ class PhpLoc implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
public function execute()
{
$ignore = '';
if (count($this->phpci->ignore)) {
$map = function ($item) {
return ' --exclude ' . rtrim($item, DIRECTORY_SEPARATOR);
$map = function ($item) {
return ' --exclude ' . (substr($item, -1) == '/' ? substr($item, 0, -1) : $item);
};
$ignore = array_map($map, $this->phpci->ignore);
$ignore = implode('', $ignore);
}
$phploc = $this->phpci->findBinary('phploc');
$success = $this->phpci->executeCommand($phploc . ' %s "%s"', $ignore, $this->directory);
$output = $this->phpci->getLastOutput();
$output = $this->phpci->getLastOutput();
if (preg_match_all('/\((LOC|CLOC|NCLOC|LLOC)\)\s+([0-9]+)/', $output, $matches)) {
$data = array();

View file

@ -38,7 +38,7 @@ class PhpMessDetector implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
/**
* @var string, based on the assumption the root may not hold the code to be
* tested, extends the base path only if the provided path is relative. Absolute
* tested, exteds the base path only if the provided path is relative. Absolute
* paths are used verbatim
*/
protected $path;
@ -50,7 +50,7 @@ class PhpMessDetector implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
/**
* Array of PHPMD rules. Can be one of the builtins (codesize, unusedcode, naming, design, controversial)
* or a filename (detected by checking for a / in it), either absolute or relative to the project root.
* or a filenname (detected by checking for a / in it), either absolute or relative to the project root.
* @var array
*/
protected $rules;
@ -123,8 +123,9 @@ class PhpMessDetector implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$this->executePhpMd($phpmdBinaryPath);
$errorCount = $this->processReport(trim($this->phpci->getLastOutput()));
list($errorCount, $data) = $this->processReport(trim($this->phpci->getLastOutput()));
$this->build->storeMeta('phpmd-warnings', $errorCount);
$this->build->storeMeta('phpmd-data', $data);
return $this->wasLastExecSuccessful($errorCount);
}
@ -157,6 +158,7 @@ class PhpMessDetector implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
}
$warnings = 0;
$data = array();
foreach ($xml->file as $file) {
$fileName = (string)$file['name'];
@ -164,20 +166,22 @@ class PhpMessDetector implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
foreach ($file->violation as $violation) {
$warnings++;
$this->build->reportError(
$this->phpci,
'php_mess_detector',
(string)$violation,
PHPCI\Model\BuildError::SEVERITY_HIGH,
$fileName,
(int)$violation['beginline'],
(int)$violation['endline']
$warning = array(
'file' => $fileName,
'line_start' => (int)$violation['beginline'],
'line_end' => (int)$violation['endline'],
'rule' => (string)$violation['rule'],
'ruleset' => (string)$violation['ruleset'],
'priority' => (int)$violation['priority'],
'message' => (string)$violation,
);
$this->build->reportError($this->phpci, $fileName, (int)$violation['beginline'], (string)$violation);
$data[] = $warning;
}
}
return $warnings;
return array($warnings, $data);
}
/**

View file

@ -55,10 +55,10 @@ class PhpParallelLint implements \PHPCI\Plugin
*/
public function __construct(Builder $phpci, Build $build, array $options = array())
{
$this->phpci = $phpci;
$this->build = $build;
$this->directory = $phpci->buildPath;
$this->ignore = $this->phpci->ignore;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = $phpci->buildPath;
$this->ignore = $this->phpci->ignore;
if (isset($options['directory'])) {
$this->directory = $phpci->buildPath.$options['directory'];

View file

@ -155,7 +155,7 @@ class PhpTalLint implements PHPCI\Plugin
if (!$this->lintFile($itemPath)) {
$success = false;
}
} elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($itemPath . DIRECTORY_SEPARATOR)) {
} elseif ($item->isDir() && $this->recursive && !$this->lintDirectory($itemPath . '/')) {
$success = false;
}
@ -202,9 +202,7 @@ class PhpTalLint implements PHPCI\Plugin
list($suffixes, $tales) = $this->getFlags();
$lint = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;
$lint .= 'vendor' . DIRECTORY_SEPARATOR . 'phptal' . DIRECTORY_SEPARATOR . 'phptal' . DIRECTORY_SEPARATOR;
$lint .= 'tools' . DIRECTORY_SEPARATOR . 'phptal_lint.php';
$lint = dirname(__FILE__) . '/../../vendor/phptal/phptal/tools/phptal_lint.php';
$cmd = '/usr/bin/env php ' . $lint . ' %s %s "%s"';
$this->phpci->executeCommand($cmd, $suffixes, $tales, $this->phpci->buildPath . $path);
@ -224,7 +222,7 @@ class PhpTalLint implements PHPCI\Plugin
$row = str_replace('(use -i to include your custom modifier functions)', '', $row);
$message = str_replace($name . ': ', '', $row);
$parts = explode(' (line ', $message);
$message = trim($parts[0]);

View file

@ -76,8 +76,8 @@ class PhpUnit implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
return 'phpunit.xml';
}
if (file_exists($buildPath . 'tests' . DIRECTORY_SEPARATOR . 'phpunit.xml')) {
return 'tests' . DIRECTORY_SEPARATOR . 'phpunit.xml';
if (file_exists($buildPath . 'tests/phpunit.xml')) {
return 'tests/phpunit.xml';
}
if (file_exists($buildPath . 'phpunit.xml.dist')) {
@ -85,7 +85,7 @@ class PhpUnit implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
}
if (file_exists($buildPath . 'tests/phpunit.xml.dist')) {
return 'tests' . DIRECTORY_SEPARATOR . 'phpunit.xml.dist';
return 'tests/phpunit.xml.dist';
}
return null;
@ -133,7 +133,7 @@ class PhpUnit implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
}
if (isset($options['coverage'])) {
$this->coverage = ' --coverage-html ' . $this->phpci->interpolate($options['coverage']) . ' ';
$this->coverage = " --coverage-html {$options['coverage']} ";
}
}
@ -194,7 +194,7 @@ class PhpUnit implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
} else {
if ($this->runFrom) {
$curdir = getcwd();
chdir($this->phpci->buildPath . DIRECTORY_SEPARATOR . $this->runFrom);
chdir($this->phpci->buildPath.'/'.$this->runFrom);
}
$phpunit = $this->phpci->findBinary('phpunit');

View file

@ -24,7 +24,6 @@ class SlackNotify implements \PHPCI\Plugin
private $username;
private $message;
private $icon;
private $show_status;
/**
* Set up the plugin, configure options, etc.
@ -61,12 +60,6 @@ class SlackNotify implements \PHPCI\Plugin
$this->username = 'PHPCI';
}
if (isset($options['show_status'])) {
$this->show_status = (bool) $options['show_status'];
} else {
$this->show_status = true;
}
if (isset($options['icon'])) {
$this->icon = $options['icon'];
}
@ -81,7 +74,31 @@ class SlackNotify implements \PHPCI\Plugin
*/
public function execute()
{
$body = $this->phpci->interpolate($this->message);
$message = $this->phpci->interpolate($this->message);
$successfulBuild = $this->build->isSuccessful();
if ($successfulBuild) {
$status = 'Success';
$color = 'good';
} else {
$status = 'Failed';
$color = 'danger';
}
// Build up the attachment data
$attachment = new \Maknz\Slack\Attachment(array(
'fallback' => $message,
'pretext' => $message,
'color' => $color,
'fields' => array(
new \Maknz\Slack\AttachmentField(array(
'title' => 'Status',
'value' => $status,
'short' => false
))
)
));
$client = new \Maknz\Slack\Client($this->webHook);
@ -99,39 +116,12 @@ class SlackNotify implements \PHPCI\Plugin
$message->setIcon($this->icon);
}
// Include an attachment which shows the status and hide the message
if ($this->show_status) {
$successfulBuild = $this->build->isSuccessful();
$message->attach($attachment);
if ($successfulBuild) {
$status = 'Success';
$color = 'good';
} else {
$status = 'Failed';
$color = 'danger';
}
$success = true;
// Build up the attachment data
$attachment = new \Maknz\Slack\Attachment(array(
'fallback' => $body,
'pretext' => $body,
'color' => $color,
'fields' => array(
new \Maknz\Slack\AttachmentField(array(
'title' => 'Status',
'value' => $status,
'short' => false
))
)
));
$message->send('');
$message->attach($attachment);
$body = '';
}
$message->send($body);
return true;
return $success;
}
}

View file

@ -124,11 +124,12 @@ class TechnicalDebt implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$success = true;
$this->phpci->logExecOutput(false);
$errorCount = $this->getErrorList();
list($errorCount, $data) = $this->getErrorList();
$this->phpci->log("Found $errorCount instances of " . implode(', ', $this->searches));
$this->build->storeMeta('technical_debt-warnings', $errorCount);
$this->build->storeMeta('technical_debt-data', $data);
if ($this->allowed_errors != -1 && $errorCount > $this->allowed_errors) {
$success = false;
@ -150,7 +151,6 @@ class TechnicalDebt implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$ignores = $this->ignore;
$ignores[] = 'phpci.yml';
$ignores[] = '.phpci.yml';
foreach ($iterator as $file) {
$filePath = $file->getRealPath();
@ -163,7 +163,7 @@ class TechnicalDebt implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
}
// Ignore hidden files, else .git, .sass_cache, etc. all get looped over
if (stripos($filePath, DIRECTORY_SEPARATOR . '.') !== false) {
if (stripos($filePath, '/.') !== false) {
$skipFile = true;
}
@ -174,6 +174,7 @@ class TechnicalDebt implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$files = array_filter(array_unique($files));
$errorCount = 0;
$data = array();
foreach ($files as $file) {
foreach ($this->searches as $search) {
@ -187,21 +188,21 @@ class TechnicalDebt implements PHPCI\Plugin, PHPCI\ZeroConfigPlugin
$content = trim($allLines[$lineNumber - 1]);
$errorCount++;
$this->phpci->log("Found $search on line $lineNumber of $file:\n$content");
$fileName = str_replace($this->directory, '', $file);
$this->build->reportError(
$this->phpci,
'technical_debt',
$content,
PHPCI\Model\BuildError::SEVERITY_LOW,
$fileName,
$lineNumber
$data[] = array(
'file' => $fileName,
'line' => $lineNumber,
'message' => $content
);
$this->build->reportError($this->phpci, $fileName, $lineNumber, $content);
}
}
}
return $errorCount;
return array( $errorCount, $data );
}
}

View file

@ -50,89 +50,12 @@ class Executor
public function executePlugins(&$config, $stage)
{
$success = true;
$pluginsToExecute = array();
// If we have global plugins to execute for this stage, add them to the list to be executed:
if (array_key_exists($stage, $config) && is_array($config[$stage])) {
$pluginsToExecute[] = $config[$stage];
// Ignore any stages for which we don't have plugins set:
if (!array_key_exists($stage, $config) || !is_array($config[$stage])) {
return $success;
}
$pluginsToExecute = $this->getBranchSpecificPlugins($config, $stage, $pluginsToExecute);
foreach ($pluginsToExecute as $pluginSet) {
if (!$this->doExecutePlugins($pluginSet, $stage)) {
$success = false;
}
}
return $success;
}
/**
* Check the config for any plugins specific to the branch we're currently building.
* @param $config
* @param $stage
* @param $pluginsToExecute
* @return array
*/
protected function getBranchSpecificPlugins(&$config, $stage, $pluginsToExecute)
{
/** @var \PHPCI\Model\Build $build */
$build = $this->pluginFactory->getResourceFor('PHPCI\Model\Build');
$branch = $build->getBranch();
// If we don't have any branch-specific plugins:
if (!isset($config['branch-' . $branch][$stage]) || !is_array($config['branch-' . $branch][$stage])) {
return $pluginsToExecute;
}
// If we have branch-specific plugins to execute, add them to the list to be executed:
$branchConfig = $config['branch-' . $branch];
$plugins = $branchConfig[$stage];
$runOption = 'after';
if (!empty($branchConfig['run-option'])) {
$runOption = $branchConfig['run-option'];
}
switch ($runOption) {
// Replace standard plugin set for this stage with just the branch-specific ones:
case 'replace':
$pluginsToExecute = array();
$pluginsToExecute[] = $plugins;
break;
// Run branch-specific plugins before standard plugins:
case 'before':
array_unshift($pluginsToExecute, $plugins);
break;
// Run branch-specific plugins after standard plugins:
case 'after':
array_push($pluginsToExecute, $plugins);
break;
default:
array_push($pluginsToExecute, $plugins);
break;
}
return $pluginsToExecute;
}
/**
* Execute the list of plugins found for a given testing stage.
* @param $plugins
* @param $stage
* @return bool
* @throws \Exception
*/
protected function doExecutePlugins(&$plugins, $stage)
{
$success = true;
foreach ($plugins as $plugin => $options) {
foreach ($config[$stage] as $plugin => $options) {
$this->logger->log(Lang::get('running_plugin', $plugin));
$this->setPluginStatus($stage, $plugin, Build::STATUS_RUNNING);

View file

@ -2,32 +2,34 @@
namespace PHPCI\Plugin\Util;
use Pimple\Container;
/**
* Plugin Factory - Loads Plugins and passes required dependencies.
* @package PHPCI\Plugin\Util
*/
class Factory
{
const TYPE_ARRAY = "array";
const TYPE_CALLABLE = "callable";
const TYPE_ARRAY = "array";
const TYPE_CALLABLE = "callable";
const INTERFACE_PHPCI_PLUGIN = '\PHPCI\Plugin';
private $currentPluginOptions;
/**
* @var \Pimple
* @var Container
*/
private $container;
/**
* @param \Pimple $container
* @param Container $container
*/
public function __construct(\Pimple $container = null)
public function __construct(Container $container = null)
{
if ($container) {
$this->container = $container;
} else {
$this->container = new \Pimple();
$this->container = new Container();
}
$self = $this;

View file

@ -56,7 +56,6 @@ class FilesPluginInformation implements InstalledPluginInformation
if ($this->pluginInfo === null) {
$this->loadPluginInfo();
}
return $this->pluginInfo;
}
@ -84,7 +83,7 @@ class FilesPluginInformation implements InstalledPluginInformation
$this->pluginInfo = array();
foreach ($this->files as $fileInfo) {
if ($fileInfo instanceof \SplFileInfo) {
if ($fileInfo->isFile() && $fileInfo->getExtension() == 'php') {
if ($fileInfo->isFile() && $fileInfo->getExtension()=='php') {
$this->addPluginFromFile($fileInfo);
}
}
@ -100,11 +99,11 @@ class FilesPluginInformation implements InstalledPluginInformation
$class = $this->getFullClassFromFile($fileInfo);
if (!is_null($class)) {
$newPlugin = new \stdClass();
$newPlugin->class = $class;
$newPlugin = new \stdClass();
$newPlugin->class = $class;
$newPlugin->source = "core";
$parts = explode('\\', $newPlugin->class);
$newPlugin->name = end($parts);
$parts = explode('\\', $newPlugin->class);
$newPlugin->name = end($parts);
$this->pluginInfo[] = $newPlugin;
}
@ -124,11 +123,11 @@ class FilesPluginInformation implements InstalledPluginInformation
if (isset($matches[1])) {
$className = $matches[1];
$matches = array();
preg_match('#namespace +([A-Za-z\\\\]+);#i', $contents, $matches);
$namespace = $matches[1];
return $namespace . '\\' . $className;
} else {
return null;

View file

@ -32,11 +32,9 @@ class PluginInformationCollection implements InstalledPluginInformation
public function getInstalledPlugins()
{
$arr = array();
foreach ($this->pluginInformations as $single) {
$arr = array_merge($arr, $single->getInstalledPlugins());
}
return $arr;
}
@ -49,11 +47,9 @@ class PluginInformationCollection implements InstalledPluginInformation
public function getPluginClasses()
{
$arr = array();
foreach ($this->pluginInformations as $single) {
$arr = array_merge($arr, $single->getPluginClasses());
}
return $arr;
}
}

View file

@ -13,10 +13,9 @@ use Symfony\Component\Yaml\Yaml;
class TapParser
{
const TEST_COUNTS_PATTERN = '/^\d+\.\.(\d+)/';
const TEST_LINE_PATTERN = '/^(ok|not ok)(?:\s+\d+)?(?:\s+\-)?\s*(.*?)(?:\s*#\s*(skip|todo)\s*(.*))?\s*$/i';
const TEST_YAML_START = '/^(\s*)---/';
const TEST_DIAGNOSTIC = '/^#/';
const TEST_COVERAGE = '/^Generating/';
const TEST_LINE_PATTERN = '/^(ok|not ok)(?:\s+\d+)?(?:\s+\-)?\s*(.*?)(?:\s*#\s*(skip|todo)\s*(.*))?\s*$/i';
const TEST_YAML_START = '/^(\s*)---/';
const TEST_DIAGNOSTIC = '/^#/';
/**
* @var string
@ -74,7 +73,7 @@ class TapParser
$line = $this->nextLine();
if ($line === $header) {
throw new Exception("Duplicated TAP log, please check the configuration.");
throw new Exception("Duplicated TAP log, please check the configration.");
}
while ($line !== false && ($this->testCount === false || count($this->results) < $this->testCount)) {
@ -82,7 +81,7 @@ class TapParser
$line = $this->nextLine();
}
if (false !== $this->testCount && count($this->results) !== $this->testCount) {
if (count($this->results) !== $this->testCount) {
throw new Exception(Lang::get('tap_error'));
}
@ -97,7 +96,7 @@ class TapParser
*/
protected function findTapLog()
{
// Look for the beginning of the TAP output
// Look for the beggning of the TAP output
do {
$header = $this->nextLine();
} while ($header !== false && substr($header, 0, 12) !== 'TAP version ');
@ -124,14 +123,19 @@ class TapParser
return false;
}
/**
* @param string $line
/** Parse a single line.
*
* @return boolean
* @param string $line
*/
protected function testLine($line)
protected function parseLine($line)
{
if (preg_match(self::TEST_LINE_PATTERN, $line, $matches)) {
if (preg_match(self::TEST_COUNTS_PATTERN, $line, $matches)) {
$this->testCount = intval($matches[1]);
} elseif (preg_match(self::TEST_DIAGNOSTIC, $line)) {
return;
} elseif (preg_match(self::TEST_LINE_PATTERN, $line, $matches)) {
$this->results[] = $this->processTestLine(
$matches[1],
isset($matches[2]) ? $matches[2] : '',
@ -139,61 +143,18 @@ class TapParser
isset($matches[4]) ? $matches[4] : null
);
return true;
}
return false;
}
/**
* @param string $line
*
* @return boolean
*/
protected function yamlLine($line)
{
if (preg_match(self::TEST_YAML_START, $line, $matches)) {
} elseif (preg_match(self::TEST_YAML_START, $line, $matches)) {
$diagnostic = $this->processYamlBlock($matches[1]);
$test = array_pop($this->results);
$test = array_pop($this->results);
if (isset($test['message'], $diagnostic['message'])) {
$test['message'] .= PHP_EOL . $diagnostic['message'];
unset($diagnostic['message']);
}
$this->results[] = array_replace($test, $diagnostic);
return true;
} else {
throw new Exception(sprintf('Incorrect TAP data, line %d: %s', $this->lineNumber, $line));
}
return false;
}
/** Parse a single line.
*
* @param string $line
*
* @throws Exception
*/
protected function parseLine($line)
{
if (preg_match(self::TEST_DIAGNOSTIC, $line) || preg_match(self::TEST_COVERAGE, $line) || !$line) {
return;
}
if (preg_match(self::TEST_COUNTS_PATTERN, $line, $matches)) {
$this->testCount = intval($matches[1]);
return;
}
if ($this->testLine($line)) {
return;
}
if ($this->yamlLine($line)) {
return;
}
throw new Exception(sprintf('Incorrect TAP data, line %d: %s', $this->lineNumber, $line));
}
/**
@ -235,20 +196,18 @@ class TapParser
*/
protected function processYamlBlock($indent)
{
$startLine = $this->lineNumber + 1;
$endLine = $indent . '...';
$startLine = $this->lineNumber+1;
$endLine = $indent.'...';
$yamlLines = array();
do {
$line = $this->nextLine();
if ($line === false) {
throw new Exception(Lang::get('tap_error_endless_yaml', $startLine));
} elseif ($line === $endLine) {
break;
}
$yamlLines[] = substr($line, strlen($indent));
} while (true);
return Yaml::parse(join("\n", $yamlLines));

View file

@ -20,7 +20,6 @@ class Codeception implements ParserInterface
protected $totalTests;
protected $totalTimeTaken;
protected $totalFailures;
protected $totalErrors;
/**
* @param Builder $phpci
@ -30,6 +29,7 @@ class Codeception implements ParserInterface
{
$this->phpci = $phpci;
$this->resultsXml = $resultsXml;
$this->totalTests = 0;
}
@ -47,7 +47,6 @@ class Codeception implements ParserInterface
$this->totalTests += (int) $testsuite['tests'];
$this->totalTimeTaken += (float) $testsuite['time'];
$this->totalFailures += (int) $testsuite['failures'];
$this->totalErrors += (int) $testsuite['errors'];
foreach ($testsuite->testcase as $testcase) {
$testresult = array(
@ -68,9 +67,9 @@ class Codeception implements ParserInterface
$testresult['feature'] = sprintf('%s::%s', $testresult['class'], $testresult['name']);
}
if (isset($testcase->failure) || isset($testcase->error)) {
if (isset($testcase->failure)) {
$testresult['pass'] = false;
$testresult['message'] = (string)$testcase->failure . (string)$testcase->error;
$testresult['message'] = (string) $testcase->failure;
} else {
$testresult['pass'] = true;
}
@ -109,6 +108,6 @@ class Codeception implements ParserInterface
*/
public function getTotalFailures()
{
return $this->totalFailures + $this->totalErrors;
return $this->totalFailures;
}
}

View file

@ -43,7 +43,7 @@ class Wipe implements \PHPCI\Plugin
$path = $phpci->buildPath;
$this->phpci = $phpci;
$this->build = $build;
$this->directory = isset($options['directory']) ? $this->phpci->interpolate($options['directory']) : $path;
$this->directory = isset($options['directory']) ? $options['directory'] : $path;
}
/**

View file

@ -132,9 +132,8 @@ class XMPP implements \PHPCI\Plugin
*/
public function findConfigFile()
{
if (file_exists($this->phpci->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc')) {
if (md5(file_get_contents($this->phpci->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc'))
!== md5($this->getConfigFormat())) {
if (file_exists($this->phpci->buildPath . '/.sendxmpprc')) {
if (md5(file_get_contents($this->phpci->buildPath . '/.sendxmpprc')) !== md5($this->getConfigFormat())) {
return null;
}
@ -161,7 +160,7 @@ class XMPP implements \PHPCI\Plugin
/*
* Try to build conf file
*/
$config_file = $this->phpci->buildPath . DIRECTORY_SEPARATOR . '.sendxmpprc';
$config_file = $this->phpci->buildPath . '/.sendxmpprc';
if (is_null($this->findConfigFile())) {
file_put_contents($config_file, $this->getConfigFormat());
chmod($config_file, 0600);
@ -175,7 +174,7 @@ class XMPP implements \PHPCI\Plugin
$tls = ' -t';
}
$message_file = $this->phpci->buildPath . DIRECTORY_SEPARATOR . uniqid('xmppmessage');
$message_file = $this->phpci->buildPath . '/' . uniqid('xmppmessage');
if ($this->buildMessage($message_file) === false) {
return false;
}

View file

@ -47,7 +47,7 @@ class Factory
*/
public static function createProcessControl()
{
switch (true) {
switch(true) {
case PosixProcessControl::isAvailable():
return new PosixProcessControl();

Some files were not shown because too many files have changed in this diff Show more