Commit 37863755 authored by Sean Madsen's avatar Sean Madsen

format code to pass civilint

parent af957011
......@@ -2,6 +2,6 @@
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class AppCache extends HttpCache
{
class AppCache extends HttpCache {
}
......@@ -3,10 +3,9 @@
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
class AppKernel extends Kernel {
public function registerBundles() {
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
......@@ -18,7 +17,7 @@ class AppKernel extends Kernel
new AppBundle\AppBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
if (in_array($this->getEnvironment(), ['dev', 'test'], TRUE)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
......@@ -28,28 +27,23 @@ class AppKernel extends Kernel
return $bundles;
}
public function getRootDir()
{
public function getRootDir() {
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
public function getCacheDir() {
return dirname(__DIR__) . '/var/cache/' . $this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
public function getLogDir() {
return dirname(__DIR__) . '/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
public function registerContainerConfiguration(LoaderInterface $loader) {
$loader->load($this->getRootDir() . '/config/config_' . $this->getEnvironment() . '.yml');
}
protected function buildContainer()
{
protected function buildContainer() {
$container = parent::buildContainer();
if ($container->hasParameter('mkdocs_path')) {
$_ENV['PATH'] = $container->getParameter('mkdocs_path')
......@@ -59,12 +53,10 @@ class AppKernel extends Kernel
if (!$container->hasParameter('publisher_repos_dir')) {
// This isn't really a good place to put it because it gets deleted
// whenever you clear the cache.
$container->setParameter('publisher_repos_dir',
$container->getParameter('kernel.cache_dir') . '/repos'
$container->setParameter('publisher_repos_dir', $container->getParameter('kernel.cache_dir') . '/repos'
);
}
return $container;
}
}
......@@ -6,7 +6,7 @@ use Composer\Autoload\ClassLoader;
/**
* @var ClassLoader $loader
*/
$loader = require __DIR__.'/../vendor/autoload.php';
$loader = require __DIR__ . '/../vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
......
......@@ -4,6 +4,5 @@ namespace AppBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
class AppBundle extends Bundle {
}
......@@ -9,17 +9,13 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DocsListCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('docs:list')
->setDescription('List available books');
class DocsListCommand extends ContainerAwareCommand {
protected function configure() {
$this->setName('docs:list')->setDescription('List available books');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
protected function execute(InputInterface $input, OutputInterface $output) {
/** @var \AppBundle\BookLoader $books */
$books = $this->getContainer()->get('book.loader');
$table = new Table($output);
......
......@@ -8,19 +8,19 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DocsPublishCommand extends ContainerAwareCommand
{
protected function configure()
{
class DocsPublishCommand extends ContainerAwareCommand {
protected function configure() {
$this
->setName('docs:publish')
->setDescription('...')
->addArgument('paths', InputArgument::IS_ARRAY,
->addArgument(
'paths',
InputArgument::IS_ARRAY,
'One or more book expressions ("book/lang/branch"). (Default: all)');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
protected function execute(InputInterface $input, OutputInterface $output) {
/** @var \AppBundle\BookLoader $books */
$books = $this->getContainer()->get('book.loader');
......@@ -33,13 +33,23 @@ class DocsPublishCommand extends ContainerAwareCommand
$output->writeln("<error>No books found</error>");
}
$rowKeys = $input->getArgument('paths') ? $input->getArgument('paths') : array_keys($rows);
if ($input->getArgument('paths')) {
$rowKeys = $input->getArgument('paths');
}
else {
$rowKeys = array_keys($rows);
}
foreach ($rowKeys as $rowKey) {
$row = $rows[$rowKey];
$output->writeln("");
$output->writeln(sprintf("Publish [%s/%s/%s] (from %s)",
$row['book'], $row['lang'], $row['branch'], $row['repo']));
$output->writeln(sprintf(
"Publish [%s/%s/%s] (from %s)",
$row['book'],
$row['lang'],
$row['branch'],
$row['repo'])
);
$publisher->publish($row['book'], $row['lang'], $row['branch']);
......@@ -47,7 +57,6 @@ class DocsPublishCommand extends ContainerAwareCommand
$output->writeln($message['label'] . ': ' . $message['content']);
}
$publisher->clearMessages();
}
}
......
......@@ -16,41 +16,50 @@ use Symfony\Component\Console\Output\OutputInterface;
* This is a dumb wrapper around `mkdocs serve`. It basically just cd's into the
* appropriate folder and then passes-through the args.
*/
class DocsServeCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('docs:serve')
->setDescription('Run the builtin docs development server')
->addOption('dev-addr', 'a', InputOption::VALUE_OPTIONAL,
'IP address and port to serve documentation')
->addOption('strict', 's', InputOption::VALUE_NONE,
'Enable strict mode. This will cause MkDocs to abort the build on any warnings.')
->addOption('theme', 't', InputOption::VALUE_OPTIONAL,
'The theme to use when building your documentation [cosmo|cyborg|readthedocs|yeti|journal|bootstrap|readable|united|simplex|flatly|spacelab|amelia|cerulean|slate|mkdocs')
->addOption('livereload', null, InputOption::VALUE_NONE,
'Enable the live reloading in the development server.')
->addOption('no-livereload', null, InputOption::VALUE_NONE,
'Enable the live reloading in the development server.')
->addOption('quiet', 'q', InputOption::VALUE_NONE,
'Silence warnings')// ->addOption('verbose', 'v', InputOption::VALUE_NONE, 'Enable verbose output')
->addArgument('[book/lang/[branch]]', InputArgument::REQUIRED,
'A book expression (e.g. "dev/en/master" or "user/fr/4.6"). The [book] and [lang] are mandatory. If [branch] is specified, it will be checked out.')
;
class DocsServeCommand extends ContainerAwareCommand {
protected function configure() {
$this->setName('docs:serve');
$this->setDescription('Run the builtin docs development server');
$this->addOption('dev-addr', 'a', InputOption::VALUE_OPTIONAL,
'IP address and port to serve documentation');
$this->addOption('strict', 's', InputOption::VALUE_NONE,
'Enable strict mode. This will cause MkDocs to abort the build on any'
. 'warnings.');
$this->addOption('theme', 't', InputOption::VALUE_OPTIONAL,
'The theme to use when building your documentation (e.g. readthedocs)');
$this->addOption('livereload', NULL, InputOption::VALUE_NONE,
'Enable the live reloading in the development server.');
$this->addOption('no-livereload', NULL, InputOption::VALUE_NONE,
'Disable the live reloading in the development server.');
$this->addOption('quiet', 'q', InputOption::VALUE_NONE,
'Silence warnings');
$this->addArgument('[book/lang/[branch]]', InputArgument::REQUIRED,
'A book expression (e.g. "dev/en/master" or "user/fr/4.6"). '
. 'The [book] and [lang] are mandatory. '
. 'If [branch] is specified, it will be checked out.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
protected function execute(InputInterface $input, OutputInterface $output) {
if (preg_match(';^(\w+)/(\w+)?$;', $input->getArgument('[book/lang/[branch]]'), $matches)) {
$book = $matches[1];
$lang = $matches[2];
$branch = NULL;
} elseif (preg_match(';^(\w+)/(\w+)/(\w+)$;', $input->getArgument('[book/lang/[branch]]'), $matches)) {
}
elseif (preg_match(';^(\w+)/(\w+)/(\w+)$;', $input->getArgument('[book/lang/[branch]]'), $matches)) {
$book = $matches[1];
$lang = $matches[2];
$branch = $matches[3];
} else {
}
else {
$output->writeln("<error>Malformed [book/lang/branch]</error>");
return 1;
}
......@@ -59,7 +68,8 @@ class DocsServeCommand extends ContainerAwareCommand
if (file_exists($repoDir)) {
$output->writeln("<info>Found git repo for $book/$lang in \"$repoDir\"</info>");
} else {
}
else {
$output->writeln("<error>Failed to find git repo for $book/$lang in \"$repoDir\".</error>");
$output->writeln("<error>Perhaps you should run \"docs:publish\" first?</error>");
return 1;
......@@ -72,7 +82,7 @@ class DocsServeCommand extends ContainerAwareCommand
}
}
foreach (array('strict', 'livereload', 'no-livereload', 'quiet') as $option) {
if ($input->getOption($option) ) {
if ($input->getOption($option)) {
$command .= " --{$option}";
}
}
......
......@@ -10,17 +10,19 @@ use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Parser;
//@TODO Make the errors that will occur if the slugs don't pass the regexp more obvious to the user
/**
* @TODO Make the errors that will occur if the slugs don't pass the regexp
* more obvious to the user
*/
class PublishController extends Controller {
class PublishController extends Controller
{
/**
* @Route("/admin/publish")
*/
public function PublishInstructionsAction()
{
public function PublishInstructionsAction() {
return $this->render('AppBundle:Publish:publish.html.twig');
}
/**
* @Route("/admin/publish/{book}/{lang}/{branch}", requirements={
* "lang":"[[:alpha:]]{2}",
......@@ -28,22 +30,17 @@ class PublishController extends Controller
* "branch":"[[:alnum:]\-\.]+",
* })
*/
public function PublishAction(Request $request, $lang, $book, $branch)
{
public function PublishAction(Request $request, $lang, $book, $branch) {
$publisher = $this->get('publisher');
$publisher->publish($book, $lang, $branch);
$content['messages'] = $publisher->getMessages();
return $this->render('AppBundle:Publish:publish.html.twig', $content);
}
/**
* @Route("/admin/listen")
*/
public function ListenAction(Request $request)
{
public function ListenAction(Request $request) {
$body = $request->getContent();
$event = $request->headers->get('X-GitHub-Event');
$payload = json_decode($body);
......@@ -52,8 +49,9 @@ class PublishController extends Controller
$processor = $this->get('github.hook.processor');
$processor->process($event, $payload);
if(!$processor->published){
return new Response('Something went wrong during publishing.', 200); // @TODO Add more appropriate error code
if (!$processor->published) {
return new Response('Something went wrong during publishing.', 200);
// @TODO Add more appropriate error code
}
$messages = $processor->getMessages();
$subject = $processor->getSubject();
......@@ -65,20 +63,17 @@ class PublishController extends Controller
->setTo($recipients)
->setBody(
$this->renderView(
'Emails/notify.html.twig', array(
'Emails/notify.html.twig',
array(
'branch' => $processor->publisher->branch,
'book' => $processor->publisher->book,
'lang' => $processor->publisher->lang,
'messages' => $processor->publisher->getMessages()
'messages' => $processor->publisher->getMessages(),
)
),
'text/html'
), 'text/html'
);
$this->get('mailer')->send($mail);
return new Response($subject, 200);
}
}
......@@ -8,22 +8,23 @@ use Symfony\Component\Yaml\Parser;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Intl\ResourceBundle\RegionBundle;
class ReadController extends Controller
{
class ReadController extends Controller {
/**
* @Route("/{path}")
*/
public function RedirectAction($path)
{
//If path is the recognised name of a book, then redirect to the stable path of the book, else redirect to the home page.
public function RedirectAction($path) {
//If path is the recognised name of a book, then redirect to the
//stable path of the book, else redirect to the home page.
$k = $this->get('kernel');
$fs = $this->get('filesystem');
$bookConfigFile = $k->getRootDir()."/config/books/{$path}.yml";
$bookConfigFile = $k->getRootDir() . "/config/books/{$path}.yml";
if (!$fs->exists($bookConfigFile)) {
return $this->redirect("/");
}
return $this->redirect("{$path}/en/stable");
}
// $k = $this->get('kernel');
// if(substr( $path, -1)=='/'){
// return new Response(file_get_contents($k->getCacheDir()."/{$path}index.html"));
......@@ -35,11 +36,14 @@ class ReadController extends Controller
/**
* @Route("/")
*/
public function HomeAction()
{
public function HomeAction() {
$k = $this->get('kernel');
// This seems like a kind of hacky way to find the locales, but not sure what a better way would be.
$locales = json_decode(file_get_contents($k->getRootDir().'/../vendor/symfony/symfony/src/Symfony/Component/Intl/Resources/data/locales/en.json'), true);
// This seems like a kind of hacky way to find the locales, but not
// sure what a better way would be.
$locales = json_decode(file_get_contents(
$k->getRootDir()
. '/../vendor/symfony/symfony/src/Symfony/Component/Intl/Resources/data/locales/en.json'
), TRUE);
$finder = new Finder();
$yaml = new Parser();
......@@ -59,4 +63,5 @@ class ReadController extends Controller
// return new Response(file_get_contents($k->getCacheDir()."/$path"));
// }
// //return $this->render('AppBundle:Read:read.html.twig');
}
......@@ -4,10 +4,9 @@ namespace AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class NotifyControllerTest extends WebTestCase
{
public function testNotify()
{
class NotifyControllerTest extends WebTestCase {
public function testNotify() {
$client = static::createClient();
$crawler = $client->request('GET', '/Notify');
......
<?php
namespace AppBundle\Utils;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Parser;
class BookLoader
{
class BookLoader {
/**
* @var string
......@@ -21,8 +21,7 @@ class BookLoader
* Books constructor.
* @param string $configDir
*/
public function __construct($configDir)
{
public function __construct($configDir) {
$this->configDir = $configDir;
}
......@@ -36,7 +35,7 @@ class BookLoader
private function compareBooksBySortOrder($bookA, $bookB) {
$aWeight = isset($bookA['weight']) ? $bookA['weight'] : 0;
$bWeight = isset($bookB['weight']) ? $bookB['weight'] : 0;
if ( $aWeight == $bWeight ) {
if ($aWeight == $bWeight) {
return strnatcmp($bookA['name'], $bookB['name']);
}
return $aWeight - $bWeight;
......@@ -46,7 +45,7 @@ class BookLoader
* Modifies the internal book cache by sorting the array of books correctly
*/
private function cacheSort() {
if( isset($this->cache) ) {
if (isset($this->cache)) {
uasort($this->cache, [$this, 'compareBooksBySortOrder']);
}
}
......@@ -56,7 +55,7 @@ class BookLoader
* array structure that provide additional information about the book, such
* as the number of languages, etc.
*
* @param array book
* @param array &$book an array of properties which represent a book
*/
private function addStatsToBook(&$book) {
$this->addToBookDistinctVersions($book);
......@@ -71,7 +70,7 @@ class BookLoader
* versions. If 'stable' and 'latest' both point to 'master', then it will
* list only 'stable' in the distinct versions.
*
* @param array book
* @param array &$book an array of properties which represent a book
*
*/
private function addToBookDistinctVersions(&$book) {
......@@ -94,12 +93,11 @@ class BookLoader
* whether the language has multiple versions that are different from one
* another
*
* @param array book
* @param array &$book an array of properties which represent a book
*/
private function addToBookIsMultiVersion(&$book) {
foreach ($book['langs'] as &$lang) {
$lang['is_multi_version'] =
count($lang['distinct_versions']) > 1 ? 1 : 0;
$lang['is_multi_version'] = count($lang['distinct_versions']) > 1 ? 1 : 0;
}
}
......@@ -107,7 +105,7 @@ class BookLoader
* Adds 'is_multi_lang' element to a book to say whether the book has
* multiple languages.
*
* @param array book
* @param array &$book an array of properties which represent a book
*/
private function addToBookIsMultiLang(&$book) {
$book['is_multi_lang'] = count($book['langs']) > 1 ? 1 : 0;
......@@ -117,11 +115,11 @@ class BookLoader
* Adds 'stable_langs' element to a book -- an array of all the languages
* which have a stable version defined.
*
* @param array book
* @param array &$book an array of properties which represent a book
*/
private function addToBookStableLangs(&$book) {
foreach ($book['langs'] as $lang => $language) {
if(isset($language['stable'])) {
if (isset($language['stable'])) {
$book['stable_langs'][$lang] = $language;
}
}
......@@ -131,10 +129,10 @@ class BookLoader
* Adds 'is_multi_stable_lang' element to a book to say whether the book has
* multiple languages which have stable versions defined.
*
* @param array book
* @param array &$book an array of properties which represent a book
*/
private function addToBookIsMultiStableLang(&$book) {
if(!isset($book['stable_langs'])) {
if (!isset($book['stable_langs'])) {
$this->addToBookStableLangs($book);
}
$book['is_multi_stable_lang'] = count($book['stable_langs']) > 1 ? 1 : 0;
......@@ -147,9 +145,8 @@ class BookLoader
*
* @return array all books
*/
public function find()
{
if ($this->cache === null) {
public function find() {
if ($this->cache === NULL) {
$finder = new Finder();
$yaml = new Parser();
$books = array();
......@@ -211,7 +208,7 @@ class BookLoader
continue;
}
elseif (is_array($langSpec[$key])) {
$branches = array_merge($branches,$langSpec[$key]);
$branches = array_merge($branches, $langSpec[$key]);
}
else {
$branches[] = $langSpec[$key];
......
......@@ -2,33 +2,34 @@
namespace AppBundle\Utils;
class GitHubHookProcessor{
class GitHubHookProcessor {
protected $messages = array();
protected $recipients = array();
public $published = FALSE;
public $published = false;
public function __construct($publisher, $bookLoader){
public function __construct($publisher, $bookLoader) {
$this->publisher = $publisher;
$this->books = $bookLoader->find();
}
function process($event, $payload){
public function process($event, $payload) {
//The getDetailsFrom functions work out what branch and repo we are talking about, and the also work out what emails we should send.
//The getDetailsFrom functions work out what branch and repo we are talking
//about, and the also work out what emails we should send.
switch ($event) {
case 'pull_request':
$this->getDetailsFromPullRequest($payload);
break;
case 'push':
$this->getDetailsFromPush($payload);
break;
}
foreach ($this->books as $bookName => $bookConfig) {
foreach ($bookConfig['langs'] as $bookLang => $bookLangConfig) {
if($bookLangConfig['repo'] == $this->repo){
if ($bookLangConfig['repo'] == $this->repo) {
$this->book = $bookName;
$this->lang = $bookLang;
$config = $bookLangConfig;
......@@ -37,23 +38,27 @@ class GitHubHookProcessor{
}
}
// If the book (in a specific language) wants additional people to be notified on each publication, they can be added in the book yml definition and will get added here
if(isset($config['notify'])){
foreach($config['notify'] as $recipient){
$this->recipients[]=$recipient;
// If the book (in a specific language) wants additional people to be
// notified on each publication, they can be added in the book yml
// definition and will get added here
if (isset($config['notify'])) {
foreach ($config['notify'] as $recipient) {
$this->recipients[] = $recipient;
}
}
$this->published = $this->publisher->publish($this->book, $this->lang, $this->branch);
$this->published = $this->publisher->publish(
$this->book, $this->lang, $this->branch);
$this->messages = $this->publisher->getMessages();
$this->subject = "Published '{$this->branch}' branch of '{$this->book}' in '{$this->lang}'";
$this->subject = "Published '{$this->branch}' branch of '{$this->book}'"
. "in '{$this->lang}'";
$this->recipients = array_unique($this->recipients);
}
function getDetailsFromPullRequest($payload){
public function getDetailsFromPullRequest($payload) {
//Only continue if this pull request is closed and merged
if($payload->action != 'closed' OR !$payload->pull_request->merged){
if ($payload->action != 'closed' OR !$payload->pull_request->merged) {
return;
}
......@@ -64,42 +69,40 @@ class GitHubHookProcessor{
//Get emails of people that should be notified
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $payload->pull_request->commits_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'User-Agent: civicrm-docs')); // Assuming you're requesting JSON
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'User-Agent: civicrm-docs',
)
); // Assuming you're requesting JSON
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->commits = json_decode(curl_exec($ch));
foreach($this->commits as $commit){
$this->recipients[]=$commit->commit->author->email;
$this->recipients[]=$commit->commit->committer->email;
foreach ($this->commits as $commit) {
$this->recipients[] = $commit->commit->author->email;
$this->recipients[] = $commit->commit->committer->email;
}
}
function getDetailsFromPush($payload){
public function getDetailsFromPush($payload) {
$this->branch = preg_replace("/.*\/(.*)/", "$1", $payload->ref);
$this->repo = $payload->repository->html_url;
foreach($payload->commits as $commit){
$this->recipients[]=$commit->author->email;
$this->recipients[]=$commit->committer->email;
foreach ($payload->commits as $commit) {
$this->recipients[] = $commit->author->email;
$this->recipients[] = $commit->committer->email;
}
}
public function getMessages()
{
public function getMessages() {
return $this->messages;
}
public function getRecipients()
{
public function getRecipients() {
return $this->recipients;
}
public function getSubject()
{
public function getSubject() {
return $this->subject;
}
}
......@@ -8,13 +8,12 @@ use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class Publisher{
class Publisher {
public $bookConfigFile;
public $messages;
public function __construct(RequestStack $requestStack, $logger, $fs, $configDir, $reposRoot, $publishRoot){
public function __construct(RequestStack $requestStack, $logger, $fs, $configDir, $reposRoot, $publishRoot) {
$this->configDir = $configDir;
$this->reposRoot = $reposRoot;
$this->publishRoot = $publishRoot;
......@@ -23,13 +22,12 @@ class Publisher{
$this->fs = $fs;
}