From 35147fecb29a0602a6d39c61181a16c78e9afe94 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 3 Jul 2016 09:14:27 +0200 Subject: [PATCH 1/2] Replaced cli execution using expressive middleware by symfony/console --- bin/cli | 17 ++-- composer.json | 3 +- config/autoload/services.global.php | 4 + src/CliCommands/GenerateShortcodeCommand.php | 95 ++++++++++++++++++++ 4 files changed, 108 insertions(+), 11 deletions(-) create mode 100644 src/CliCommands/GenerateShortcodeCommand.php diff --git a/bin/cli b/bin/cli index 0aca7dd0..1816b80f 100755 --- a/bin/cli +++ b/bin/cli @@ -1,17 +1,14 @@ #!/usr/bin/env php get(Application::class); -$command = count($_SERVER['argv']) > 1 ? $_SERVER['argv'][1] : ''; -$request = ServerRequestFactory::fromGlobals() - ->withMethod('CLI') - ->withUri(new Uri(sprintf('/%s', $command))); -$app->run($request); +$app = new CliApp(); +$app->addCommands([ + $container->get(GenerateShortcodeCommand::class), +]); +$app->run(); diff --git a/composer.json b/composer.json index d43d7fbb..922e9067 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,8 @@ "zendframework/zend-servicemanager": "^3.0", "doctrine/orm": "^2.5", "guzzlehttp/guzzle": "^6.2", - "acelaya/zsm-annotated-services": "^0.2.0" + "acelaya/zsm-annotated-services": "^0.2.0", + "symfony/console": "^3.0" }, "require-dev": { "phpunit/phpunit": "^4.8", diff --git a/config/autoload/services.global.php b/config/autoload/services.global.php index 300f1bf3..6027973d 100644 --- a/config/autoload/services.global.php +++ b/config/autoload/services.global.php @@ -1,4 +1,5 @@ AnnotatedFactory::class, Cache::class => CacheFactory::class, + // Cli commands + CliCommands\GenerateShortcodeCommand::class => AnnotatedFactory::class, + // Middleware Middleware\CliRoutable\GenerateShortcodeMiddleware::class => AnnotatedFactory::class, Middleware\Routable\RedirectMiddleware::class => AnnotatedFactory::class, diff --git a/src/CliCommands/GenerateShortcodeCommand.php b/src/CliCommands/GenerateShortcodeCommand.php new file mode 100644 index 00000000..9f545dce --- /dev/null +++ b/src/CliCommands/GenerateShortcodeCommand.php @@ -0,0 +1,95 @@ +urlShortener = $urlShortener; + $this->domainConfig = $domainConfig; + } + + public function configure() + { + $this->setName('generate-shortcode') + ->setDescription('Generates a shortcode for provided URL and returns the short URL') + ->addArgument('longUrl', InputArgument::REQUIRED, 'The long URL to parse'); + } + + public function interact(InputInterface $input, OutputInterface $output) + { + $longUrl = $input->getArgument('longUrl'); + if (! empty($longUrl)) { + return; + } + + /** @var QuestionHelper $helper */ + $helper = $this->getHelper('question'); + $question = new Question( + 'A long URL was not provided. Which URL do you want to shorten?: ' + ); + + $longUrl = $helper->ask($input, $output, $question); + if (! empty($longUrl)) { + $input->setArgument('longUrl', $longUrl); + } + } + + public function execute(InputInterface $input, OutputInterface $output) + { + $longUrl = $input->getArgument('longUrl'); + + try { + if (! isset($longUrl)) { + $output->writeln('A URL was not provided!'); + return; + } + + $shortcode = $this->urlShortener->urlToShortCode(new Uri($longUrl)); + $shortUrl = (new Uri())->withPath($shortcode) + ->withScheme($this->domainConfig['schema']) + ->withHost($this->domainConfig['hostname']); + + $output->writeln([ + sprintf('Processed URL %s', $longUrl), + sprintf('Generated URL %s', $shortUrl), + ]); + } catch (InvalidUrlException $e) { + $output->writeln( + sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl) + ); + } catch (\Exception $e) { + $output->writeln('' . $e . ''); + } + } +} From e09915dd211bcd57dbaee755a8592470cd0184c8 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 3 Jul 2016 09:16:56 +0200 Subject: [PATCH 2/2] Removed cli-related middlewares and factories --- config/autoload/cli-routes.global.php | 15 --- .../autoload/middleware-pipeline.global.php | 2 - config/autoload/services.global.php | 2 - .../GenerateShortcodeMiddleware.php | 91 ------------------- .../Factory/CliParamsMiddlewareFactory.php | 32 ------- tests/Middleware/CliParamsMiddlewareTest.php | 91 ------------------- .../CliParamsMiddlewareFactoryTest.php | 29 ------ 7 files changed, 262 deletions(-) delete mode 100644 config/autoload/cli-routes.global.php delete mode 100644 src/Middleware/CliRoutable/GenerateShortcodeMiddleware.php delete mode 100644 src/Middleware/Factory/CliParamsMiddlewareFactory.php delete mode 100644 tests/Middleware/CliParamsMiddlewareTest.php delete mode 100644 tests/Middleware/Factory/CliParamsMiddlewareFactoryTest.php diff --git a/config/autoload/cli-routes.global.php b/config/autoload/cli-routes.global.php deleted file mode 100644 index c2aafdf1..00000000 --- a/config/autoload/cli-routes.global.php +++ /dev/null @@ -1,15 +0,0 @@ - [ - [ - 'name' => 'cli-generate-shortcode', - 'path' => '/generate-shortcode', - 'middleware' => CliRoutable\GenerateShortcodeMiddleware::class, - 'allowed_methods' => ['CLI'], - ], - ], - -]; diff --git a/config/autoload/middleware-pipeline.global.php b/config/autoload/middleware-pipeline.global.php index d033f9b2..8a393ce1 100644 --- a/config/autoload/middleware-pipeline.global.php +++ b/config/autoload/middleware-pipeline.global.php @@ -1,5 +1,4 @@ [ 'middleware' => [ ApplicationFactory::ROUTING_MIDDLEWARE, - CliParamsMiddleware::class, Helper\UrlHelperMiddleware::class, ApplicationFactory::DISPATCH_MIDDLEWARE, ], diff --git a/config/autoload/services.global.php b/config/autoload/services.global.php index 6027973d..617242b5 100644 --- a/config/autoload/services.global.php +++ b/config/autoload/services.global.php @@ -43,9 +43,7 @@ return [ CliCommands\GenerateShortcodeCommand::class => AnnotatedFactory::class, // Middleware - Middleware\CliRoutable\GenerateShortcodeMiddleware::class => AnnotatedFactory::class, Middleware\Routable\RedirectMiddleware::class => AnnotatedFactory::class, - Middleware\CliParamsMiddleware::class => Middleware\Factory\CliParamsMiddlewareFactory::class, ], 'aliases' => [ 'em' => EntityManager::class, diff --git a/src/Middleware/CliRoutable/GenerateShortcodeMiddleware.php b/src/Middleware/CliRoutable/GenerateShortcodeMiddleware.php deleted file mode 100644 index 6573ed60..00000000 --- a/src/Middleware/CliRoutable/GenerateShortcodeMiddleware.php +++ /dev/null @@ -1,91 +0,0 @@ -urlShortener = $urlShortener; - $this->domainConfig = $domainConfig; - } - - /** - * Process an incoming request and/or response. - * - * Accepts a server-side request and a response instance, and does - * something with them. - * - * If the response is not complete and/or further processing would not - * interfere with the work done in the middleware, or if the middleware - * wants to delegate to another process, it can use the `$out` callable - * if present. - * - * If the middleware does not return a value, execution of the current - * request is considered complete, and the response instance provided will - * be considered the response to return. - * - * Alternately, the middleware may return a response instance. - * - * Often, middleware will `return $out();`, with the assumption that a - * later middleware will return a response. - * - * @param Request $request - * @param Response $response - * @param null|callable $out - * @return null|Response - */ - public function __invoke(Request $request, Response $response, callable $out = null) - { - $longUrl = $request->getAttribute('longUrl'); - - try { - if (! isset($longUrl)) { - $response->getBody()->write('A URL was not provided!' . PHP_EOL); - return; - } - - $shortcode = $this->urlShortener->urlToShortCode(new Uri($longUrl)); - $shortUrl = (new Uri())->withPath($shortcode) - ->withScheme($this->domainConfig['schema']) - ->withHost($this->domainConfig['hostname']); - - $response->getBody()->write( - sprintf('Processed URL "%s".%sGenerated short URL "%s"', $longUrl, PHP_EOL, $shortUrl) . PHP_EOL - ); - } catch (InvalidUrlException $e) { - $response->getBody()->write( - sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl) . PHP_EOL - ); - } catch (\Exception $e) { - $response->getBody()->write($e); - } finally { - return $response; - } - } -} diff --git a/src/Middleware/Factory/CliParamsMiddlewareFactory.php b/src/Middleware/Factory/CliParamsMiddlewareFactory.php deleted file mode 100644 index 9be7f52e..00000000 --- a/src/Middleware/Factory/CliParamsMiddlewareFactory.php +++ /dev/null @@ -1,32 +0,0 @@ -__invoke( - ServerRequestFactory::fromGlobals(), - $originalResponse, - function ($req, $resp) use (&$invoked) { - $invoked = true; - return $resp; - } - ); - - $this->assertSame($originalResponse, $response); - $this->assertTrue($invoked); - } - - /** - * @test - */ - public function nonSuccessRouteResultJustInvokesNextMiddleware() - { - $middleware = new CliParamsMiddleware([], 'cli'); - - $invoked = false; - $originalResponse = new Response(); - $routeResult = $this->prophesize(RouteResult::class); - $routeResult->isSuccess()->willReturn(false)->shouldBeCalledTimes(1); - - $response = $middleware->__invoke( - ServerRequestFactory::fromGlobals()->withAttribute(RouteResult::class, $routeResult->reveal()), - $originalResponse, - function ($req, $resp) use (&$invoked) { - $invoked = true; - return $resp; - } - ); - - $this->assertSame($originalResponse, $response); - $this->assertTrue($invoked); - } - - /** - * @test - */ - public function properRouteWillInjectAttributeInResponse() - { - $expectedLongUrl = 'http://www.google.com'; - $middleware = new CliParamsMiddleware(['foo', 'bar', $expectedLongUrl], 'cli'); - - $invoked = false; - $originalResponse = new Response(); - $routeResult = $this->prophesize(RouteResult::class); - $routeResult->isSuccess()->willReturn(true)->shouldBeCalledTimes(1); - $routeResult->getMatchedRouteName()->willReturn('cli-generate-shortcode')->shouldBeCalledTimes(1); - /** @var ServerRequestInterface $request */ - $request = null; - - $response = $middleware->__invoke( - ServerRequestFactory::fromGlobals()->withAttribute(RouteResult::class, $routeResult->reveal()), - $originalResponse, - function ($req, $resp) use (&$invoked, &$request) { - $invoked = true; - $request = $req; - return $resp; - } - ); - - $this->assertSame($originalResponse, $response); - $this->assertEquals($expectedLongUrl, $request->getAttribute('longUrl')); - $this->assertTrue($invoked); - } -} diff --git a/tests/Middleware/Factory/CliParamsMiddlewareFactoryTest.php b/tests/Middleware/Factory/CliParamsMiddlewareFactoryTest.php deleted file mode 100644 index 3fad4bab..00000000 --- a/tests/Middleware/Factory/CliParamsMiddlewareFactoryTest.php +++ /dev/null @@ -1,29 +0,0 @@ -factory = new CliParamsMiddlewareFactory(); - } - - /** - * @test - */ - public function serviceIsCreated() - { - $instance = $this->factory->__invoke(new ServiceManager(), ''); - $this->assertInstanceOf(CliParamsMiddleware::class, $instance); - } -}