Merge branch 'feature-cleanup'

This commit is contained in:
Dmitry Khomutov 2017-05-23 23:22:44 +07:00
commit dd8c85a449
No known key found for this signature in database
GPG key ID: 7EB36C9576F9ECB9
9 changed files with 9 additions and 211 deletions

1
.gitignore vendored
View file

@ -1,6 +1,5 @@
/vendor
/composer.phar
/runtime
/app/loggerconfig.php
/app/config.yml
/public/assets/vendor

View file

@ -1,16 +0,0 @@
<?php
return [
/** Loggers attached to every command */
"_" => function() {
return [
new \Monolog\Handler\StreamHandler(__DIR__ . DIRECTORY_SEPARATOR . 'errors.log', \Monolog\Logger::ERROR),
];
},
/** Loggers for the RunCommand */
'RunCommand' => function() {
return [
new \Monolog\Handler\RotatingFileHandler(__DIR__ . DIRECTORY_SEPARATOR . 'everything', 3, \Monolog\Logger::DEBUG),
];
},
];

View file

@ -9,7 +9,6 @@ Getting Started
* [Run builds using a worker](workers/worker.md)
* [Run builds using cronjob](workers/cron.md)
* [Adding PHP Censor Support to Your Projects](configuring_project.md)
* [Setting up Logging](logging.md)
* Updating PHP Censor (See [README](../../README.md))
* [Configuring PHP Censor](configuring.md)

View file

@ -1,59 +0,0 @@
Setting up Logging
==================
Basics
------
The PHP Censor codebase makes use of the [PSR3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) logging standard. By default we use [Monolog](https://github.com/Seldaek/monolog) to handle the actual work implementing this standard.
How to Setup Logging (For people running a PHP Censor instance)
---------------------------------------------------------------
The only step required to activate logging is to create a file in the root directory called loggerconfig.php with content like the following:
```php
<?php
return [
/** Loggers attached to every command */
"_" => function () {
return [
new \Monolog\Handler\StreamHandler('path/to/log', \Monolog\Logger::ERROR),
];
}
];
```
This file should return an array of key value pairs. Each key tells PHP Censor which command to attach the logger to (the underscore is a special value which matches all commands). For each command an array of [Monolog](https://github.com/Seldaek/monolog) handlers should be returned. In the example above we've used one that simply writes to the file system but in practise this could be any handler written for monolog.
Once this file is created all plugins and core PHP Censor functionality should start writing to the configured handlers.
How to write to the Log (For people creating a new plugin)
----------------------------------------------------------
### Using the plugin constructor to get a logger directly
For plugin creators the simplest way to get hold of an error logger is to add a parameter to the constructor and typehint on 'Psr\Log\LoggerInterface'. The code that loads your plugin will automatically inject the logger when it sees this. For example:
```php
class ExampleLoggingPlugin implements \PHPCensor\Plugin
{
protected $log;
public function __construct(Psr\Log\LoggerInterface $log)
{
$this->log = $log;
}
public function execute()
{
$this->log->notice("You'll notice this in the log");
}
}
```
### Using convenience methods provided by the Builder
Your plugin can also call a couple of messages on the Builder object:
logSuccess()
logFailure()
log()
All calls will get piped through to the appropriate logger.

View file

@ -1,95 +0,0 @@
<?php
namespace PHPCensor\Command;
use b8\Store\Factory;
use b8\HttpClient;
use Monolog\Logger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Parser;
use PHPCensor\Model\Build;
/**
* Run console command - Poll github for latest commit id
*
* @author Jimmy Cleuren <jimmy.cleuren@gmail.com>
*/
class PollCommand extends Command
{
/**
* @var \Monolog\Logger
*/
protected $logger;
public function __construct(Logger $logger, $name = null)
{
parent::__construct($name);
$this->logger = $logger;
}
protected function configure()
{
$this
->setName('php-censor:poll-github')
->setDescription('Poll GitHub to check if we need to start a build.');
}
/**
* Pulls all pending builds from the database and runs them.
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$parser = new Parser();
$yaml = file_get_contents(APP_DIR . 'config.yml');
$this->settings = $parser->parse($yaml);
$token = $this->settings['php-censor']['github']['token'];
if (!$token) {
$this->logger->error('No GitHub token found');
return;
}
$buildStore = Factory::getStore('Build');
$this->logger->addInfo('Finding projects to poll');
$projectStore = Factory::getStore('Project');
$result = $projectStore->getWhere();
$this->logger->addInfo(sprintf('Found %d projects', count($result['items'])));
foreach ($result['items'] as $project) {
$http = new HttpClient('https://api.github.com');
$commits = $http->get('/repos/' . $project->getReference() . '/commits', ['access_token' => $token]);
$last_commit = $commits['body'][0]['sha'];
$last_committer = $commits['body'][0]['commit']['committer']['email'];
$message = $commits['body'][0]['commit']['message'];
$this->logger->info(sprintf('Last commit to GitHub for %s is %s', $project->getTitle(), $last_commit));
if (!$project->getArchived() && ($project->getLastCommit() != $last_commit && $last_commit != "")) {
$this->logger->info('Last commit is different to database, adding new build.');
$build = new Build();
$build->setProjectId($project->getId());
$build->setCommitId($last_commit);
$build->setStatus(Build::STATUS_PENDING);
$build->setBranch($project->getBranch());
$build->setCreated(new \DateTime());
$build->setCommitMessage($message);
if (!empty($last_committer)) {
$build->setCommitterEmail($last_committer);
}
$buildStore->save($build);
$project->setLastCommit($last_commit);
$projectStore->save($project);
}
}
$this->logger->addInfo('Finished processing builds.');
}
}

View file

@ -4,10 +4,11 @@ namespace PHPCensor\Console;
use b8\Config;
use b8\Store\Factory;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use PHPCensor\Command\CreateAdminCommand;
use PHPCensor\Command\CreateBuildCommand;
use PHPCensor\Command\InstallCommand;
use PHPCensor\Command\PollCommand;
use PHPCensor\Command\RebuildCommand;
use PHPCensor\Command\RebuildQueueCommand;
use PHPCensor\Command\RunCommand;
@ -41,7 +42,13 @@ class Application extends BaseApplication
{
parent::__construct($name, $version);
$loggerConfig = LoggerConfig::newFromFile(APP_DIR . 'loggerconfig.php');
$loggerConfig = new LoggerConfig([
"_" => function() {
return [
new StreamHandler(RUNTIME_DIR . 'console.log', Logger::DEBUG),
];
}
]);
$applicationConfig = Config::getInstance();
$databaseSettings = $applicationConfig->get('b8.database', []);
@ -105,7 +112,6 @@ class Application extends BaseApplication
$this->add(new RunCommand($loggerConfig->getFor('RunCommand')));
$this->add(new RebuildCommand($loggerConfig->getFor('RunCommand')));
$this->add(new InstallCommand());
$this->add(new PollCommand($loggerConfig->getFor('PollCommand')));
$this->add(new CreateAdminCommand($userStore));
$this->add(new CreateBuildCommand($projectStore, new BuildService($buildStore)));
$this->add(new WorkerCommand($loggerConfig->getFor('WorkerCommand')));

View file

@ -13,23 +13,6 @@ class LoggerConfig
private $config;
private $cache = [];
/**
* The filepath is expected to return an array which will be
* passed to the normal constructor.
*
* @param string $filePath
* @return LoggerConfig
*/
public static function newFromFile($filePath)
{
if (file_exists($filePath)) {
$configArray = require($filePath);
} else {
$configArray = [];
}
return new self($configArray);
}
/**
* Each key of the array is the name of a logger. The value of
* each key should be an array or a function that returns an

View file

@ -173,10 +173,6 @@ class BuildService
'build_id' => $build->getId(),
];
if ($config->get('using_custom_file')) {
$jobData['config'] = $config->getArray();
}
$pheanstalk = new Pheanstalk($settings['host']);
$pheanstalk->useTube($settings['name']);
$pheanstalk->put(

View file

@ -2,8 +2,6 @@
namespace PHPCensor\Worker;
use b8\Config;
use b8\Database;
use b8\Store\Factory;
use Monolog\Logger;
use Pheanstalk\Job;
@ -95,14 +93,6 @@ class BuildWorker
$this->logger->addInfo('Received build #'.$jobData['build_id'].' from Beanstalkd');
// If the job comes with config data, reset our config and database connections
// and then make sure we kill the worker afterwards:
if (!empty($jobData['config'])) {
$this->logger->addDebug('Using job-specific config.');
$currentConfig = Config::getInstance()->getArray();
Database::reset();
}
try {
$build = BuildFactory::getBuildById($jobData['build_id']);
} catch (\Exception $ex) {
@ -156,11 +146,6 @@ class BuildWorker
// destructor implicitly call flush
unset($buildDbLog);
// Reset the config back to how it was prior to running this job:
if (!empty($currentConfig)) {
Database::reset();
}
// Delete the job when we're done:
if (!empty($job)) {
$this->pheanstalk->delete($job);