Skip to content

Commit

Permalink
[console] Implement statistics feature (#342)
Browse files Browse the repository at this point in the history
* [console] Implement statistics feature

* [statistics] Change statistics config location

* [statistics] Remove getStatisticsDirectory

* [statistics] Use fgetcsv function

* [statistics] Remove statistics after success response

* [statistics] Add validation to custom commands.

* [statistics] Remove var_dump from saveStatistics class

* [statistics] Add validation is finder count is 0

* [config] Add statistics to console config

* [configManager] Change getConfigGlobalAsArray function

* [settings:set] Add missing message to success execution

* [statistics] Add more condition to send info

* [statistics] Change count-attempted to times-attempted

* [statistics] Delete the error message for failed attempted

* [statistics] Add validation if there is not config file

* Add url to config.yml to send data
  • Loading branch information
hjuarez20 authored and enzolutions committed May 28, 2019
1 parent 4914556 commit c4d578d
Show file tree
Hide file tree
Showing 12 changed files with 559 additions and 35 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
"symfony/yaml": "~2.8|~3.0",
"twig/twig": "^1.23.1",
"webflo/drupal-finder": "^1.0",
"webmozart/path-util": "^2.3"
"webmozart/path-util": "^2.3",
"guzzlehttp/guzzle": "~6.1"
},
"minimum-stability": "dev",
"prefer-stable": true,
Expand Down
4 changes: 4 additions & 0 deletions config/config.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
application:
statistics:
enabled: false
last-attempted: ~
times-attempted: 0
language: 'en'
autowire:
commands:
Expand Down
1 change: 1 addition & 0 deletions services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ services:
# DrupalConsoleCore Generators
console.init_generator:
class: Drupal\Console\Core\Generator\InitGenerator
arguments: ['@console.configuration_manager']
tags:
- { name: drupal.generator }
console.site_alias_generator:
Expand Down
47 changes: 35 additions & 12 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Drupal\Console\Core;

use Drupal\Console\Core\EventSubscriber\SendStatisticsListener;
use Drupal\Console\Core\EventSubscriber\RemoveMessagesListener;
use Drupal\Console\Core\EventSubscriber\SaveStatisticsListener;
use Drupal\Console\Core\EventSubscriber\ShowGenerateCountCodeLinesListener;
use Drupal\Console\Core\Utils\TranslatorManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
Expand Down Expand Up @@ -305,6 +307,21 @@ private function registerEvents()
)
);

$dispatcher->addSubscriber(
new SaveStatisticsListener(
$this->container->get('console.count_code_lines'),
$this->container->get('console.configuration_manager'),
$this->container->get('console.translator_manager')
)
);

$dispatcher->addSubscriber(
new SendStatisticsListener(
$this->container->get('console.configuration_manager'),
$this->container->get('console.translator_manager')
)
);

$dispatcher->addSubscriber(
new RemoveMessagesListener(
$this->container->get('console.message_manager')
Expand Down Expand Up @@ -714,7 +731,9 @@ public function getData($filterNamespaces = null, $excludeNamespaces = [], $excl
$namespaces = array_diff($namespaces, $excludeNamespaces);

// filter namespaces if available
if($filterNamespaces) $namespaces = array_intersect($namespaces, $filterNamespaces);
if ($filterNamespaces) {
$namespaces = array_intersect($namespaces, $filterNamespaces);
}

foreach ($namespaces as $namespace) {
$commands = $this->all($namespace);
Expand All @@ -726,8 +745,8 @@ public function getData($filterNamespaces = null, $excludeNamespaces = [], $excl

foreach ($commands as $command) {
// Exclude command if is a chain command and was requested to exclude chain commands
if($excludeChainCommands && $command instanceof ChainCustomCommand) {
continue;
if ($excludeChainCommands && $command instanceof ChainCustomCommand) {
continue;
}

if (method_exists($command, 'getModule')) {
Expand All @@ -745,9 +764,11 @@ public function getData($filterNamespaces = null, $excludeNamespaces = [], $excl
}

// Remove namepsaces without commands
$namespaces = array_filter($namespaces, function($namespace) use( $data) {
return count($data['commands'][$namespace]) > 0;
});
$namespaces = array_filter(
$namespaces, function ($namespace) use ($data) {
return count($data['commands'][$namespace]) > 0;
}
);

$input = $this->getDefinition();
$options = [];
Expand Down Expand Up @@ -894,7 +915,8 @@ public function getContainer()
/**
* Add Drupal system messages.
*/
protected function addDrupalMessages($messageManager) {
protected function addDrupalMessages($messageManager)
{
if (function_exists('drupal_get_messages')) {
$drupalMessages = drupal_get_messages();
foreach ($drupalMessages as $type => $messages) {
Expand All @@ -915,13 +937,14 @@ protected function addDrupalMessages($messageManager) {
* @return string
* Name of the method
*/
protected function getMessageMethod($type) {
protected function getMessageMethod($type)
{
$methodName = 'info';
switch ($type) {
case 'error':
case 'warning':
$methodName = $type;
break;
case 'error':
case 'warning':
$methodName = $type;
break;
}

return $methodName;
Expand Down
40 changes: 32 additions & 8 deletions src/Command/InitCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ class InitCommand extends Command
'sites' => false,
'learning' => false,
'generate_inline' => false,
'generate_chain' => false
'generate_chain' => false,
'statistics' => true
];

private $directories = [
Expand Down Expand Up @@ -192,6 +193,27 @@ protected function interact(InputInterface $input, OutputInterface $output)
);
$input->setOption('autocomplete', $autocomplete);
}

$this->getIo()->commentBlock(
sprintf(
$this->trans('commands.init.messages.statistics'),
sprintf(
'%sconfig.yml',
$this->configurationManager->getConsoleDirectory()
)
)
);

$this->configParameters['statistics'] = $this->getIo()->confirm(
$this->trans('commands.init.questions.statistics'),
true
);

if ($this->configParameters['statistics']) {
$this->getIo()->commentBlock(
$this->trans('commands.init.messages.statistics-disable')
);
}
}

/**
Expand Down Expand Up @@ -269,13 +291,15 @@ protected function execute(InputInterface $input, OutputInterface $output)
$process->stop();
}

$this->generator->generate([
'user_home' => $this->configurationManager->getConsoleDirectory(),
'executable_name' => $executableName,
'override' => $override,
'destination' => $destination,
'config_parameters' => $this->configParameters,
]);
$this->generator->generate(
[
'user_home' => $this->configurationManager->getConsoleDirectory(),
'executable_name' => $executableName,
'override' => $override,
'destination' => $destination,
'config_parameters' => $this->configParameters,
]
);

$this->getIo()->writeln($this->trans('application.messages.autocomplete'));

Expand Down
15 changes: 15 additions & 0 deletions src/Command/Settings/SetCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ protected function execute(InputInterface $input, OutputInterface $output)
$settingName = $input->getArgument('name');
$settingValue = $input->getArgument('value');

// Reset the default values ​​of the statistics.
if ($settingName == 'statistics.enabled') {
$this->configurationManager->updateConfigGlobalParameter(
'statistics.last-attempted',
null
);
$this->configurationManager->updateConfigGlobalParameter(
'statistics.times-attempted',
0
);
}

$userConfigFile = sprintf(
'%s/.console/config.yml',
$this->configurationManager->getHomeDirectory()
Expand Down Expand Up @@ -111,6 +123,8 @@ protected function execute(InputInterface $input, OutputInterface $output)
}

$parents = array_merge(['application'], explode(".", $settingName));
// Change the value type if it is boolean.
$settingValue = json_decode($settingValue) === null ? $settingValue : json_decode($settingValue);

$this->nestedArray->setValue(
$userConfigFileParsed,
Expand Down Expand Up @@ -163,6 +177,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
return 1;
}

$settingValue = is_bool($settingValue) ? $settingValue ? 'true' : 'false' : $settingValue;
$this->getIo()->success(
sprintf(
$this->trans('commands.settings.set.messages.success'),
Expand Down
119 changes: 119 additions & 0 deletions src/EventSubscriber/SaveStatisticsListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

/**
* @file
* Contains \Drupal\Console\Core\EventSubscriber\SaveStatisticsListener.
*/

namespace Drupal\Console\Core\EventSubscriber;

use Drupal\Console\Core\Command\Chain\ChainCustomCommand;
use Drupal\Console\Core\Utils\ConfigurationManager;
use Drupal\Console\Core\Utils\CountCodeLines;
use Drupal\Console\Core\Utils\TranslatorManagerInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Filesystem\Filesystem;

/**
* Class SaveStatisticsListener
*
* @package Drupal\Console\Core\EventSubscriber
*/
class SaveStatisticsListener implements EventSubscriberInterface
{

/**
* @var ShowGenerateChainListener
*/
protected $countCodeLines;

/**
* @var ConfigurationManager
*/
protected $configurationManager;

/**
* @var TranslatorManagerInterface
*/
protected $translator;

/**
* FileSystem $fs
*/
protected $fs;

/**
* SaveStatisticsListener constructor.
*
* @param CountCodeLines $countCodeLines
* @param ConfigurationManager $configurationManager
* @param TranslatorManagerInterface $translator
*/
public function __construct(
CountCodeLines $countCodeLines,
ConfigurationManager $configurationManager,
TranslatorManagerInterface $translator
) {
$this->countCodeLines = $countCodeLines;
$this->configurationManager = $configurationManager;
$this->translator = $translator;

$this->fs = new Filesystem();
}

/**
* @param ConsoleTerminateEvent $event
*/
public function saveStatistics(ConsoleTerminateEvent $event)
{
if ($event->getExitCode() != 0) {
return;
}

$configGlobalAsArray = $this->configurationManager->getConfigGlobalAsArray();

//Validate if the config is enable.
if (is_null($configGlobalAsArray) || !$configGlobalAsArray['application']['statistics']['enabled']) {
return;
}

//Check that the namespace starts with 'Drupal\Console'.
$class = new \ReflectionClass($event->getCommand());
if (strpos($class->getNamespaceName(), "Drupal\Console") !== 0) {
return;
}

//Validate if the command is not a custom chain command.
if ($event->getCommand() instanceof ChainCustomCommand) {
return;
}

$path = $path = sprintf(
'%s/.console/stats/',
$this->configurationManager->getHomeDirectory()
);

$information = $event->getCommand()->getName() . ',' . $this->translator->getLanguage();

$countCodeLines = $this->countCodeLines->getCountCodeLines();
if ($countCodeLines > 0) {
$information = $information . ',' . $countCodeLines;
}


$this->fs->appendToFile(
$path . date('Y-m-d') . '.csv',
$information . PHP_EOL
);
}

/**
* @{@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [ConsoleEvents::TERMINATE => 'saveStatistics'];
}
}
Loading

0 comments on commit c4d578d

Please sign in to comment.