Page MenuHomeDevCentral

No OneTemporary

diff --git a/app/Analyzers/GitHubPayloadAnalyzer.php b/app/Analyzers/GitHubPayloadAnalyzer.php
new file mode 100644
index 0000000..8586331
--- /dev/null
+++ b/app/Analyzers/GitHubPayloadAnalyzer.php
@@ -0,0 +1,135 @@
+<?php
+
+namespace Nasqueron\Notifications\Analyzers;
+
+
+use Config;
+
+class GitHubPayloadAnalyzer {
+ ///
+ /// Private members
+ ///
+
+ /**
+ * The project name, used to load specific configuration and offer defaults
+ * @var string
+ */
+ private $project;
+
+ /**
+ * The GitHub event triggering this request
+ * @var string
+ */
+ private $event;
+
+ /**
+ * The request content, as a structured data
+ * @var stdClass
+ */
+ private $payload;
+
+
+ /**
+ * The configuration for the payload analyzer
+ * @var GitHubPayloadAnalyzerConfiguration;
+ */
+ private $configuration;
+
+ ///
+ /// Constructor
+ ///
+
+ /**
+ * Creates a new GitHubPayloadAnalyzer instance.
+ *
+ * @param string $project
+ * @param string $event
+ * @param stdClass $payload
+ */
+ public function __construct($project, $event, $payload) {
+ $this->project = $project;
+ $this->event = $event;
+ $this->payload = $payload;
+
+ $this->loadConfiguration($project);
+ }
+
+ ///
+ /// Configuration
+ ///
+
+ const CONFIG_DEFAULT_FILE = 'default.json';
+
+ public function getConfigurationFileName () {
+ $dir = Config::get('services.github.analyzer.configDir');
+ $filename = $dir . '/' . $this->project . '.json';
+
+ if (!file_exists($filename)) {
+ return $dir . '/' . static::CONFIG_DEFAULT_FILE;
+ }
+
+ return $filename;
+ }
+
+ public function loadConfiguration () {
+ $fileName = $this->getConfigurationFileName();
+ $mapper = new \JsonMapper();
+ $this->configuration = $mapper->map(
+ json_decode(file_get_contents($fileName)),
+ new GitHubPayloadAnalyzerConfiguration()
+ );
+ }
+
+ ///
+ /// Properties
+ ///
+
+ public function getRepository () {
+ if ($this->isAdministrativeEvent()) {
+ return '';
+ }
+ return $this->payload->repository->name;
+ }
+
+ ///
+ /// Qualification of the payload
+ ///
+
+ public function isAdministrativeEvent () {
+ $administrativeEvents = [
+ 'membership', // Member added to team
+ 'ping', // Special ping ponf event, fired on new hook
+ 'repository', // Repository created
+ ];
+
+ return in_array($this->event, $administrativeEvents);
+ }
+
+ /**
+ * Gets the group for a specific payload
+ *
+ * @return string the group, central part of the routing key
+ */
+ public function getGroup () {
+ // Some events are organization-level only and can't be mapped to an
+ // existing repository.
+ if ($this->isAdministrativeEvent()) {
+ return $this->configuration->administrativeGroup;
+ }
+
+ // If the payload is about some repository matching a table of
+ // symbols, we need to sort it to the right group.
+ $repository = $this->getRepository();
+ foreach ($this->configuration->repositoryMapping as $mapping) {
+ if ($mapping->doesRepositoryBelong($repository)) {
+ return $mapping->group;
+ }
+ }
+
+ // By default, fallback group is the project name or a specified value.
+ if (empty($this->configuration->defaultGroup)) {
+ return $this->project;
+ }
+ return $this->configuration->defaultGroup;
+ }
+}
diff --git a/app/Analyzers/GitHubPayloadAnalyzerConfiguration.php b/app/Analyzers/GitHubPayloadAnalyzerConfiguration.php
new file mode 100644
index 0000000..6c41cb5
--- /dev/null
+++ b/app/Analyzers/GitHubPayloadAnalyzerConfiguration.php
@@ -0,0 +1,26 @@
+<?php
+
+namespace Nasqueron\Notifications\Analyzers;
+
+class GitHubPayloadAnalyzerConfiguration {
+ /**
+ * The group for organization only events
+ *
+ * @var string
+ */
+ public $administrativeGroup;
+
+ /**
+ * The default group to fallback for any event not mapped in another group
+ *
+ * @var string
+ */
+ public $defaultGroup;
+
+ /**
+ * An array of RepositoryGroupMapping objects to match repositories & groups
+ *
+ * @var RepositoryGroupMapping[]
+ */
+ public $repositoryMapping;
+}
\ No newline at end of file
diff --git a/app/Analyzers/RepositoryGroupMapping.php b/app/Analyzers/RepositoryGroupMapping.php
new file mode 100644
index 0000000..44da5bc
--- /dev/null
+++ b/app/Analyzers/RepositoryGroupMapping.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace Nasqueron\Notifications\Analyzers;
+
+class RepositoryGroupMapping {
+ ///
+ /// Properties
+ ///
+
+ /**
+ * The group the mapped repositories belong to
+ *
+ * @var string
+ */
+ public $group;
+
+ /**
+ * An array of the repositories, each item a string with the name of the
+ * repository. The wildcard '*' is allowed to specify several repositories.
+ *
+ * @var array
+ */
+ public $repositories;
+
+ ///
+ /// Helper methods
+ ///
+
+ /**
+ * Determines if the specified repository matches a pattern
+ *
+ * @param string the pattern, with * and ? allowed
+ * @param string the repository name to compare with the pattern
+ * @return bool
+ */
+ public static function doesRepositoryMatch ($pattern, $repository) {
+ return ($pattern == $repository) || fnmatch($pattern, $repository);
+ }
+
+ /**
+ * Determines if the specified repository belong to this mapping
+ *
+ * @return bool
+ */
+ public function doesRepositoryBelong ($actualRepository) {
+ foreach ($this->repositories as $candidateRepository) {
+ if (static::doesRepositoryMatch($candidateRepository, $actualRepository)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/app/Jobs/SendMessageToBroker.php b/app/Jobs/SendMessageToBroker.php
new file mode 100644
index 0000000..d0a2338
--- /dev/null
+++ b/app/Jobs/SendMessageToBroker.php
@@ -0,0 +1,68 @@
+<?php
+
+namespace Nasqueron\Notifications\Jobs;
+
+use Illuminate\Contracts\Bus\SelfHandling;
+use Keruald\Brokers\AMQPBroker;
+use Nasqueron\Notifications\Jobs\Job;
+
+class SendMessageToBroker extends Job implements SelfHandling {
+
+ /**
+ * The routing key, for topic exchange
+ *
+ * @var string
+ */
+ private $routingKey = '';
+
+ /**
+ * The message to send
+ *
+ * @var string
+ */
+ private $message = '';
+
+ /**
+ * Create a new job instance.
+ *
+ * @param $routingKey the routing key, for topic exchange
+ * @param $message the message to send
+ *
+ * @return void
+ */
+ public function __construct ($routingKey, $message) {
+ $this->routingKey = $routingKey;
+ $this->message = $message;
+ }
+
+ /**
+ * Executes the job.
+ *
+ * @return void
+ */
+ public function handle() {
+ $this->getBroker()
+ ->setExchangeTarget("github_events")
+ ->routeTo($this->routingKey)
+ ->sendMessage($this->message);
+ }
+
+ /**
+ * Gets broker
+ *
+ * @return Broker
+ * @todo Transform into a service provider, a singleton pattern and a facade
+ */
+ public function getBroker() {
+ $broker = new AMQPBroker();
+ $broker->connect(
+ Config::get('broker.connections.amqp.host'),
+ Config::get('broker.connections.amqp.port'),
+ Config::get('broker.connections.amqp.username'),
+ Config::get('broker.connections.amqp.password'),
+ Config::get('broker.connections.amqp.vhost')
+ );
+ return $broker;
+ }
+}
+
diff --git a/app/Listeners/AMQPEventListener.php b/app/Listeners/AMQPEventListener.php
new file mode 100644
index 0000000..33c8948
--- /dev/null
+++ b/app/Listeners/AMQPEventListener.php
@@ -0,0 +1,85 @@
+<?php
+
+namespace Nasqueron\Notifications\Listeners;
+
+use Nasqueron\Notifications\Events\GitHubPayloadEvent;
+use Nasqueron\Notifications\Analyzers\GitHubPayloadAnalyzer;
+
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+
+use Keruald\Broker\AMQPBroker;
+
+class AMQPEventListener {
+ ///
+ /// GitHub events
+ ///
+
+ /**
+ * Gets routing key, to allow consumers to select the topic they subscribe to.
+ *
+ * @param GitHubPayloadEvent $event the payload event
+ */
+ protected static function getRoutingKey (GitHubPayloadEvent $event) {
+ $key = [
+ strtolower($event->door),
+ self::getGroup($event),
+ $event->event
+ ];
+ return implode('.', $key);
+ }
+
+ protected static function getAnalyzer (GitHubPayloadEvent $event) {
+ return new GitHubPayloadAnalyzer(
+ $event->door,
+ $event->event,
+ $event->payload
+ );
+ }
+
+ /**
+ * Gets the group for a specific payload
+ *
+ * @return string the group, central part of the routing key
+ */
+ protected static function getGroup (GitHubPayloadEvent $event) {
+ $analyzer = self::getAnalyzer($event);
+ return $analyzer->getGroup();
+ }
+
+ /**
+ * Handles a GitHub payload event.
+ *
+ * @param GitHubPayloadEvent $event
+ * @return void
+ */
+ public function onGitHubPayload(GitHubPayloadEvent $event) {
+ $message = json_encode($event->payload);
+ $routingKey = static::getRoutingKey($event);
+
+ echo "Event $event->event has been fired to GitHub $event->door door.\nRouting key is $routingKey.";
+ $broker = new AMQPBroker();
+ $broker
+ ->connect()
+ ->setExchangeTarget('github_events')
+ ->routeTo($routingKey)
+ ->sendMessage($message);
+ }
+
+ ///
+ /// Events listening
+ ///
+
+ /**
+ * Register the listeners for the subscriber.
+ *
+ * @param Illuminate\Events\Dispatcher $events
+ */
+ public function subscribe ($events) {
+ $class = 'Nasqueron\Notifications\Listeners\AMQPEventListener';
+ $events->listen(
+ 'Nasqueron\Notifications\Events\GitHubPayloadEvent',
+ "$class@onGitHubPayload"
+ );
+ }
+}
diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php
index 7babc9a..a8abc93 100644
--- a/app/Providers/EventServiceProvider.php
+++ b/app/Providers/EventServiceProvider.php
@@ -1,39 +1,40 @@
<?php
namespace Nasqueron\Notifications\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
];
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [
'Nasqueron\Notifications\Listeners\LastPayloadSaver',
+ 'Nasqueron\Notifications\Listeners\AMQPEventListener',
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
diff --git a/composer.json b/composer.json
index 43d1530..2763a80 100644
--- a/composer.json
+++ b/composer.json
@@ -1,58 +1,59 @@
{
"name": "nasqueron/notifications",
"description": "Nasqueron notifications center",
"keywords": [
"nasqueron",
"activemq",
"AMQP",
"notifications"
],
"license": "BSD-2-Clause",
"type": "project",
"require": {
"php": ">=5.6.0",
"laravel/framework": "5.1.*",
"keruald/github": ">=0.2.0",
- "videlalvaro/php-amqplib": "2.5.*"
+ "keruald/broker": ">=0.1.0",
+ "netresearch/jsonmapper": "~0.1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~4.0",
"phpspec/phpspec": "~2.1"
},
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"Nasqueron\\Notifications\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"pre-update-cmd": [
"php artisan clear-compiled"
],
"post-update-cmd": [
"php artisan optimize"
],
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
}
}
diff --git a/config/services.php b/config/services.php
index 3b99b29..6d26e17 100644
--- a/config/services.php
+++ b/config/services.php
@@ -1,42 +1,48 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'mandrill' => [
'secret' => env('MANDRILL_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'stripe' => [
'model' => Nasqueron\Notifications\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
+ 'github' => [
+ 'analyzer' => [
+ 'configDir' => storage_path(env('GITHUB_ANALYZER_CONFIG_DIR', 'app/GitHubPayloadAnalyzer'))
+ ]
+ ],
+
'gate' => [
'credentials' => storage_path(env('CREDENTIALS')),
]
];

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 14, 03:03 (1 d, 22 h ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4258227
Default Alt Text
(14 KB)

Event Timeline