Skip to content

Commit

Permalink
Merge pull request #1 from Moesif/new-branch
Browse files Browse the repository at this point in the history
New branch
  • Loading branch information
matthewtanner91 authored Mar 29, 2024
2 parents 5a77021 + c91593e commit 1605151
Show file tree
Hide file tree
Showing 8 changed files with 205 additions and 87 deletions.
144 changes: 78 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ moesif:
options:
max_queue_size: 50
max_batch_size: 25

hooks_class: 'App\Configuration\MyMoesifHooks'
```
Your Moesif Application Id can be found in the [_Moesif Portal_](https://www.moesif.com/).
Expand Down Expand Up @@ -64,23 +64,29 @@ If set, will override the default max queue size before data is sent over to Moe
Type: Int
If set, will override the default max batch size that is sent over to Moesif. The default is `10`.

## Subscriber Configuration Options
#### __`hooks_class`__

Certain functionalities can be overridden and customized within the plugin. To override these functions, within your projects `/src/EventSubscriber` directory, you must add a `CustomMoesifSubscriber.php` file.
Type: String
Optional, if set, this should be your implementation of the `Moesif\MoesifBundle\Interfaces\MoesifHooksInterface`.

## User Hook class Options

Certain functionalities can be overridden and customized within the plugin with hooks.

In your `services.yaml` file you will also need to add the following:
``` yaml
services:

# Existing services config
...
Within the `MyMoesifHooks.php` file, you will need to override the following methods:

App\EventSubscriber\CustomMoesifSubscriber:
class: App\EventSubscriber\CustomMoesifSubscriber # Ensure this matches the namespace and class name of your custom subscriber
tags:
- { name: moesif.event_subscriber }
```php
use Moesif\MoesifBundle\Interfaces\MoesifHooksInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class MyMoesifHooks implements MoesifHooksInterface {
// your implementation of every method below.
}
```
Within the `CustomMoesifSubscriber.php` file, you will need to override the following methods:

The method you should implement is:

### __`identifyUserId`__

Expand Down Expand Up @@ -129,67 +135,73 @@ Optional, a function that takes a $request and $response and returns $metdata wh
Type: `($request, $response) => String`
Optional, a function that takes a $request and $response and returns true if this API call should be not be sent to Moesif.

Here is an example of what the `CustomMoesifSubscriber.php` file may look like:
Here is an example of what the `MyMoesifHooks.php` file may look like:

``` php
<?php
namespace App\EventSubscriber;
namespace App\Configuration;
use Moesif\MoesifBundle\Interfaces\MoesifHooksInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Moesif\MoesifBundle\Interfaces\EventSubscriberInterface as MoesifEventSubscriberInterface;
class CustomMoesifSubscriber implements EventSubscriberInterface {
// Implement all abstract methods, but focus on the ones you want to override
public function identifyUserId(Request $request, Response $response): ?string {
// Your custom logic to identify the user
// For example, extract user ID from JWT token
return "1234abcd";
}
public function identifyCompanyId(Request $request, Response $response): ?string {
// Your custom logic to identify the company
// For example, extract company ID from request headers
return "5678efgh";
}
public function identifySessionToken(Request $request, Response $response): ?string
{
return null;
}
public function getMetadata(Request $request, Response $response): ?array
{
return null;
}
public function skip(Request $request, Response $response): bool
{
return false;
}
public function maskRequestHeaders(array $headers): array
{
return $headers;
}
public function maskResponseHeaders(array $headers): array
{
return $headers;
}
public function maskRequestBody(string $body): ?string
{
return $body;
}
public function maskResponseBody(string $body): ?string
{
return $body;
}
class MyMoesifHooks implements MoesifHooksInterface {
public function __construct() {
}
public function identifyUserId(Request $request, Response $response): string|null
{
return 'nihao1';
}
public function identifyCompanyId(Request $request, Response $response): string|null
{
return $request->headers->get('X-Company-Id');
}
public function identifySessionToken(Request $request, Response $response): string|null
{
return null;
}
public function getMetadata(Request $request, Response $response): ?array
{
return null;
}
public function skip(Request $request, Response $response): bool
{
return false;
}
public function maskRequestHeaders(array $headers): array
{
return $headers;
}
public function maskResponseHeaders(array $headers): array
{
return $headers;
}
public function maskRequestBody($body)
{
// this can be a string or array object.
// because prior to php 8, can not declare union type (such as string|array)
return $body;
}
public function maskResponseBody($body)
{
// this can be a string or array object.
// because prior to php 8, can not declare union type (such as string|array)
return $body;
}
}
```

## Update a Single User
Expand Down
10 changes: 3 additions & 7 deletions src/Consumer/SendCurlTaskConsumer.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function persist(array $batch): bool {
public function updateUser(array $userData): bool {
$data = json_encode($userData);
$url = $this->protocol . '://' . $this->host . $this->usersEndpoint;

return $this->fork ? $this->_executeForked($url, $data) : $this->_executeCurl($url, $data);
}

Expand Down Expand Up @@ -107,10 +107,6 @@ public function updateSubscriptionsBatch(array $subscriptionsBatchData): bool {
}

protected function _executeCurl(string $url, string $data): bool {

if ($this->debug) {
// $this->logger->error('Moesif cURL data: ' . $data);
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
Expand All @@ -126,13 +122,13 @@ protected function _executeCurl(string $url, string $data): bool {

$curlCommand = 'curl -X POST -H "Content-Type: application/json" -H "X-Moesif-Application-Id: ' . $this->appId . '" -d \'' . addslashes($data) . '\' \'' . $url . '\'';
if ($this->debug) {
$this->logger->info('Moesif cURL command: ' . $curlCommand);
$this->logger->debug('Moesif cURL command: ' . $curlCommand);
}

$result = curl_exec($ch);

if ($this->debug) {
$this->logger->error('Moesif cURL result: ' . $result);
$this->logger->debug('Moesif cURL result: ' . $result);
}

if (curl_errno($ch)) {
Expand Down
3 changes: 3 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public function getConfigTreeBuilder(): TreeBuilder
->booleanNode('debug')
->defaultFalse()
->end()
->scalarNode('hooks_class')
->defaultValue('Moesif\MoesifBundle\Interfaces\MoesifDefaultHooks')
->end()
->arrayNode('options')
->addDefaultsIfNotSet()
->children()
Expand Down
8 changes: 8 additions & 0 deletions src/DependencyInjection/MoesifExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Definition;

class MoesifExtension extends Extension
{
Expand All @@ -33,6 +35,12 @@ public function load(array $configs, ContainerBuilder $container)
$container->setParameter('moesif.moesif_application_id', $config['moesif_application_id']);
}

if ($config['hooks_class']) {
$userMoesifConfigClass = $config['hooks_class'];
$definition = new Definition($userMoesifConfigClass);
$container->setDefinition('moesif.user_hooks', $definition);
}

if (isset($config['debug'])) {
$container->setParameter('moesif.debug', $config['debug']);
}
Expand Down
58 changes: 48 additions & 10 deletions src/EventSubscriber/MoesifSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,22 @@
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Moesif\MoesifBundle\Service\MoesifApiService;
use Moesif\MoesifBundle\Interfaces\EventSubscriberInterface as MoesifEventSubscriberInterface;
use Moesif\MoesifBundle\Interfaces\MoesifHooksInterface;

class MoesifSubscriber implements SymfonyEventSubscriberInterface, MoesifEventSubscriberInterface
use Psr\Log\LoggerInterface;

class MoesifSubscriber implements SymfonyEventSubscriberInterface
{
private MoesifApiService $moesifApiService;
private LoggerInterface $logger;
private $options;

private $configHooks;

public function __construct(MoesifApiService $moesifApiService)
public function __construct(MoesifApiService $moesifApiService, MoesifHooksInterface $configHooks, LoggerInterface $logger = null)
{
$this->configHooks = $configHooks;
$this->logger = $logger;
$this->moesifApiService = $moesifApiService;
}

Expand All @@ -32,7 +40,11 @@ public static function getSubscribedEvents(): array

public function onKernelRequest(RequestEvent $event): void
{
// Optional: Perform actions before the request is handled, such as initializing logging or tracking
$startTime = new DateTime();
$startTime->setTimezone(new DateTimeZone("UTC"));

$request = $event->getRequest();
$request->attributes->set('mo_start_time', $startTime);
}

public function onKernelResponse(ResponseEvent $event): void
Expand All @@ -48,9 +60,8 @@ public function onKernelResponse(ResponseEvent $event): void

private function prepareData(Request $request, Response $response): array
{
$startTime = new DateTime();
$startTime->setTimezone(new DateTimeZone("UTC"));

$startTime = $request->attributes->get('mo_start_time');

$endTime = new DateTime();
$endTime->setTimezone(new DateTimeZone("UTC"));

Expand Down Expand Up @@ -78,7 +89,6 @@ private function prepareData(Request $request, Response $response): array
'user_id' => $this->identifyUserId($request, $response),
'company_id' => $this->identifyCompanyId($request, $response),
'session_token' => $this->identifySessionToken($request, $response),
'company_id' => $this->identifyCompanyId($request, $response),
'metadata' => $this->getMetadata($request, $response),
];

Expand All @@ -101,46 +111,74 @@ private function getIp(Request $request): ?string

public function identifyUserId(Request $request, Response $response): ?string
{

if ($this->configHooks) {
return $this->configHooks->identifyUserId($request, $response);
}
return null;
}

public function identifyCompanyId(Request $request, Response $response): ?string
{
if ($this->configHooks) {
return $this->configHooks->identifyCompanyId($request, $response);
}
return null;
}

public function identifySessionToken(Request $request, Response $response): ?string
{
if ($this->configHooks) {
return $this->configHooks->identifySessionToken($request, $response);
}
return null;
}

public function getMetadata(Request $request, Response $response): ?array
{
if ($this->configHooks) {
return $this->configHooks->getMetadata($request, $response);
}
return null;
}

public function skip(Request $request, Response $response): bool
{
if ($this->configHooks) {
return $this->configHooks->skip($request, $response);
}
return false;
}

public function maskRequestHeaders(array $headers): array
{
if ($this->configHooks) {
return $this->configHooks->maskRequestHeaders($headers);
}
return $headers;
}

public function maskResponseHeaders(array $headers): array
{
if ($this->configHooks) {
return $this->configHooks->maskResponseHeaders($headers);
}
return $headers;
}

public function maskRequestBody(string $body): ?string
public function maskRequestBody($body)
{
if ($this->configHooks) {
return $this->configHooks->maskRequestBody($body);
}
return $body;
}

public function maskResponseBody(string $body): ?string
public function maskResponseBody($body)
{
if ($this->configHooks) {
return $this->configHooks->maskResponseBody($body);
}
return $body;
}
}
Loading

0 comments on commit 1605151

Please sign in to comment.