Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a "render" command #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea
composer.lock
vendor
tests/_output/*
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
"symfony/yaml": "~2.5|~3.0",
"symfony/console": "~2.8|~3.0",
"symfony/finder": "~2.8|~3.0",
"padraic/phar-updater": "~1.0"
"padraic/phar-updater": "~1.0",
"ext-json": "*"
},
"require-dev": {
"mockery/mockery": "~0.9.2",
Expand Down
16 changes: 16 additions & 0 deletions src/Command/ApplicationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public function create()
$app = new Application(Message::NAME, Version::read());
$app->setDefaultCommand(Message::CMD_ANALYZE);
$app->add($this->createAnalyzeCommand());
$app->add($this->createRenderCommand());

if (\Phar::running()) {
$app->add($this->createUpdateCommand());
Expand All @@ -76,6 +77,21 @@ protected function createAnalyzeCommand()
return $command;
}

/**
* @return Render
*/
protected function createRenderCommand()
{
$command = new Render(Message::CMD_RENDER);

$command->setHelp(Message::CMD_RENDER_HELP);
$command->setDescription(Message::CMD_RENDER_DESCR);
$command->setConfigParser(new Parser);
$command->setStrategyLoader(new Loader);

return $command;
}

/**
* @return Update
*/
Expand Down
16 changes: 16 additions & 0 deletions src/Command/MessageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ interface MessageInterface

const CMD_ANALYZE_OPT_TARGET = 'Filepath for writing created dependency graph.';

const CMD_RENDER = 'render';

const CMD_RENDER_HELP = "Read the result of an analysis from a JSON file and render it in the desired format.";

const CMD_RENDER_DESCR = 'Render a previously created JSON file';

const CMD_RENDER_ARG_SOURCE = 'The JSON file to load.';

const CMD_RENDER_ARG_TARGET = 'Filepath for writing created dependency graph.';

const CMD_RENDER_OPT_CONFIG = 'Path to the yaml configuration file.';

const CMD_RENDER_OPT_FORMATTER = 'Formatter as FQCN for creating dependency graph.';

const CMD_UPDATE = 'update';

const CMD_UPDATE_DESCR = 'Update to latest version';
Expand All @@ -59,6 +73,8 @@ interface MessageInterface

const READ_CONFIG_FROM = 'Configuration read from %s';

const RENDER_FROM_TO = 'Render data from %s to %s';

const WRITE_GRAPH_TO = 'Write dependency graph to %s';

const PROGRESS_DISPLAY = '%current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% Memory: %memory:6s%';
Expand Down
256 changes: 256 additions & 0 deletions src/Command/Render.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 Daniel Kinzler
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

namespace PhpDA\Command;

use Exception;
use PhpDA\Command\MessageInterface as Message;
use PhpDA\Command\Strategy\RenderFactory;
use PhpDA\Command\Strategy\StrategyInterface;
use PhpDA\Plugin\LoaderInterface;
use PhpDA\Writer\Strategy\Svg;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Parser;

/**
* @SuppressWarnings("PMD.CouplingBetweenObjects")
*/
class Render extends Command
{
const EXIT_SUCCESS = 0, EXIT_VIOLATION = 1, EXIT_EXCEPTION = 2;

/** @var Parser */
private $configParser;

/** @var LoaderInterface */
private $strategyLoader;

/**
* @param Parser $parser
*/
public function setConfigParser(Parser $parser)
{
$this->configParser = $parser;
}

/**
* @param LoaderInterface $loader
*/
public function setStrategyLoader(LoaderInterface $loader)
{
$this->strategyLoader = $loader;
}

protected function configure()
{
$this->addArgument(
'source',
InputArgument::REQUIRED,
Message::CMD_RENDER_ARG_SOURCE
);

$this->addArgument(
'target',
InputArgument::REQUIRED,
Message::CMD_RENDER_ARG_TARGET
);

$this->addOption(
'config',
'c',
InputOption::VALUE_OPTIONAL,
Message::CMD_RENDER_OPT_CONFIG
);
$this->addOption(
'formatter',
'f',
InputOption::VALUE_OPTIONAL,
Message::CMD_RENDER_OPT_FORMATTER,
Svg::class
);
}

protected function execute(InputInterface $input, OutputInterface $output)
{
try {
$config = $this->createConfigBy($input);
$this->addClassMapToClassLoaderFrom($config);
$this->addLogLevelFormatsTo($output);
$label = Message::NAME . ' (' . Version::read() . ')';

$source = $input->getArgument('source');
$target = $input->getArgument('target');

$output->writeln($label . PHP_EOL);

$output->writeln(sprintf(Message::RENDER_FROM_TO, $source, $target) . PHP_EOL);

$options = [
'source' => $source,
'target' => $target,
'config' => $config,
'output' => $output
];

if ($this->loadStrategy($options)->execute()) {
return self::EXIT_SUCCESS;
} else {
return self::EXIT_VIOLATION;
}
} catch ( Exception $e) {
throw new Exception('Execution failed', self::EXIT_EXCEPTION, $e);
}
}

/**
* @param OutputInterface $output
*/
private function addLogLevelFormatsTo(OutputInterface $output)
{
$error = new OutputFormatterStyle('white', 'red');
$warning = new OutputFormatterStyle('red', 'yellow');
$info = new OutputFormatterStyle('white', 'green');
$debug = new OutputFormatterStyle('magenta');

$formatter = $output->getFormatter();

$formatter->setStyle(LogLevel::EMERGENCY, $error);
$formatter->setStyle(LogLevel::ALERT, $error);
$formatter->setStyle(LogLevel::CRITICAL, $error);
$formatter->setStyle(LogLevel::WARNING, $warning);
$formatter->setStyle(LogLevel::NOTICE, $info);
$formatter->setStyle(LogLevel::DEBUG, $debug);
}

/**
* @param InputInterface $input
* @throws \InvalidArgumentException
* @return Config
*/
private function createConfigBy(InputInterface $input)
{
$configFilePath = $input->getOption('config');

if ( !$configFilePath ) {
$config = [];
} else {
if (strpos($configFilePath, '://') === false) {
$this->configFilePath = realpath($configFilePath);
}

if (!is_readable($configFilePath)) {
throw new \InvalidArgumentException('Configfile "' . $configFilePath . '" is not readable');
}

$config = $this->configParser->parse(file_get_contents($configFilePath));

if (!is_array($config)) {
throw new \InvalidArgumentException('Configuration is invalid');
}
$config = $this->normalizePathsIn($config, $configFilePath);

}

$config = array_merge($config, array_filter($input->getOptions()));
$config = array_merge($config, array_filter($input->getArguments()));

return new Config($config);
}

/**
* @param array $config
* @param string $base
*
* @return array
*/
private function normalizePathsIn(array $config, $base)
{
if (isset($config['classMap']) && is_array($config['classMap'])) {
foreach ($config['classMap'] as $class => $path) {
$config['classMap'][$class] = $this->generateAbsolutePathFrom($path, $base);
}
}

return $config;
}

/**
* @param string $path
* @param string $base
*
* @return bool
*/
private function generateAbsolutePathFrom($path, $base)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('Path must be a string');
}

$path = trim($path);

if ($path[0] === '/') {
return $path;
}

if (defined('PHP_WINDOWS_VERSION_BUILD')
&& ($path[0] === '\\' || (strlen($path) >= 3 && preg_match('#^[A-Z]\:[/\\\]#i', substr($path, 0, 3))))
) {
return $path;
}

if (strpos($path, '://') !== false) {
return $path;
}

return $base . DIRECTORY_SEPARATOR . $path;
}

/**
* @param Config $config
*/
private function addClassMapToClassLoaderFrom(Config $config)
{
ApplicationFactory::$classLoader->addClassMap($config->getClassMap());
}

/**
* @param array $options
*
* @return StrategyInterface
*/
private function loadStrategy(array $options)
{
$factory = new RenderFactory();
$strategy = $factory->create();
$strategy->setOptions($options);
return $strategy;
}
}
36 changes: 36 additions & 0 deletions src/Command/Strategy/RenderFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Marco Muths
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

namespace PhpDA\Command\Strategy;

class RenderFactory extends AbstractFactory
{
public function create()
{
return new RenderStrategy(
$this->createWriteAdapter()
);
}
}
Loading