Skip to content

Commit

Permalink
Merge pull request #8 from heismehrab/v2
Browse files Browse the repository at this point in the history
refactor: Update middlewares and dependencies to be compatible with PHP 8.3
  • Loading branch information
subzerobo authored Aug 28, 2024
2 parents bfb0d60 + 990721d commit 4daa8f0
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 80 deletions.
7 changes: 4 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@
"ramsey/uuid": "^3.8",
"ralouphie/getallheaders": "^3.0",
"ircmaxell/random-lib": "^1.2",
"guzzlehttp/guzzle": "^6.3",
"subzerobo/sabalim-action-wrapper": "^1.0"
"guzzlehttp/guzzle": "^6.5",
"subzerobo/sabalim-action-wrapper": "^1.0",
"psr/http-server-handler": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "6.*"
"phpunit/phpunit": "11.3.*"
},
"suggest": {
"ext-xdebug": "Required for processing of request headers",
Expand Down
45 changes: 15 additions & 30 deletions src/Middlewares/GuzzleAPMMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

namespace Subzerobo\ElasticApmPhpAgent\Middlewares;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

use Subzerobo\ElasticApmPhpAgent\ActionWrappers\APMHandlerAbstract;

class GuzzleAPMMiddleware
Expand All @@ -23,35 +26,17 @@ public function __construct(APMHandlerAbstract $actionWrapper)
$this->actionWrapper = $actionWrapper;
}

public function __invoke(callable $handler) {

$apmActionWrapper = $this->actionWrapper;

$before = function($request, $options) use ($apmActionWrapper) {
$type = $options['type'] ?? "General";
$apmActionWrapper->handleBefore($request,$type,[]);
//var_dump( "BTap " . microtime(true) );
};

$after = function($request,$option,$response) use ($apmActionWrapper) {
$type = $options['type'] ?? "General";
$response->then(function (\Psr\Http\Message\ResponseInterface $response) use($apmActionWrapper,$type) {
$apmActionWrapper->handleAfter($response,$type,[]);
});
};

// Tap Function of Guzzle

return function ($request, array $options) use ($handler, $before, $after) {
if ($before) {
$before($request, $options);
}
$response = $handler($request, $options);
if ($after) {
$after($request, $options, $response);
}
return $response;
};
public function __invoke(Request $request, RequestHandler $requestHandler): Response
{
$type = $options['type'] ?? "General";

$this->actionWrapper->handleBefore($request,$type,[]);

$response = $requestHandler->handle($request);

$this->actionWrapper->handleAfter($response,$type,[]);

return $response;
}

}
29 changes: 14 additions & 15 deletions src/Middlewares/PSR7Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@
namespace Subzerobo\ElasticApmPhpAgent\Middlewares;


use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

use Subzerobo\ElasticApmPhpAgent\ApmAgent;
use Subzerobo\ElasticApmPhpAgent\Factories\DefaultTransactionNameFactoryAbstract;
use Subzerobo\ElasticApmPhpAgent\Factories\TransactionNameGeneratorInterface;

/**
* Add this middleware as the first middleware to not loose any span
* Add this middleware as the first middleware to not lose any span
*
* Class PSR7Middleware
* @package Subzerobo\ElasticApmPhpAgent\Middlewares
Expand All @@ -38,27 +37,24 @@ public function __construct($container, ApmAgent $apmAgent)
}

/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @param \Psr\Http\Message\ServerRequestInterface $request
* @param \Psr\Http\Server\RequestHandlerInterface $requestHandler
*
* @return ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
* @return \Psr\Http\Message\ResponseInterface
* @throws \Subzerobo\ElasticApmPhpAgent\Exceptions\DuplicateTransactionNameException
* @throws \Subzerobo\ElasticApmPhpAgent\Exceptions\TimerNotStartedException
* @throws \Subzerobo\ElasticApmPhpAgent\Exceptions\TimerNotStoppedException
* @throws \Subzerobo\ElasticApmPhpAgent\Exceptions\UnknownTransactionException
* @throws \Subzerobo\ElasticApmPhpAgent\Exceptions\UnknownTransactionException|\GuzzleHttp\Exception\GuzzleException
* @author alikaviani <[email protected]>
* @since 2019-06-15 09:55
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next=null)
public function __invoke(Request $request, RequestHandler $requestHandler): Response
{
// Start Transaction
$transactionEvent = $this->apmAgent->startTransaction();

// TODO: Implement __invoke() method.
$response = $next($request, $response);

$response = $requestHandler->handle($request);

// Set and Stop Transaction
$transactionEvent->setResult("HTTP " . $response->getStatusCode());
Expand All @@ -69,9 +65,12 @@ public function __invoke(ServerRequestInterface $request, ResponseInterface $res
'headers_sent' => true,
'status_code' => $response->getStatusCode(),]
);

$transactionEvent->stop();

$this->apmAgent->renameTransaction();
$this->apmAgent->send();

return $response;
}
}
4 changes: 1 addition & 3 deletions src/Wrappers/SpanEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,6 @@ public function getSpanID()
*/
public function setSpanName(string $name)
{
$name = strlen($name) > 1024 ? substr($name, 0, 1021).'...' : $name;

$this->span->setName($name);
}

Expand Down Expand Up @@ -555,4 +553,4 @@ public function getSpanObject()

return $this->span;
}
}
}
34 changes: 7 additions & 27 deletions src/Wrappers/Traits/EventTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ private function initContext(EventSharedData $sharedData) : Context
{
// Generate Random UUIDs
$this->id = UID::Generate(16); //Uuid::uuid4()->toString();
$this->trace_id = $this->trace_id = $_SERVER['HTTP_ELASTIC_APM_TRACEPARENT'] ? : UID::Generate(16); //Uuid::uuid4()->toString();
$this->trace_id = UID::Generate(16); //Uuid::uuid4()->toString();

// Set Shared Context Variable for further use
$this->sharedData = $sharedData;
Expand Down Expand Up @@ -278,19 +278,17 @@ final public function setRequest() {
],
'headers' => [
'content_type' => $headers['Content-Type'] ?? '',
'user_agent' => $this->clean_non_chars($headers['User-Agent']) ?? '',
'user_agent' => $headers['User-Agent'] ?? '',
'cookie' => $this->getCookieHeader($headers['Cookie'] ?? ''),
],
'env' => $this->getEnv(),
'cookies' => $this->getCookies(),
];

$ctxRequest = new Context\Request();
try {
$ctxRequest->mergeFromJsonString(json_encode($contextRequestArr));
$this->context->setRequest($ctxRequest);
}catch(\Exception $ex){
}
$ctxRequest->mergeFromJsonString(json_encode($contextRequestArr));

$this->context->setRequest($ctxRequest);
}

/**
Expand Down Expand Up @@ -319,11 +317,6 @@ final protected function getEnv()
? $_SERVER
: array_intersect_key($_SERVER, array_flip($envMask));

array_walk($env, function(&$value) {
if (is_array($value)) {
$value = json_encode($value);
}
});
return (object) $env;
}

Expand Down Expand Up @@ -359,19 +352,6 @@ final protected function getCookieHeader(string $cookieHeader) : string
// Returns an empty string if cookies are masked.
return empty($cookieMask) ? $cookieHeader : '';
}

/**
* Clean Bad Characters
*
* @param string $string
*
* @return string
* @author alikaviani <[email protected]>
* @since 2020-12-09 14:43
*/
final protected function clean_non_chars($string) {
return preg_replace('/[^A-Za-z0-9\-\;\(\)\,\ \/\.]/', '', $string); // Removes special chars.
}


}
}
4 changes: 2 additions & 2 deletions src/Wrappers/TransactionEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function start()
* @see https://github.com/elastic/apm-server/blob/v6.7.1/docs/spec/timestamp_epoch.json
*/
$this->setTimestamp();
$this->timestamp = intval(microtime(true) * 1000000);
$this->timestamp = microtime(true) * 1000000;
$this->transaction->setTimestamp($this->getTimestamp());
$this->timer->start();
}
Expand Down Expand Up @@ -274,4 +274,4 @@ public function getProtoBufTransaction() {
}


}
}

0 comments on commit 4daa8f0

Please sign in to comment.