Skip to content

Commit

Permalink
Feature/symfony 5 (#51)
Browse files Browse the repository at this point in the history
* fix: Restore Symfony 5.4 support
[symfony-5]

* fix: Fix edfault blackfire configuration
[symfony-5]

* test: Update tests to use internal httpbin image instead of calling real one
[symfony-5]

* fix: Deprecated: fnmatch(): Passing null to parameter #2 ($filename) of type string is deprecated in /data/sites/vendor/evaisse/simple-http-bundle/Http/Response.php on line 59
[symfony-5]

---------

Co-authored-by: Yoann MOROCUTTI <[email protected]>
  • Loading branch information
ymorocutti and Yoann MOROCUTTI authored Aug 2, 2023
1 parent 20f5238 commit bcb1762
Show file tree
Hide file tree
Showing 8 changed files with 1,455 additions and 947 deletions.
65 changes: 22 additions & 43 deletions DataCollector/ProfilerDataCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,19 @@

namespace evaisse\SimpleHttpBundle\DataCollector;

use evaisse\SimpleHttpBundle\Http\Event\AbstractStatementPrepareEvent;
use evaisse\SimpleHttpBundle\Http\Event\StatementErrorEvent;
use evaisse\SimpleHttpBundle\Http\Event\StatementPrepareEvent;
use evaisse\SimpleHttpBundle\Http\Event\StatementSuccessEventInterface;
use evaisse\SimpleHttpBundle\Http\StatementEventMap;
use evaisse\SimpleHttpBundle\Serializer\CustomGetSetNormalizer;
use evaisse\SimpleHttpBundle\Http\Exception;

use evaisse\SimpleHttpBundle\Serializer\RequestNormalizer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;

use Symfony\Component\Stopwatch\Stopwatch;



/*
* @author Emmanuel VAISSE
*/
Expand Down Expand Up @@ -61,13 +47,13 @@ class ProfilerDataCollector extends DataCollector implements EventSubscriberInte
* blackfire instance id
* @var string
*/
protected string $blackfireClientId;
protected ?string $blackfireClientId;

/**
* Access key to blackfire instance
* @var string
*/
protected string $blackfireClientToken;
protected ?string $blackfireClientToken;

/**
* sample amount used by blackfire commande
Expand Down Expand Up @@ -140,7 +126,6 @@ public function normalizeCalls()
$calls = array();

foreach ($this->calls as $k => $v) {

$calls[$k] = array(
'time' => $this->fetchTransferInfos($v),
'request' => $this->fetchRequestInfos($v['request']),
Expand All @@ -156,7 +141,7 @@ public function normalizeCalls()
if (isset($v['response'])) {
$calls[$k]['response']['fromHttpCache'] = false;
foreach ($calls[$k]['response']['headers'] as $h) {
foreach(['x-debug-uri:', 'x-debug-link:'] as $hk) {
foreach (['x-debug-uri:', 'x-debug-link:'] as $hk) {
if (stripos($h, $hk) === 0) {
list($hv, $url) = explode(':', $h, 2);
$url = trim($url);
Expand Down Expand Up @@ -261,7 +246,8 @@ public function onSuccess(ResponseEvent $event)
* If there is some cache hit informative headers,
* we set cache infos for the timeline
*/
if ($event->getResponse()
if (
$event->getResponse()
&& $event->getResponse()->headers->get('X-Cache')
&& stripos($event->getResponse()->headers->get('X-Cache')[0], 'HIT') !== false
) {
Expand All @@ -278,36 +264,28 @@ public function finishEvent($key)
unset($this->calls[$key]['stopWatchEvent']);
}

/**
* @param Request $request
* @return string
*/
public function buildCurlCommand(Request $request)
public function buildCurlCommand(Request $request): string
{
$command = 'curl -i
-X '.$request->getRealMethod();
foreach($request->headers->all() as $headerName => $headerValues) {
foreach($headerValues as $headerValue) {
-X ' . $request->getRealMethod();
foreach ($request->headers->all() as $headerName => $headerValues) {
foreach ($headerValues as $headerValue) {
$command .= "
-H \"$headerName: " . (string)$headerValue . "\"";
}
}

if (in_array($request->getRealMethod(), ['POST', 'PUT', 'PATCH']) && !empty($request->getContent())) {
$command.= '
--data "'.addcslashes($request->getContent(), '"').'"';
$command .= '
--data "' . addcslashes($request->getContent(), '"') . '"';
}

$command.='
"'.$request->getSchemeAndHttpHost().$request->getRequestUri().'"';
$command .= '
"' . $request->getSchemeAndHttpHost() . $request->getRequestUri() . '"';
return str_replace("\n", " \\\n", $command);
}

/**
* @param Request $request
* @return string
*/
public function buildBlackfireCommand(Request $request)
public function buildBlackfireCommand(Request $request): string
{
$command = "blackfire \\\n";
if (!empty($this->blackfireClientId)) {
Expand Down Expand Up @@ -391,7 +369,7 @@ public function fetchResponseInfos(Response $response)
"secure" => $c->isSecure(),
"httpOnly" => $c->isHttpOnly(),
"cleared" => $c->getExpiresTime() !== 0
&& time() > $c->getExpiresTime(),
&& time() > $c->getExpiresTime(),
);
}

Expand Down Expand Up @@ -505,10 +483,12 @@ public function hasClientErrors()
public function getClientErrors()
{
return array_filter($this->getCalls(), static function ($call) {
if ($call['response']
if (
$call['response']
&& array_key_exists('statusCode', $call['response'])
&& $call['response']['statusCode'] < 500
&& $call['response']['statusCode'] >= 400) {
&& $call['response']['statusCode'] >= 400
) {
return true;
}
});
Expand Down Expand Up @@ -594,7 +574,6 @@ protected function filterCall(array $call)
if ($requestJwt || $responseJwt) {
$call['auth']['type'] = "JWT";
}

} catch (\Exception $e) {
// prevent
}
Expand Down Expand Up @@ -688,8 +667,8 @@ public function reset()
*/
public function setBlackfireConfig(array $config): void
{
$this->blackfireClientId = $config["client_id"] ?? "";
$this->blackfireClientToken = $config["client_token"] ?? "";
$this->blackfireSamples = $config["samples"] ?? 10;
$this->blackfireClientId = $config['client_id'] ?? '';
$this->blackfireClientToken = $config['client_token'] ?? '';
$this->blackfireSamples = $config['samples'] ?? 10;
}
}
4 changes: 2 additions & 2 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

class Configuration implements ConfigurationInterface
{

public function getConfigTreeBuilder() : TreeBuilder
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('simple_http');
$rootNode = $treeBuilder->getRootNode();
Expand All @@ -26,6 +25,7 @@ public function getConfigTreeBuilder() : TreeBuilder
->defaultValue(10)
->end()
->end()
->addDefaultsIfNotSet()
->end()
->end();

Expand Down
10 changes: 5 additions & 5 deletions DependencyInjection/SimpleHttpExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace evaisse\SimpleHttpBundle\DependencyInjection;

use Exception;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
Expand All @@ -16,18 +17,17 @@ class SimpleHttpExtension extends Extension
{
/**
* {@inheritdoc}
* @throws Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');

if (!empty($config['blackfire'])) {
$container->getDefinition('simple_http.profiler.data_collector')
->addMethodCall('setBlackfireConfig', [$config['blackfire']]);
}
$container->getDefinition('simple_http.profiler.data_collector')
->addMethodCall('setBlackfireConfig', [$config['blackfire']]);
}
}
2 changes: 1 addition & 1 deletion Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected function parseResponse(): void
$this->error = ErrorHttpException::createHttpException($this);
}

if (fnmatch("application/json*", $this->headers->get('content-type'))) {
if (fnmatch("application/json*", $this->headers->get('content-type', ''))) {
$content = $this->getContent();
if (!empty($content)) {
$result = json_decode($content, true);
Expand Down
29 changes: 8 additions & 21 deletions Tests/Unit/PromisesTest.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

/**
* Testing promises
* User: evaisse
Expand All @@ -7,9 +8,6 @@

namespace evaisse\SimpleHttpBundle\Tests\Unit;


use evaisse\SimpleHttpBundle\Http\Statement;
use React\Promise\Deferred;
use Symfony\Component\HttpKernel\Exception\HttpException;

class PromisesTest extends AbstractTests
Expand All @@ -33,7 +31,7 @@ public function testPromises($code, $expectedResults)
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/status/{code}', array(
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/status/{code}', array(
'code' => $code
));

Expand All @@ -56,7 +54,6 @@ public function testPromises($code, $expectedResults)
foreach ($expectedResults as $expectedResult) {
$this->assertContains($expectedResult, $events);
}

}


Expand All @@ -67,13 +64,12 @@ public function testProxiedPromises($code, $expectedResults)
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/status/{code}', array(
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/status/{code}', array(
'code' => $code
));

$events = new \ArrayObject();


$stmt->onSuccess(function () use ($events) {
$events[] = 'success';
})->onError(function () use ($events) {
Expand All @@ -82,7 +78,6 @@ public function testProxiedPromises($code, $expectedResults)
$events[] = 'done';
});


$httpKernel->execute([
$stmt
]);
Expand All @@ -92,7 +87,6 @@ public function testProxiedPromises($code, $expectedResults)
foreach ($expectedResults as $expectedResult) {
$this->assertContains($expectedResult, $events);
}

}

/**
Expand All @@ -102,7 +96,7 @@ public function testPromisesOnTimeout()
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/delay/1');
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/delay/1');

$stmt->setTimeout(400);

Expand All @@ -123,20 +117,16 @@ public function testPromisesOnTimeout()
$this->assertCount(2, $events);
$this->assertContains("error", $events);
$this->assertContains("done", $events);


}



/**
* @dataProvider provideErrors
*/
public function testPromisesValues($code, $events)
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/status/{code}', [
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/status/{code}', [
'code' => $code,
]);

Expand Down Expand Up @@ -165,16 +155,14 @@ public function testPromisesValues($code, $events)
$this->assertTrue($events["finish"]);
}



/**
* @dataProvider provideErrors
*/
public function testPromisesAfterwards($code, $events)
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/status/{code}', [
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/status/{code}', [
'code' => $code,
]);

Expand Down Expand Up @@ -214,7 +202,7 @@ public function testAllPromisesFulfillsMultipleTimesAfterwards($code, $events)
{
list($helper, $httpKernel) = $this->createContext();

$stmt = $helper->prepare("GET", 'https://httpbin.org/status/{code}', [
$stmt = $helper->prepare("GET", AbstractTests::$baseUrl . '/status/{code}', [
'code' => $code,
]);

Expand Down Expand Up @@ -242,5 +230,4 @@ public function testAllPromisesFulfillsMultipleTimesAfterwards($code, $events)

$this->assertCount(4, $events);
}

}
}
26 changes: 13 additions & 13 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@
"require": {
"php": "^8.0",
"react/promise": "2.2.*",
"symfony/http-foundation": "^6.0",
"symfony/browser-kit": "^6.0",
"symfony/event-dispatcher": "^6.0",
"symfony/serializer": "^6.0",
"symfony/http-kernel": "^6.0",
"symfony/stopwatch": "^6.0",
"symfony/config": "^6.0",
"symfony/dependency-injection": "^6.0",
"symfony/security-http": "^6.0",
"symfony/twig-bundle": "^6.0",
"sensio/framework-extra-bundle": "^6.0",
"symfony/http-foundation": "^5.4 || ^6.0",
"symfony/browser-kit": "^5.4 || ^6.0",
"symfony/event-dispatcher": "^5.4 || ^6.0",
"symfony/serializer": "^5.4 || ^6.0",
"symfony/http-kernel": "^5.4 || ^6.0",
"symfony/stopwatch": "^5.4 || ^6.0",
"symfony/config": "^5.4 || ^6.0",
"symfony/dependency-injection": "^5.4 || ^6.0",
"symfony/security-http": "^5.4 || ^6.0",
"symfony/twig-bundle": "^5.4 || ^6.0",
"symfony/mime": "^5.4 || ^6.0",
"sensio/framework-extra-bundle": "^5.5 || ^6.0",
"ext-dom": "*",
"ext-json": "*",
"ext-curl": "*",
"symfony/mime": "^6.0"
"ext-curl": "*"
},
"conflict": {
"symfony/serializer": "6.0.0"
Expand Down
Loading

0 comments on commit bcb1762

Please sign in to comment.