Page MenuHomeDevCentral

No OneTemporary

diff --git a/.arclint b/.arclint
index 31ca21a..3647dc9 100644
--- a/.arclint
+++ b/.arclint
@@ -1,42 +1,46 @@
{
"exclude": [
"(^vendor/)",
"(^tests/data/)"
],
"linters": {
"chmod": {
"type": "chmod"
},
"filename": {
"type": "filename"
},
"json": {
"type": "json",
"include": [
"(^\\.arcconfig$)",
"(^\\.arclint$)",
"(\\.json$)"
]
},
"merge-conflict": {
"type": "merge-conflict"
},
"php": {
"type": "php",
"include": "(\\.php$)"
},
"phpcs": {
"type": "phpcs",
"bin": "vendor/bin/phpcs",
- "phpcs.standard": "PSR1",
- "include": "(^app/.*\\.php$)"
+ "phpcs.standard": "phpcs.xml",
+ "include": [
+ "(app/.*\\.php$)",
+ "(config/.*\\.php$)",
+ "(tests/.*\\.php$)"
+ ]
},
"spelling": {
"type": "spelling"
},
"xml": {
"type": "xml",
"include": "(\\.xml$)"
}
}
}
diff --git a/app/Analyzers/BasePayloadAnalyzer.php b/app/Analyzers/BasePayloadAnalyzer.php
index bebd917..f531724 100644
--- a/app/Analyzers/BasePayloadAnalyzer.php
+++ b/app/Analyzers/BasePayloadAnalyzer.php
@@ -1,181 +1,180 @@
<?php
namespace Nasqueron\Notifications\Analyzers;
-use Config;
-use Storage;
-
use BadMethodCallException;
+use Illuminate\Support\Facades\Config;
+use Illuminate\Support\Facades\Storage;
abstract class BasePayloadAnalyzer {
///
/// Constants
///
/**
* The name of the service, used to get specific classes and config
*/
const SERVICE_NAME = "UnknownService";
///
/// Private members
///
/**
* The project name, used to load specific configuration and offer defaults
* @var string
*/
protected $project;
/**
* The request content, as a structured data
* @var \stdClass
*/
protected $payload;
/**
* The configuration for the payload analyzer
- * @var PayloadAnalyzerConfiguration;
+ * @var PayloadAnalyzerConfiguration
*/
protected $configuration;
///
/// Constructor
///
/**
* Creates a new JenkinsPayloadAnalyzer instance.
*
* @param string $project
* @param \stdClass $payload
*/
public function __construct(string $project, \stdClass $payload) {
$this->project = $project;
$this->payload = $payload;
$this->loadConfiguration();
}
///
/// Configuration
///
/**
* The default name of the configuration file
*/
const CONFIG_DEFAULT_FILE = 'default.json';
/**
* Gets the full path to the configuration file.
*
* @return string
*/
public function getConfigurationFileName () : string {
$dir = Config::get(
'services.'
. strtolower(static::SERVICE_NAME)
. '.analyzer.configDir'
);
$filename = $dir . '/' . $this->project . '.json';
- if (!Storage::has($filename)) {
+ if (!Storage::exists($filename)) {
return $dir . '/' . static::CONFIG_DEFAULT_FILE;
}
return $filename;
}
/**
* Gets full qualified class name for configuration.
*
* @return string
*/
private function getCandidateConfigurationClassName() : string {
return 'Nasqueron\Notifications\Analyzers\\' . static::SERVICE_NAME //ns
. "\\"
. static::SERVICE_NAME . 'PayloadAnalyzerConfiguration'; // class
}
/**
* Gets full qualified class name for configuration if existing,
* or PayloadAnalyzerConfiguration class if not.
*
* @return string The configuration class to use
*/
private function getConfigurationClassName () : string {
$class = $this->getCandidateConfigurationClassName();
if (class_exists($class)) {
return $class;
}
return PayloadAnalyzerConfiguration::class;
}
/**
* Loads configuration for the analyzer
*/
public function loadConfiguration () : void {
$fileName = $this->getConfigurationFileName();
$class = $this->getConfigurationClassName();
$mapper = new \JsonMapper();
$this->configuration = $mapper->map(
json_decode(Storage::get($fileName)),
new $class($this->project)
);
}
///
/// Properties
///
/**
* Gets the name of the item.
*
* @var string
*/
public function getItemName () : string {
throw new BadMethodCallException(<<<MSG
The getItemName method must be implemented in the analyzer class if used.
MSG
);
}
/**
* Determines if the event isn't related to a specific item,
* but to the general service.
*
* @return bool
*/
public function isAdministrativeEvent () : bool {
return false;
}
/**
* Gets the group for a specific payload.
*
* @return string The group, central part of the routing key
*/
public function getGroup () : string {
// Some events are organization-level only and can't be mapped
// to projects.
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.
$item = $this->getItemName();
foreach ($this->configuration->map as $mapping) {
if ($mapping->doesItemBelong($item)) {
return $mapping->group;
}
}
return $this->configuration->getDefaultGroup();
}
}
diff --git a/app/Analyzers/DockerHub/BuildFailureEvent.php b/app/Analyzers/DockerHub/BuildFailureEvent.php
index de63bf6..acd5c60 100644
--- a/app/Analyzers/DockerHub/BuildFailureEvent.php
+++ b/app/Analyzers/DockerHub/BuildFailureEvent.php
@@ -1,67 +1,67 @@
<?php
namespace Nasqueron\Notifications\Analyzers\DockerHub;
-use Mailgun;
+use Nasqueron\Notifications\Facades\Mailgun;
class BuildFailureEvent extends BaseEvent {
/**
* Initializes a new instance of the BuildFailureEvent object.
*
* @param \stdClass $payload The payload to analyze
*/
public function __construct ($payload) {
parent::__construct($payload);
$this->payload = $this->getMailGunPayload();
}
/**
* Gets a MailGun message.
*
* @return \stdClass
*/
private function getMailGunPayload () {
return Mailgun::fetchMessageFromPayload($this->payload);
}
/**
* @return string
*/
private function getMailBody () {
$bodyProperty = 'body-plain';
return $this->payload->$bodyProperty;
}
/**
* Extracts a regular expression from the mail body.
*
* @param $string Regular expression
* @return string
*/
private function extractFromBody ($regex) {
preg_match($regex, $this->getMailBody(), $matches);
return $matches[1];
}
/**
* Gets text from payload.
*
* @return string
*/
public function getText() {
$repo = $this->extractFromBody("@\"(.*?\/.*?)\"@");
return "Image build by Docker Hub registry failure for $repo";
}
/**
* Gets link from payload.
*
* @return string
*/
public function getLink() {
return $this->extractFromBody("@(https\:\/\/hub.docker.com\/r.*)@");
}
}
diff --git a/app/Analyzers/GitHub/Events/Event.php b/app/Analyzers/GitHub/Events/Event.php
index 044a111..33c7606 100644
--- a/app/Analyzers/GitHub/Events/Event.php
+++ b/app/Analyzers/GitHub/Events/Event.php
@@ -1,80 +1,88 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
class Event {
///
/// Properties
///
/**
* The payload
*
* @var \stdClass
*/
protected $payload;
///
/// Constructor
///
public function __construct ($payload) {
$this->payload = $payload;
}
///
/// Gets or initialize relevant class
///
/**
* Gets class name from the GitHub webhooks event name
*
* @param string $eventName The event name (e.g. commit_comment)
* @return string The event class name (e.g. CommitCommentEvent)
*/
- public static function getClass ($eventName) {
- return __NAMESPACE__ . '\\' . studly_case($eventName) . 'Event';
+ public static function getClass (string $eventName) {
+ return __NAMESPACE__ . '\\' . self::toCamelCase($eventName) . 'Event';
+ }
+
+ private static function toCamelCase (string $string) : string {
+ return str_replace(" ", "", ucwords(str_replace("_", " ", $string)));
}
/**
* Gets an instance of the event class, from the
*
* @param string $eventName The event name (e.g. commit_comment)
* @return Event
*/
- public static function forPayload ($eventName, $payload) {
+ public static function forPayload (string $eventName, $payload) {
$class = self::getClass($eventName);
if (!class_exists($class)) {
throw new \InvalidArgumentException(
"Class doesn't exist: $class (for $eventName)"
);
}
return new $class($payload);
}
///
/// Helper methods
///
/**
* Cuts a text
*
- * @param string $text The text to cut
- * @param int $strLen The amount of characters to allow [optional]
+ * @param string $text The text to cut
+ * @param int $strLen The amount of characters to allow [optional]
* @param string $symbol The symbol to append to a cut text [optional]
*/
- public static function cut ($text, $strLen = 114, $symbol = '…') {
+ public static function cut (
+ string $text,
+ int $strLen = 114,
+ string $symbol = '…'
+ ) {
$len = strlen($text);
if ($len <= $strLen) {
return $text;
}
if ($strLen < 1) {
return $symbol;
}
return substr($text, 0, $strLen - 1) . $symbol;
}
}
diff --git a/app/Analyzers/GitHub/Events/IssueCommentEvent.php b/app/Analyzers/GitHub/Events/IssueCommentEvent.php
index 40bb5ec..40f5556 100644
--- a/app/Analyzers/GitHub/Events/IssueCommentEvent.php
+++ b/app/Analyzers/GitHub/Events/IssueCommentEvent.php
@@ -1,65 +1,64 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
/**
* IssueCommentEvent payload analyzer
*
* @link https://developer.github.com/v3/activity/events/types/#issuecommentevent
*/
class IssueCommentEvent extends Event {
/**
* Determines if the action is valid.
*
* @param string $action The action to check
* @return bool true if the action is valid; otherwise, false
*/
- protected static function isValidAction ($action) {
+ protected static function isValidAction (string $action) {
$actions = ['created', 'edited', 'deleted'];
return in_array($action, $actions);
}
/**
* Gets description for the payload.
*
* @return string
*/
public function getDescription () : string {
$action = $this->payload->action;
if (!static::isValidAction($action)) {
return trans(
'GitHub.EventsDescriptions.IssueCommentEventUnknown',
['action' => $action]
);
}
$key = 'GitHub.EventsDescriptions.IssueCommentEventPerAction.';
$key .= $action;
$comment = $this->payload->comment;
$issue = $this->payload->issue;
return trans(
$key,
[
'author' => $comment->user->login,
'issueNumber' => $issue->number,
'issueTitle' => $issue->title,
'excerpt' => self::cut($comment->body),
]
);
}
/**
* Gets link for the payload.
*
* @return string
*/
public function getLink () : string {
return $this->payload->comment->html_url;
}
}
-
diff --git a/app/Analyzers/GitHub/Events/PullRequestEvent.php b/app/Analyzers/GitHub/Events/PullRequestEvent.php
index 8e94f0b..bbe0b1e 100644
--- a/app/Analyzers/GitHub/Events/PullRequestEvent.php
+++ b/app/Analyzers/GitHub/Events/PullRequestEvent.php
@@ -1,91 +1,91 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
/**
* PingEvent payload analyzer
*
* @link https://developer.github.com/v3/activity/events/types/#pullrequestevent
*/
class PullRequestEvent extends Event {
/**
* Determines if the action is valid.
*
* @param string $action The action to check
* @return bool true if the action is valid; otherwise, false
*/
- protected static function isValidAction ($action) {
+ protected static function isValidAction(string $action) {
$actions = [
'assigned', 'unassigned',
'labeled', 'unlabeled',
'opened', 'closed',
'edited', 'reopened',
];
return in_array($action, $actions);
}
/**
* Gets description for the payload.
*
* @return string
*/
public function getDescription () : string {
$action = $this->payload->action;
if (!static::isValidAction($action)) {
return trans(
'GitHub.EventsDescriptions.PullRequestEventUnknown',
['action' => $action]
);
}
$key = 'GitHub.EventsDescriptions.PullRequestEventPerAction.';
$key .= $action;
return trans($key, $this->getLocalisationParameters());
}
/**
* Gets the parameters to pass to the localisation message
*
* @return array
*/
private function getLocalisationParameters () {
$parameters = [
'author' => $this->payload->sender->login,
'number' => $this->payload->number,
'title' => $this->payload->pull_request->title,
];
switch ($this->payload->action) {
case 'assigned':
$parameters['assignee'] = $this->getLastAssignee();
break;
}
return $parameters;
}
/**
* @return string The last assignee username, or "" if there is no assignee.
*/
private function getLastAssignee() {
$assignees = $this->payload->pull_request->assignees;
if (count($assignees) === 0) {
return ""; // No assignee.
}
$assignee = array_pop($assignees);
return $assignee->login;
}
/**
* Gets link for the payload.
*
* @return string
*/
public function getLink () : string {
return $this->payload->pull_request->html_url;
}
}
diff --git a/app/Analyzers/GitHub/Events/PushEvent.php b/app/Analyzers/GitHub/Events/PushEvent.php
index 8ac69de..6d005bb 100644
--- a/app/Analyzers/GitHub/Events/PushEvent.php
+++ b/app/Analyzers/GitHub/Events/PushEvent.php
@@ -1,67 +1,67 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
/**
* PushEvent payload analyzer
*
* @link https://developer.github.com/v3/activity/events/types/#pushevent
*/
class PushEvent extends Event {
use WithCommit;
use WithRepoAndBranch;
/**
* Gets the description message key according the amount of commits
*
* @param int $count The count of commits
* @return string The l10n message key for description
*/
- private static function getDescriptionMessageKey ($count) {
+ private static function getDescriptionMessageKey (int $count) {
$key = 'GitHub.EventsDescriptions.PushEvent';
if ($count === 0) {
return $key . '.0';
}
return $key . '.n';
}
/**
* Gets description for the payload
*
* @return string
*/
public function getDescription () : string {
$n = count($this->payload->commits);
if ($n === 1) {
// If only one commit is pushed at the time,
// we want a description for this commit.
return $this->getHeadCommitDescription();
}
// Otherwise, we want a description for the push.
return trans(self::getDescriptionMessageKey($n), [
'user' => $this->payload->pusher->name,
'count' => $n,
'repoAndBranch' => $this->getWhere(),
]);
}
/**
* Gets link for the payload
*
* @return string
*/
public function getLink () : string {
$n = count($this->payload->commits);
if ($n === 1) {
return $this->payload->head_commit->url;
}
return $this->payload->compare;
}
}
diff --git a/app/Analyzers/GitHub/Events/WithRef.php b/app/Analyzers/GitHub/Events/WithRef.php
index 5407168..2454188 100644
--- a/app/Analyzers/GitHub/Events/WithRef.php
+++ b/app/Analyzers/GitHub/Events/WithRef.php
@@ -1,43 +1,43 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
/**
* References helper methods for events using ref and ref_type fields.
* (e.g. create and delete)
*
* @link https://developer.github.com/v3/activity/events/types/#createevent
* @link https://developer.github.com/v3/activity/events/types/#deleteevent
*/
trait WithRef {
/**
* Determines if the ref type is valid.
*
* The ref type 'repository' is deemed invalid, as we shouldn't receive it.
*
* @param string $type The ref type to check
* @return bool true if the ref type id valid; otherwise, false
*/
- protected static function isValidRefType ($type) {
+ protected static function isValidRefType (string $type) {
$types = ['branch', 'tag'];
return in_array($type, $types);
}
/**
* Gets link ref segment for the payload
*
* @param string $type The reference type
* @return string the part of the URL for this reference type (e.g. /tree/)
*/
- protected function getLinkRefSegment ($type) {
+ protected function getLinkRefSegment (string $type) {
$segments = $this->getLinkRefSegments();
if (!array_key_exists($type, $segments)) {
throw new \InvalidArgumentException;
}
return $segments[$type];
}
}
diff --git a/app/Analyzers/GitHub/Events/WithRepoAndBranch.php b/app/Analyzers/GitHub/Events/WithRepoAndBranch.php
index 09537bd..9d0608e 100644
--- a/app/Analyzers/GitHub/Events/WithRepoAndBranch.php
+++ b/app/Analyzers/GitHub/Events/WithRepoAndBranch.php
@@ -1,45 +1,45 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub\Events;
/**
* Helper methods for events with a need to specify the repo and the branch
* (e.g. push)
*
* @link https://developer.github.com/v3/activity/events/types/#pushevent
*/
trait WithRepoAndBranch {
/**
* Gets repository and branch information
*/
public function getWhere () : string {
$repo = $this->payload->repository->name;
$branch = $this->payload->ref;
return static::getRepositoryAndBranch($repo, $branch);
}
public static function getRepositoryAndBranch (
$repo = "",
$branch = ""
) : string {
if ($repo === "") {
return "";
}
- if (starts_with($branch, "refs/heads/")) {
+ if (str_starts_with($branch, "refs/heads/")) {
$branch = substr($branch, 11);
}
if ($branch === "" || $branch === "master") {
return $repo;
}
return trans('GitHub.RepoAndBranch', [
'repo' => $repo,
'branch' => $branch,
]);
}
}
diff --git a/app/Analyzers/GitHub/GitHubPayloadAnalyzer.php b/app/Analyzers/GitHub/GitHubPayloadAnalyzer.php
index 3148f6d..30ef854 100644
--- a/app/Analyzers/GitHub/GitHubPayloadAnalyzer.php
+++ b/app/Analyzers/GitHub/GitHubPayloadAnalyzer.php
@@ -1,116 +1,116 @@
<?php
namespace Nasqueron\Notifications\Analyzers\GitHub;
use Nasqueron\Notifications\Analyzers\BasePayloadAnalyzer;
use Nasqueron\Notifications\Analyzers\GitHub\Events\Event;
use Nasqueron\Notifications\Analyzers\GitHub\Events\UnknownEvent;
class GitHubPayloadAnalyzer extends BasePayloadAnalyzer {
/**
* The name of the service, used to get specific classes and config
*/
const SERVICE_NAME = "GitHub";
///
/// Private members
///
/**
* The GitHub event triggering this request
* @var string
*/
private $event;
/**
* The payload analyzer event
*
- * @var \Nasqueron\Notifications\Analyzers\GitHub\Events\Event;
+ * @var \Nasqueron\Notifications\Analyzers\GitHub\Events\Event
*/
private $analyzerEvent;
///
/// Constructor
///
/**
* Creates a new GitHubPayloadAnalyzer instance.
*
* @param string $project
* @param string $event
* @param \stdClass $payload
*/
public function __construct(
string $project,
string $event,
\stdClass $payload
) {
parent::__construct($project, $payload);
$this->event = $event;
try {
$this->analyzerEvent = Event::forPayload($event, $payload);
} catch (\InvalidArgumentException $ex) {
$this->analyzerEvent = new UnknownEvent($event);
}
}
///
/// Properties
///
/**
* Gets the name of the item, ie here of the name of the repository.
*
* @var string
*/
public function getItemName () : string {
if ($this->isAdministrativeEvent()) {
return '';
}
return $this->payload->repository->name;
}
///
/// Qualification of the payload
///
/**
* @return bool
*/
public function isAdministrativeEvent () : bool {
$administrativeEvents = [
'membership', // Member added to team
'ping', // Special ping pong event, fired on new hook
'repository', // Repository created
];
return in_array($this->event, $administrativeEvents);
}
///
/// Description of the payload
///
/**
* Gets a short textual description of the event.
*
* @return string
*/
public function getDescription () : string {
return $this->analyzerEvent->getDescription();
}
/**
* Gets a link to view the event on GitHub.
*
* @return string The most relevant URL
*/
public function getLink () : string {
return $this->analyzerEvent->getLink();
}
}
diff --git a/app/Analyzers/ItemGroupMapping.php b/app/Analyzers/ItemGroupMapping.php
index ad056bf..4037b0d 100644
--- a/app/Analyzers/ItemGroupMapping.php
+++ b/app/Analyzers/ItemGroupMapping.php
@@ -1,63 +1,65 @@
<?php
namespace Nasqueron\Notifications\Analyzers;
+use Illuminate\Support\Str;
+
/**
* Map items (repositories, projects, items, etc.) names to groups
*/
class ItemGroupMapping {
///
/// Properties
///
/**
* The group the mapped items belong to
*
* @var string
*/
public $group;
/**
* An array of the items to map, each item a string with the name of the
* repository, project or item used for mapping.
* The wildcard '*' is allowed to specify several items.
*
* @var array
*/
public $items = [];
///
/// Helper methods
///
/**
* Determines if the specified item matches a pattern.
*
* @param string $pattern The pattern, with * allowed as wildcard character
* @param string $item The item name to compare with the pattern
* @return bool
*/
public static function doesItemMatch (
string $pattern,
string $item
) : bool {
- return str_is($pattern, $item);
+ return Str::is($pattern, $item);
}
/**
* Determines if the specified item belong to this mapping
*
* @return bool
*/
public function doesItemBelong (string $actualItem) : bool {
foreach ($this->items as $candidateItem) {
if (static::doesItemMatch($candidateItem, $actualItem)) {
return true;
}
}
return false;
}
}
diff --git a/app/Analyzers/Jenkins/JenkinsPayloadAnalyzer.php b/app/Analyzers/Jenkins/JenkinsPayloadAnalyzer.php
index 9c868a9..b004cee 100644
--- a/app/Analyzers/Jenkins/JenkinsPayloadAnalyzer.php
+++ b/app/Analyzers/Jenkins/JenkinsPayloadAnalyzer.php
@@ -1,82 +1,82 @@
<?php
namespace Nasqueron\Notifications\Analyzers\Jenkins;
use Nasqueron\Notifications\Analyzers\BasePayloadAnalyzer;
class JenkinsPayloadAnalyzer extends BasePayloadAnalyzer {
/**
* The name of the service, used to get specific classes and config
*/
const SERVICE_NAME = "Jenkins";
///
/// Payload custom properties
///
/**
* Gets the name of the item, ie here of the job.
*
* @var string
*/
public function getItemName () : string {
return $this->payload->name;
}
///
/// Notify only on failure helper methods
///
/**
* Tries to get build status.
*
- * @param out string $status
+ * @param out string &$status
* @return bool indicates if the build status is defined in the payload
*/
private function tryGetBuildStatus (string &$status) : bool {
if (!isset($this->payload->build->status)) {
return false;
}
$status = $this->payload->build->status;
return true;
}
/**
* @return bool
*/
public function shouldNotifyOnlyOnFailure () : bool {
return in_array(
$this->getItemName(),
$this->configuration->notifyOnlyOnFailure
);
}
/**
* Determines if the build status is a failure.
*
* @return bool
*/
public function isFailure () : bool {
$status = "";
if (!$this->tryGetBuildStatus($status)) {
return false;
}
return $status === "FAILURE"
|| $status === "ABORTED"
|| $status === "UNSTABLE";
}
/**
* Indicates if we should handle this payload to trigger a notification.
*
* @return bool if false, this payload is to be ignored for notifications
*/
public function shouldNotify () : bool {
return $this->isFailure() || !$this->shouldNotifyOnlyOnFailure();
}
}
diff --git a/app/Config/Features.php b/app/Config/Features.php
index 09c0a70..8c463c1 100644
--- a/app/Config/Features.php
+++ b/app/Config/Features.php
@@ -1,92 +1,92 @@
<?php
namespace Nasqueron\Notifications\Config;
-use Config;
+use Illuminate\Support\Facades\Config;
/**
* The features class offers a sugar syntax to check if a feature is enabled
* in the Config repository, at app.features.
*
* Features could be added to config/app.php to the features array.
*/
class Features {
///
/// Feature information
///
/**
* Gets the configuration key for the specified feature name.
*
* @param string $feature The feature to get the config key
* @return string The config key
*/
private static function getFeatureConfigKey (string $feature) : string {
return 'app.features.' . $feature;
}
/**
* Determines if the specified feature is enabled.
*
* @param string $feature The feature to check in the config
* @return bool
*/
public static function isEnabled (string $feature) : bool {
$key = self::getFeatureConfigKey($feature);
return Config::has($key) && (bool)Config::get($key);
}
/**
* Enables a feature in our current configuration instance.
*
* @param string $feature The feature
*/
public static function enable (string $feature) : void {
$key = self::getFeatureConfigKey($feature);
Config::set($key, true);
}
/**
* Disables a feature in our current configuration instance.
*
* @param string $feature The feature
*/
public static function disable (string $feature) : void {
$key = self::getFeatureConfigKey($feature);
Config::set($key, false);
}
///
/// Features lists
///
/**
* Gets all the features, with the toggle status.
*/
public static function getAll () : array {
return Config::get('app.features');
}
/**
* Lists all the features.
*
* @return string[] a list of all features
*/
public static function getAvailable () : array {
$features = self::getAll();
return array_keys($features);
}
/**
* Lists the enabled features.
*
* @return string[] a list of enabled features
*/
public static function getEnabled () : array {
$features = self::getAll();
$enabledFeatures = array_filter($features);
return array_keys($enabledFeatures);
}
}
diff --git a/app/Config/Reporting/ConfigReport.php b/app/Config/Reporting/ConfigReport.php
index 1a093d3..01b04a3 100644
--- a/app/Config/Reporting/ConfigReport.php
+++ b/app/Config/Reporting/ConfigReport.php
@@ -1,84 +1,84 @@
<?php
namespace Nasqueron\Notifications\Config\Reporting;
use Nasqueron\Notifications\Config\Features;
-use Config;
-use Services;
+use Nasqueron\Notifications\Facades\Services;
+use Illuminate\Support\Facades\Config;
class ConfigReport {
///
/// Public properties
///
/**
* @var string[]
*/
public $gates;
/**
* @var FeatureReportEntry[]
*/
public $features;
/**
* @var ServiceReportEntry[]
*/
public $services;
///
/// Public constructor
///
public function __construct () {
$this->gates = $this->queryGates();
$this->features = $this->queryFeatures();
$this->services = $this->queryServices();
}
///
/// Report builder
///
/**
* Queries information about the features enabled from the configuration.
*
* @return string[]
*/
protected function queryGates () : array {
return Config::get('gate.controllers');
}
/**
* Queries information about the features enabled from the configuration.
*
* @return FeatureReportEntry[]
*/
protected function queryFeatures () : array {
$features = [];
foreach (Features::getAll() as $feature => $enabled) {
$features[] = new FeatureReportEntry($feature, $enabled);
}
return $features;
}
/**
* Queries information about services described in credentials.json.
*
* @return ServiceReportEntry[]
*/
protected function queryServices () : array {
$services = [];
foreach (Services::get() as $service) {
$services[] = new ServiceReportEntry($service);
}
return $services;
}
}
diff --git a/app/Config/Reporting/ServiceReportEntry.php b/app/Config/Reporting/ServiceReportEntry.php
index b8d7517..1266c5f 100644
--- a/app/Config/Reporting/ServiceReportEntry.php
+++ b/app/Config/Reporting/ServiceReportEntry.php
@@ -1,129 +1,129 @@
<?php
namespace Nasqueron\Notifications\Config\Reporting;
use Nasqueron\Notifications\Config\Services\Service;
-use ProjectsMap;
+use Nasqueron\Notifications\Facades\ProjectsMap;
final class ServiceReportEntry extends BaseReportEntry {
///
/// Private members
///
/**
* @var Service
*/
private $service;
///
/// Public properties
///
/**
* @var string
*/
public $gate;
/**
* @var string
*/
public $door;
/**
* @var string
*/
public $instance;
/**
* @var string
*/
public $status = "";
///
/// Constructor
///
public function __construct (Service $service) {
$this->service = $service;
$this->query();
}
///
/// Report builder
///
/**
* Queries the service to fill public properties.
*/
protected function query () : void {
// Direct properties
$this->gate = $this->service->gate;
$this->door = $this->service->door;
$this->instance = (string)$this->service->instance;
// Properties to query with business logic
$this->status = $this->getServiceStatus();
}
/**
* @return string An issue to fix, or an empty string if all looks good.
*/
protected function getServiceStatus () : string {
if ($this->isPhabricatorServiceWithNotCachedProjectsMap()) {
return "Projects map not cached.";
}
return "";
}
/**
* Determines if the service matches the following issue to report:
* - service is Phabricator
* - instance doesn't have the projects' name/PHID map in cache
*
* @return bool
*/
protected function isPhabricatorServiceWithNotCachedProjectsMap () : bool {
if ($this->service->gate !== 'Phabricator') {
return false;
}
$map = ProjectsMap::fetch($this->service->door);
return !$map->isCached();
}
///
/// Format
///
/**
* Gets the entry as an array. Formats empty string.
*
* @return string[]
*/
public function toArray () : array {
return [
$this->gate,
$this->door,
$this->instance,
$this->status,
];
}
/**
* Gets the entry as an array. Formats empty string.
*
* @return string[]
*/
public function toFancyArray () : array {
return [
$this->gate,
$this->door,
self::fancyString($this->instance, 'ø'),
self::fancyString($this->status, '✓'),
];
}
}
diff --git a/app/Config/Services/Services.php b/app/Config/Services/Services.php
index b59b6a7..1e06852 100644
--- a/app/Config/Services/Services.php
+++ b/app/Config/Services/Services.php
@@ -1,107 +1,107 @@
<?php
namespace Nasqueron\Notifications\Config\Services;
-use Storage;
+use Illuminate\Support\Facades\Storage;
class Services {
///
/// Properties
///
/**
* @var Service[]
*/
public $services = [];
///
/// Constructors
///
/**
* @param string $file The JSON file to deserialize
* @return Services The deserialized instance
*/
public static function loadFromJson (string $file) : Services {
$data = json_decode(Storage::get($file));
$mapper = new \JsonMapper();
return $mapper->map($data, new self());
}
///
/// Methods to get a list of services
///
/**
* Gets the services found in credentials.json configuration file.
*
* @return Service[]
*/
public function get () {
return $this->services;
}
/**
* Gets all the services for a specific gate.
*
* @param string $gate The gate (e.g. GitHub)
* @return Service[]
*/
public function getForGate (string $gate) : array {
$services = [];
foreach ($this->services as $service) {
if ($service->gate === $gate) {
$services[] = $service;
}
}
return $services;
}
///
/// Methods to find a service matching criteria
///
/**
* Gets the service for a specific gate and door
*
* @param string $gate The gate (e.g. GitHub)
* @param string $door The door (e.g. Nasqueron)
* @return Service|null The service information is found; otherwise, null.
*/
public function findServiceByDoor (string $gate, string $door) : ?Service {
foreach ($this->services as $service) {
if ($service->gate === $gate && $service->door === $door) {
return $service;
}
}
return null;
}
/**
* Finds a service for a specific gate, property and value
*
* @param string $gate The gate (e.g. Phabricator)
* @param string $property The property to check (e.g. instance)
* @param mixed $value The property value to find
* (e.g. 'http://devcentral.nasqueron.org')
* @return Service|null The service information is found; otherwise, null.
*/
public function findServiceByProperty (
string $gate,
string $property,
$value
) : ?Service {
foreach ($this->services as $service) {
if ($service->gate === $gate && $service->$property === $value) {
return $service;
}
}
return null;
}
}
diff --git a/app/Console/Commands/ConfigValidate.php b/app/Console/Commands/ConfigValidate.php
index 7199951..9d7e667 100644
--- a/app/Console/Commands/ConfigValidate.php
+++ b/app/Console/Commands/ConfigValidate.php
@@ -1,54 +1,53 @@
<?php
namespace Nasqueron\Notifications\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\FilesystemAdapter;
-
-use App;
+use Illuminate\Support\Facades\App;
class ConfigValidate extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'config:validate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Validates JSON configuration files';
private function getFS () : FilesystemAdapter {
return App::make('filesystem')->disk('local');
}
private function getConfigFiles () : array {
return array_filter(
$this->getFS()->allFiles(),
// Filters *.json
function ($file) : bool {
return substr($file, -5) === ".json";
}
);
}
/**
* Executes the console command.
*/
public function handle() : void {
$files = $this->getConfigFiles();
foreach ($files as $file) {
$content = $this->getFS()->get($file);
if (json_decode($content) === null) {
$this->line("$file — " . json_last_error_msg());
}
}
}
}
diff --git a/app/Console/Commands/PhabricatorProjectsMap.php b/app/Console/Commands/PhabricatorProjectsMap.php
index 364873b..62abf2d 100644
--- a/app/Console/Commands/PhabricatorProjectsMap.php
+++ b/app/Console/Commands/PhabricatorProjectsMap.php
@@ -1,41 +1,41 @@
<?php
namespace Nasqueron\Notifications\Console\Commands;
use Illuminate\Console\Command;
-use ProjectsMap;
-use Services;
+use Nasqueron\Notifications\Facades\ProjectsMap;
+use Nasqueron\Notifications\Facades\Services;
class PhabricatorProjectsMap extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'phabricator:projectsmap';
/**
* The console command description.
*
* @var string
*/
protected $description = <<<'TXT'
Regenerate the projects map for each Phabricator instances
TXT;
/**
* Executes the console command.
*/
public function handle() : void {
foreach (Services::getForGate('Phabricator') as $service) {
$this->info("Querying projects map for " . $service->instance);
$map = ProjectsMap::fetch($service->door);
$map->saveToCache();
$this->table(
['PHID', 'Project name'],
$map->toArray()
);
}
}
}
diff --git a/app/Contracts/APIClient.php b/app/Contracts/APIClient.php
index 2f0ab7e..7bfe9d1 100644
--- a/app/Contracts/APIClient.php
+++ b/app/Contracts/APIClient.php
@@ -1,24 +1,24 @@
<?php
namespace Nasqueron\Notifications\Contracts;
interface APIClient {
/**
* Sets API end point
*
* @param string $url The API end point URL
* @return void
*/
- public function setEndPoint ($url);
+ public function setEndPoint (string $url);
/**
* Calls an API method
*
* @param string $method The method to call
* @param array $arguments The arguments to use
* @return mixed The API result
*/
- public function call ($method, $arguments = []);
+ public function call (string $method, array $arguments = []);
}
diff --git a/app/Contracts/APIFactory.php b/app/Contracts/APIFactory.php
index 064f09a..797a695 100644
--- a/app/Contracts/APIFactory.php
+++ b/app/Contracts/APIFactory.php
@@ -1,15 +1,15 @@
<?php
namespace Nasqueron\Notifications\Contracts;
interface APIFactory {
/**
* Gets an instance of the API client class
*
* @param string $endPoint The API end point
* @return APIClient
*/
- public function get ($endPoint);
+ public function get (string $endPoint);
}
diff --git a/app/Events/DockerHubPayloadEvent.php b/app/Events/DockerHubPayloadEvent.php
index f82d623..e5a2581 100644
--- a/app/Events/DockerHubPayloadEvent.php
+++ b/app/Events/DockerHubPayloadEvent.php
@@ -1,53 +1,52 @@
<?php
namespace Nasqueron\Notifications\Events;
-use Nasqueron\Notifications\Events\Event;
use Illuminate\Queue\SerializesModels;
class DockerHubPayloadEvent extends Event {
use SerializesModels;
/**
* The gate door which receives the request
* @var string
*/
public $door;
/**
* The event triggering this request
* @var string
*/
public $event;
/**
* The request content, as a structured data
* @var \stdClass
*/
public $payload;
/**
* Gets event according the kind of payload we receive.
*
* @return string
*/
public function getEvent () : string {
if (isset($this->payload->repository->repo_url)) {
return "push";
}
return "buildFailure";
}
/**
* Creates a new event instance.
*
* @param string $door
* @param \stdClass $payload
*/
public function __construct($door, $payload) {
$this->door = $door;
$this->payload = $payload;
$this->event = $this->getEvent();
}
}
diff --git a/app/Events/GitHubPayloadEvent.php b/app/Events/GitHubPayloadEvent.php
index ef09f07..f45faac 100644
--- a/app/Events/GitHubPayloadEvent.php
+++ b/app/Events/GitHubPayloadEvent.php
@@ -1,41 +1,40 @@
<?php
namespace Nasqueron\Notifications\Events;
-use Nasqueron\Notifications\Events\Event;
use Illuminate\Queue\SerializesModels;
class GitHubPayloadEvent extends Event {
use SerializesModels;
/**
* The gate door which receives the request
* @var string
*/
public $door;
/**
* The GitHub event triggering this request
* @var string
*/
public $event;
/**
* The request content, as a structured data
* @var \stdClass
*/
public $payload;
/**
* Creates a new event instance.
*
* @param string $door
* @param string $event
* @param \stdClass $payload
*/
public function __construct($door, $event, $payload) {
$this->door = $door;
$this->event = $event;
$this->payload = $payload;
}
}
diff --git a/app/Events/JenkinsPayloadEvent.php b/app/Events/JenkinsPayloadEvent.php
index fe287a8..01cae98 100644
--- a/app/Events/JenkinsPayloadEvent.php
+++ b/app/Events/JenkinsPayloadEvent.php
@@ -1,33 +1,32 @@
<?php
namespace Nasqueron\Notifications\Events;
-use Nasqueron\Notifications\Events\Event;
use Illuminate\Queue\SerializesModels;
class JenkinsPayloadEvent extends Event {
use SerializesModels;
/**
* The gate door which receives the request
* @var string
*/
public $door;
/**
* The request content, as a structured data
* @var \stdClass
*/
public $payload;
/**
* Creates a new event instance.
*
* @param string $door
* @param \stdClass $payload
*/
public function __construct($door, $payload) {
$this->door = $door;
$this->payload = $payload;
}
}
diff --git a/app/Events/NotificationEvent.php b/app/Events/NotificationEvent.php
index 7f476bb..2e25dab 100644
--- a/app/Events/NotificationEvent.php
+++ b/app/Events/NotificationEvent.php
@@ -1,26 +1,25 @@
<?php
namespace Nasqueron\Notifications\Events;
-use Nasqueron\Notifications\Events\Event;
use Nasqueron\Notifications\Notifications\Notification;
use Illuminate\Queue\SerializesModels;
class NotificationEvent extends Event {
use SerializesModels;
/**
* @var Notification
*/
public $notification;
/**
* Creates a new event instance.
*
* @param Notification $notification the notification
*/
public function __construct(Notification $notification) {
$this->notification = $notification;
}
}
diff --git a/app/Events/PhabricatorPayloadEvent.php b/app/Events/PhabricatorPayloadEvent.php
index 6d06743..c08e4ec 100644
--- a/app/Events/PhabricatorPayloadEvent.php
+++ b/app/Events/PhabricatorPayloadEvent.php
@@ -1,54 +1,54 @@
<?php
namespace Nasqueron\Notifications\Events;
-use Nasqueron\Notifications\Events\Event;
use Nasqueron\Notifications\Phabricator\PhabricatorStory;
+
use Illuminate\Queue\SerializesModels;
class PhabricatorPayloadEvent extends Event {
use SerializesModels;
/**
* The gate door which receives the request
* @var string
*/
public $door;
/**
* The raw payload
* @var iterable
*/
public $payload;
/**
* The story sent by the request
* @var PhabricatorStory
*/
public $story;
/**
* Gets story from the request
*
* @return PhabricatorStory
*/
protected function getStory () {
return PhabricatorStory::loadFromIterable(
$this->door,
$this->payload
);
}
/**
* Creates a new event instance.
*
* @param string $door
* @param iterable $payload
*/
public function __construct(string $door, iterable $payload) {
$this->door = $door;
$this->payload = $payload;
$this->story = $this->getStory();
}
}
diff --git a/app/Events/ReportEvent.php b/app/Events/ReportEvent.php
index e8086e1..655a542 100644
--- a/app/Events/ReportEvent.php
+++ b/app/Events/ReportEvent.php
@@ -1,25 +1,25 @@
<?php
namespace Nasqueron\Notifications\Events;
use Nasqueron\Notifications\Actions\Action;
-use Nasqueron\Notifications\Events\Event;
+
use Illuminate\Queue\SerializesModels;
class ReportEvent extends Event {
use SerializesModels;
/**
* @var Action
*/
public $action;
/**
* Creates a new event instance.
*
* @param Action $action the action to report
*/
public function __construct(Action $action) {
$this->action = $action;
}
}
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 918655a..2d031b9 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -1,74 +1,75 @@
<?php
namespace Nasqueron\Notifications\Exceptions;
-use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+use Nasqueron\Notifications\Facades\Raven;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
-use Illuminate\Foundation\Validation\ValidationException;
+use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+use Illuminate\Validation\ValidationException;
use Illuminate\Session\TokenMismatchException;
+use Illuminate\Support\Facades\Config;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
-use Config;
-use Raven;
-
use Exception;
class Handler extends ExceptionHandler {
/**
* A list of the exception types that should not be reported.
*
* @var string[]
*/
protected $dontReport = [
AuthorizationException::class,
CommandNotFoundException::class,
HttpException::class,
ModelNotFoundException::class,
TokenMismatchException::class,
ValidationException::class,
];
/**
* Reports or logs an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
- * @param \Exception $e
+ * @param \Exception|\Throwable $e
+ *
+ * @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
- public function report(Exception $e) : void {
+ public function report(Exception|\Throwable $e) : void {
if (!$this->shouldReport($e)) {
return;
}
if ($this->shouldReportToSentry()) {
$this->reportToSentry($e);
}
$log = $this->container->make(LoggerInterface::class);
$log->error((string)$e);
}
/**
* Determines if the error handler should report to Sentry
*
* @return bool
*/
protected function shouldReportToSentry () : bool {
return Raven::isConfigured() && Config::get('app.env') !== 'testing';
}
/**
* Reports the exception to Sentry
*
* @param Exception $e The exception to report
*/
protected function reportToSentry (Exception $e) : void {
Raven::captureException($e);
}
}
diff --git a/app/Facades/Raven.php b/app/Facades/Raven.php
index b1745f2..8473298 100644
--- a/app/Facades/Raven.php
+++ b/app/Facades/Raven.php
@@ -1,29 +1,28 @@
<?php
namespace Nasqueron\Notifications\Facades;
+use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Facade;
-use Config;
-
/**
* @see \Raven_Client
*/
class Raven extends Facade {
/**
* Gets the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() : string {
return 'raven';
}
/**
* Determines if a Sentry DSN is provided in the configuration
*/
public static function isConfigured () : bool {
return Config::get('services.sentry.dsn') !== null;
}
}
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 547f57b..b7881b7 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -1,13 +1,15 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
-use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
-use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use Illuminate\Routing\Controller as BaseController;
abstract class Controller extends BaseController {
- use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+ use AuthorizesRequests;
+ use DispatchesJobs;
+ use ValidatesRequests;
}
diff --git a/app/Http/Controllers/Gate/DockerHubGateController.php b/app/Http/Controllers/Gate/DockerHubGateController.php
index 24ebbde..3085a6d 100644
--- a/app/Http/Controllers/Gate/DockerHubGateController.php
+++ b/app/Http/Controllers/Gate/DockerHubGateController.php
@@ -1,83 +1,82 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Events\DockerHubPayloadEvent;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\Response;
-use Event;
-use Request;
-
class DockerHubGateController extends GateController {
///
/// Private members
///
/**
* The request content, as a structured data
*
* @var \stdClass
*/
private $payload;
/**
* The request content
*
* @var string
*/
private $rawRequestContent;
///
/// Request processing
///
/**
* Handles POST requests
*
* @param string $door The door, matching the project for this payload
* @return \Symfony\Component\HttpFoundation\Response
*/
public function onPost (string $door) : Response {
// Parses the request and check if it's legit
$this->door = $door;
$this->extractPayload();
// Process the request
$this->logRequest();
$this->onPayload();
// Output
return parent::renderReport();
}
/**
* Extracts payload from the request
*/
protected function extractPayload () : void {
$request = Request::instance();
$this->rawRequestContent = $request->getContent();
$this->payload = json_decode($this->rawRequestContent);
}
public function getServiceName () : string {
return "DockerHub";
}
///
/// Payload processing
///
protected function onPayload () : void {
$this->initializeReport();
- Event::fire(new DockerHubPayloadEvent(
+ Event::dispatch(new DockerHubPayloadEvent(
$this->door,
$this->payload
));
}
}
diff --git a/app/Http/Controllers/Gate/GateController.php b/app/Http/Controllers/Gate/GateController.php
index 36cdf38..a3325ae 100644
--- a/app/Http/Controllers/Gate/GateController.php
+++ b/app/Http/Controllers/Gate/GateController.php
@@ -1,121 +1,120 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Config\Features;
use Nasqueron\Notifications\Config\Services\Service;
+use Nasqueron\Notifications\Facades\Services;
+use Nasqueron\Notifications\Facades\Report;
use Nasqueron\Notifications\Http\Controllers\Controller;
-use Symfony\Component\HttpFoundation\Response as BaseResponse;
+use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Response;
use Illuminate\View\View;
-
-use App;
-use Log;
-use Report;
-use Response;
-use Services;
+use Symfony\Component\HttpFoundation\Response as BaseResponse;
/**
* Represents a controller handling an entry-point for API payloads
*/
class GateController extends Controller {
///
/// Private members
///
/**
* @var string
*/
protected $door;
///
/// Requests
///
/**
* Handles GET requests
*/
public function onGet () : View {
// Virtually all the push APIs will send they payloads
// using a POST request, so we can provide a sensible
// default GET error message.
return view('gate/ispostonly');
}
/**
* Logs the request
*/
protected function logRequest (array $extraContextualData = []) : void {
Log::info('[Gate] New payload.', [
'service' => $this->getServiceName(),
'door' => $this->door,
] + $extraContextualData);
}
///
/// Reports
///
/**
* Initializes the report and registers it
*/
protected function initializeReport () : void {
if (Features::isEnabled('ActionsReport')) {
Report::attachToGate($this->getServiceName(), $this->door);
}
}
/**
* Renders the report
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function renderReport () : BaseResponse {
if (!Features::isEnabled('ActionsReport')) {
return response("");
}
$report = App::make('report');
$statusCode = $report->containsError() ? 503 : 200;
return Response::json($report)
->setStatusCode($statusCode);
}
///
/// Credentials
///
/**
* Gets service credentials for this gate and door
*/
public function getService () : ?Service {
return Services::findServiceByDoor(
$this->getServiceName(),
$this->door
);
}
/**
* Checks if a registered service exists for this service and door.
*/
protected function doesServiceExist () : bool {
return $this->getService() !== null;
}
/**
* Gets secret for this service and door.
*
* @return string the secret, or if unknown, an empty string
*/
protected function getSecret () : string {
$service= $this->getService();
if ($service !== null) {
return $service->secret;
}
return "";
}
}
diff --git a/app/Http/Controllers/Gate/GitHubGateController.php b/app/Http/Controllers/Gate/GitHubGateController.php
index 090fcc4..3a8f0f9 100644
--- a/app/Http/Controllers/Gate/GitHubGateController.php
+++ b/app/Http/Controllers/Gate/GitHubGateController.php
@@ -1,189 +1,189 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Events\GitHubPayloadEvent;
use Keruald\GitHub\XHubSignature;
-use Symfony\Component\HttpFoundation\Response;
-use Event;
-use Request;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Request;
+use Symfony\Component\HttpFoundation\Response;
class GitHubGateController extends GateController {
///
/// Private members
///
/**
* The request signature, allowing to determine if the payload is legit
*
* @var string
*/
private $signature;
/**
* The GitHub event triggering this request
*
* @var string
*/
private $event;
/**
* The request delivery GUID
*
* @var string
*/
private $delivery;
/**
* The request content, as a structured data
*
* @var \stdClass
*/
private $payload;
/**
* The request content
*
* @var string
*/
private $rawRequestContent;
///
/// Request processing
///
/**
* Handles POST requests
*
* @param string $door The door, matching the project for this payload
* @return \Symfony\Component\HttpFoundation\Response
*/
public function onPost (string $door) : Response {
// Parses the request and check if it's legit
$this->door = $door;
$this->extractHeaders();
$this->extractPayload();
if (!$this->isLegitRequest()) {
abort(403, 'Unauthorized action.');
}
if (!$this->isValidRequest()) {
abort(400, 'Bad request.');
}
// Process the request
$this->logGateRequest();
$this->onPayload();
// Output
return parent::renderReport();
}
/**
* Extracts headers from the request
*/
protected function extractHeaders () : void {
$this->signature = $this->getSignature();
$this->event = Request::header('X-Github-Event');
$this->delivery = Request::header('X-Github-Delivery');
}
/**
* Gets the signature from an X-Hub-Signature header
*
* @return string The signature part of the header
*/
private function getSignature () : string {
$headerSignature = Request::header('X-Hub-Signature');
return XHubSignature::parseSignature($headerSignature);
}
/**
* Extracts payload from the request
*/
protected function extractPayload () : void {
$request = Request::instance();
$this->rawRequestContent = $request->getContent();
$this->payload = json_decode($this->rawRequestContent);
}
/**
* Determines if the request is valid, ie contains the mandatory headers
* and a payload.
*
* @return bool true if the request looks valid; otherwise, false.
*/
protected function isValidRequest () : bool {
if (empty($this->event)) {
return false;
}
if (empty($this->delivery)) {
return false;
}
if (empty($this->payload) || !is_object($this->payload)) {
return false;
}
return true;
}
/**
* Determines if the request is legit.
*
* @return bool true if the request looks legit; otherwise, false.
*/
protected function isLegitRequest () : bool {
$secret = $this->getSecret();
// If the secret is not defined, request legitimation is bypassed
if (empty($secret)) {
return true;
}
// If the secret is defined, but signature is missing from the
// request, we don't need to perform any other validation.
if (empty($this->signature)) {
return false;
}
return XHubSignature::validatePayload(
$secret,
$this->rawRequestContent,
$this->signature
);
}
/**
* Logs the request
*/
protected function logGateRequest () {
$this->logRequest([
'delivery' => $this->delivery,
'event' => $this->event,
]);
}
public function getServiceName () : string {
return "GitHub";
}
///
/// Payload processing
///
protected function onPayload () {
$this->initializeReport();
- Event::fire(new GitHubPayloadEvent(
+ Event::dispatch(new GitHubPayloadEvent(
$this->door,
$this->event,
$this->payload
));
}
}
diff --git a/app/Http/Controllers/Gate/JenkinsGateController.php b/app/Http/Controllers/Gate/JenkinsGateController.php
index 3364b92..90a4199 100644
--- a/app/Http/Controllers/Gate/JenkinsGateController.php
+++ b/app/Http/Controllers/Gate/JenkinsGateController.php
@@ -1,83 +1,82 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Events\JenkinsPayloadEvent;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\Response;
-use Event;
-use Request;
-
class JenkinsGateController extends GateController {
///
/// Private members
///
/**
* The request content, as a structured data
*
* @var \stdClass
*/
private $payload;
/**
* The request content
*
* @var string
*/
private $rawRequestContent;
///
/// Request processing
///
/**
* Handles POST requests
*
* @param string $door The door, matching the project for this payload
* @return \Symfony\Component\HttpFoundation\Response
*/
public function onPost (string $door) : Response {
// Parses the request and check if it's legit
$this->door = $door;
$this->extractPayload();
// Process the request
$this->logRequest();
$this->onPayload();
// Output
return parent::renderReport();
}
/**
* Extracts payload from the request
*/
protected function extractPayload () {
$request = Request::instance();
$this->rawRequestContent = $request->getContent();
$this->payload = json_decode($this->rawRequestContent);
}
public function getServiceName () : string {
return "Jenkins";
}
///
/// Payload processing
///
protected function onPayload () {
$this->initializeReport();
- Event::fire(new JenkinsPayloadEvent(
+ Event::dispatch(new JenkinsPayloadEvent(
$this->door,
$this->payload
));
}
}
diff --git a/app/Http/Controllers/Gate/NotificationGateController.php b/app/Http/Controllers/Gate/NotificationGateController.php
index 8572ea7..419003c 100644
--- a/app/Http/Controllers/Gate/NotificationGateController.php
+++ b/app/Http/Controllers/Gate/NotificationGateController.php
@@ -1,139 +1,137 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Events\NotificationEvent;
use Nasqueron\Notifications\Notifications\Notification;
-use Symfony\Component\HttpFoundation\Response;
-
-use Event;
-use Request;
-
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Request;
use InvalidArgumentException;
+use Symfony\Component\HttpFoundation\Response;
class NotificationGateController extends GateController {
///
/// Private members
///
/**
* The request content, as a structured data
*
* @var \Nasqueron\Notifications\Notifications\Notification
*/
private $payload;
/**
* The request content
*
* @var string
*/
private $rawRequestContent;
///
/// Request processing
///
/**
* Handles POST requests
*
* @param string $door The door, matching the project for this payload
* @return \Symfony\Component\HttpFoundation\Response
*/
public function onPost (string $door) : Response {
// Parses the request and check if it's legit
$this->door = $door;
try {
$this->extractPayload();
$this->normalizePayload();
} catch (InvalidArgumentException $ex) {
abort(400, 'Bad request.');
}
// Process the request
$this->logRequest();
$this->onPayload();
// Output
return parent::renderReport();
}
/**
* Extracts payload from the request
*/
protected function extractPayload () {
$request = Request::instance();
$this->rawRequestContent = $request->getContent();
$this->payload = $this->getNotification();
}
protected function getServiceName () : string {
return (string)$this->payload->service;
}
///
/// Helper methods to get notification
///
private function getNotification () : Notification {
$payload = json_decode($this->rawRequestContent);
if ($payload === null) {
throw new InvalidArgumentException("Invalid JSON");
}
$mapper = new \JsonMapper();
- return (Notification)($mapper->map(
+ return $mapper->map(
$payload,
new Notification
- ));
+ );
}
private function normalizePayload () : void {
$this->normalizeProject();
$this->ensureRequiredPayloadFieldsArePresent();
}
private function normalizeProject () : void {
if (!$this->isPayloadFieldPresent('project')) {
$this->payload->project = $this->door;
}
}
private function ensureRequiredPayloadFieldsArePresent () : void {
foreach ($this->getMandatoryPayloadFields() as $field) {
if (!$this->isPayloadFieldPresent($field)) {
throw new InvalidArgumentException("Field $field is missing.");
}
}
}
private function getMandatoryPayloadFields () : array {
return [
'service',
'project',
'group',
'type',
];
}
private function isPayloadFieldPresent (string $field) : bool {
return (string)$this->payload->$field !== "";
}
///
/// Payload processing
///
protected function onPayload () {
$this->initializeReport();
- Event::fire(new NotificationEvent($this->payload));
+ Event::dispatch(new NotificationEvent($this->payload));
}
}
diff --git a/app/Http/Controllers/Gate/PhabricatorGateController.php b/app/Http/Controllers/Gate/PhabricatorGateController.php
index b4c94a3..52f056e 100644
--- a/app/Http/Controllers/Gate/PhabricatorGateController.php
+++ b/app/Http/Controllers/Gate/PhabricatorGateController.php
@@ -1,73 +1,72 @@
<?php
namespace Nasqueron\Notifications\Http\Controllers\Gate;
use Nasqueron\Notifications\Events\PhabricatorPayloadEvent;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\Response;
-use Event;
-use Request;
-
class PhabricatorGateController extends GateController {
///
/// Private members
///
/**
* The request content, as a structured data
*
* @var array
*/
private $payload;
///
/// Requests processing
///
/**
* Handles POST requests
*
* @param string $door The door, matching the project for this payload
* @return \Symfony\Component\HttpFoundation\Response
*/
public function onPost (string $door) : Response {
$this->door = $door;
if (!$this->doesServiceExist()) {
abort(404, 'Unknown Phabricator instance.');
}
$this->extractPayload();
$this->logRequest();
$this->onPayload();
return parent::renderReport();
}
/**
* Extracts payload from the request
*/
protected function extractPayload () : void {
$this->payload = Request::all();
}
public function getServiceName () : string {
return "Phabricator";
}
///
/// Payload processing
///
protected function onPayload () : void {
$this->initializeReport();
- Event::fire(new PhabricatorPayloadEvent(
+ Event::dispatch(new PhabricatorPayloadEvent(
$this->door,
$this->payload
));
}
}
diff --git a/app/Http/routes.php b/app/Http/routes.php
index e20d78f..d5b08eb 100644
--- a/app/Http/routes.php
+++ b/app/Http/routes.php
@@ -1,42 +1,46 @@
<?php
use Nasqueron\Notifications\Config\Features;
use Nasqueron\Notifications\Config\Reporting\ConfigReport;
+use Illuminate\Support\Facades\Config;
+use Illuminate\Support\Facades\Response;
+use Illuminate\Support\Facades\Route;
+
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
// Allows to external tool to ping your instalation and know if the site is up.
Route::get('/status', function() {
return "ALIVE";
});
// Allows to external tool to check the current configuration.
if (Features::isEnabled('GetConfig')) {
Route::get('/config', function() {
$report = new ConfigReport();
return Response::json($report);
});
}
// Gate controllers
if (Features::isEnabled('Gate')) {
foreach (Config::get('gate.controllers') as $controller) {
$controllerRoute = '/gate/' . $controller . '/';
$controllerClass = "Gate\\${controller}GateController";
Route::get($controllerRoute . '{door?}', "$controllerClass@onGet");
Route::post($controllerRoute . '{door}', "$controllerClass@onPost");
}
}
diff --git a/app/Jobs/FireDockerHubNotification.php b/app/Jobs/FireDockerHubNotification.php
index 5f246a5..461d30c 100644
--- a/app/Jobs/FireDockerHubNotification.php
+++ b/app/Jobs/FireDockerHubNotification.php
@@ -1,47 +1,46 @@
<?php
namespace Nasqueron\Notifications\Jobs;
-use Nasqueron\Notifications\Notifications\DockerHubNotification;
use Nasqueron\Notifications\Events\DockerHubPayloadEvent;
use Nasqueron\Notifications\Events\NotificationEvent;
-use Nasqueron\Notifications\Jobs\Job;
+use Nasqueron\Notifications\Notifications\DockerHubNotification;
-use Event;
+use Illuminate\Support\Facades\Event;
class FireDockerHubNotification extends Job {
/**
- * @var DockerHubPayloadEvent;
+ * @var DockerHubPayloadEvent
*/
private $event;
/**
* Initializes a new instance of FireDockerHubNotification
*
* @param DockerHubPayloadEvent $event The event to notify
*/
public function __construct (DockerHubPayloadEvent $event) {
$this->event = $event;
}
///
/// Task
///
/**
* Executes the job.
*/
public function handle() : void {
$notification = $this->createNotification();
- Event::fire(new NotificationEvent($notification));
+ Event::dispatch(new NotificationEvent($notification));
}
protected function createNotification() : DockerHubNotification {
return new DockerHubNotification(
$this->event->door, // project
$this->event->event, // event type
$this->event->payload // raw content
);
}
}
diff --git a/app/Jobs/FireGitHubNotification.php b/app/Jobs/FireGitHubNotification.php
index 4ce7e18..b962a10 100644
--- a/app/Jobs/FireGitHubNotification.php
+++ b/app/Jobs/FireGitHubNotification.php
@@ -1,48 +1,47 @@
<?php
namespace Nasqueron\Notifications\Jobs;
-use Nasqueron\Notifications\Notifications\GitHubNotification;
use Nasqueron\Notifications\Events\GitHubPayloadEvent;
use Nasqueron\Notifications\Events\NotificationEvent;
-use Nasqueron\Notifications\Jobs\Job;
+use Nasqueron\Notifications\Notifications\GitHubNotification;
-use Event;
+use Illuminate\Support\Facades\Event;
class FireGitHubNotification extends Job {
/**
- * @var GitHubPayloadEvent;
+ * @var GitHubPayloadEvent
*/
private $event;
/**
* Initializes a new instance of FireGitHubNotification
*
* @param GitHubPayloadEvent $event The event to notify
*/
public function __construct (GitHubPayloadEvent $event) {
$this->event = $event;
}
///
/// Task
///
/**
* Executes the job.
*/
public function handle() : void {
$notification = $this->createNotification();
- Event::fire(new NotificationEvent($notification));
+ Event::dispatch(new NotificationEvent($notification));
}
protected function createNotification() : GitHubNotification {
return new GitHubNotification(
$this->event->door, // project
$this->event->event, // event type
$this->event->payload // raw content
);
}
}
diff --git a/app/Jobs/FireJenkinsNotification.php b/app/Jobs/FireJenkinsNotification.php
index 8a2d14e..e162c35 100644
--- a/app/Jobs/FireJenkinsNotification.php
+++ b/app/Jobs/FireJenkinsNotification.php
@@ -1,50 +1,49 @@
<?php
namespace Nasqueron\Notifications\Jobs;
-use Nasqueron\Notifications\Notifications\JenkinsNotification;
use Nasqueron\Notifications\Events\JenkinsPayloadEvent;
use Nasqueron\Notifications\Events\NotificationEvent;
-use Nasqueron\Notifications\Jobs\Job;
+use Nasqueron\Notifications\Notifications\JenkinsNotification;
-use Event;
+use Illuminate\Support\Facades\Event;
class FireJenkinsNotification extends Job {
/**
- * @var JenkinsPayloadEvent;
+ * @var JenkinsPayloadEvent
*/
private $event;
/**
* Initializes a new instance of FireJenkinsNotification
*
* @param JenkinsPayloadEvent $event The event to notify
*/
public function __construct (JenkinsPayloadEvent $event) {
$this->event = $event;
}
///
/// Task
///
/**
* Executes the job.
*
* @return void
*/
public function handle() : void {
$notification = $this->createNotification();
if ($notification->shouldNotify()) {
- Event::fire(new NotificationEvent($notification));
+ Event::dispatch(new NotificationEvent($notification));
}
}
protected function createNotification() : JenkinsNotification {
return new JenkinsNotification(
$this->event->door, // project
$this->event->payload // raw content
);
}
}
diff --git a/app/Jobs/FirePhabricatorNotification.php b/app/Jobs/FirePhabricatorNotification.php
index d8cb8a7..62581ef 100644
--- a/app/Jobs/FirePhabricatorNotification.php
+++ b/app/Jobs/FirePhabricatorNotification.php
@@ -1,46 +1,45 @@
<?php
namespace Nasqueron\Notifications\Jobs;
-use Nasqueron\Notifications\Notifications\PhabricatorNotification;
-use Nasqueron\Notifications\Events\PhabricatorPayloadEvent;
use Nasqueron\Notifications\Events\NotificationEvent;
-use Nasqueron\Notifications\Jobs\Job;
+use Nasqueron\Notifications\Events\PhabricatorPayloadEvent;
+use Nasqueron\Notifications\Notifications\PhabricatorNotification;
-use Event;
+use Illuminate\Support\Facades\Event;
class FirePhabricatorNotification extends Job {
/**
- * @var PhabricatorPayloadEvent;
+ * @var PhabricatorPayloadEvent
*/
private $event;
/**
* Initializes a new instance of FirePhabricatorNotification
*
* @param PhabricatorPayloadEvent $event The event to notify
*/
public function __construct (PhabricatorPayloadEvent $event) {
$this->event = $event;
}
///
/// Task
///
/**
* Executes the job.
*/
public function handle() : void {
$notification = $this->createNotification();
- Event::fire(new NotificationEvent($notification));
+ Event::dispatch(new NotificationEvent($notification));
}
protected function createNotification() : PhabricatorNotification {
return new PhabricatorNotification(
$this->event->door, // Project
$this->event->story // Story
);
}
}
diff --git a/app/Jobs/NotifyNewCommitsToDiffusion.php b/app/Jobs/NotifyNewCommitsToDiffusion.php
index 0b16d39..acd151f 100644
--- a/app/Jobs/NotifyNewCommitsToDiffusion.php
+++ b/app/Jobs/NotifyNewCommitsToDiffusion.php
@@ -1,201 +1,200 @@
<?php
namespace Nasqueron\Notifications\Jobs;
use Nasqueron\Notifications\Actions\ActionError;
use Nasqueron\Notifications\Actions\NotifyNewCommitsAction;
use Nasqueron\Notifications\Events\ReportEvent;
+use Nasqueron\Notifications\Facades\PhabricatorAPI;
use Nasqueron\Notifications\Phabricator\PhabricatorAPI as API;
use Nasqueron\Notifications\Phabricator\PhabricatorAPIException;
-use Event;
-use Log;
-use PhabricatorAPI;
-
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Log;
use RuntimeException;
/**
* This class allows to notify Phabricator of new commits, so daemons can pull
* these new commits and add them into Diffusion.
*/
class NotifyNewCommitsToDiffusion extends Job {
///
/// Private members
///
/**
* The clone URL of the repository
*
* @var string
*/
private $repository;
/**
* @var \Nasqueron\Notifications\Phabricator\PhabricatorAPI
*/
private $api;
/**
* @var string
*/
private $callSign;
/**
* @var NotifyNewCommitsAction
*/
private $actionToReport;
/**
* @var string
*/
private $sourceProject;
///
/// Constructor
///
/**
* Initializes a new instance of NotifyNewCommitsToDiffusion.
*/
public function __construct ($sourceProject, $repository) {
$this->sourceProject = $sourceProject;
$this->repository = $repository;
}
///
/// Task
///
/**
* Executes the job.
*
* @return void
*/
public function handle () : void {
if (!$this->fetchRequirements()) {
return;
}
$this->initializeReport();
$this->notifyPhabricator();
$this->sendReport();
}
/**
* Initializes the actions report.
*/
private function initializeReport () : void {
$this->actionToReport = new NotifyNewCommitsAction($this->callSign);
}
/**
* Notifies Phabricator to pull from the repository.
*/
private function notifyPhabricator () : void {
try {
$this->callDiffusionLookSoon();
} catch (PhabricatorAPIException $ex) {
$actionError = new ActionError($ex);
$this->actionToReport->attachError($actionError);
Log::error($ex);
}
}
/**
* Fires a report event with the actions report.
*/
private function sendReport () : void {
$event = new ReportEvent($this->actionToReport);
- Event::fire($event);
+ Event::dispatch($event);
}
///
/// Helper methods to find correct Phabricator instance and get the API
///
/**
* Gets the relevant Phabricator project for the specified source project.
*
* @return string The Phabricator project name
*/
private function getPhabricatorProject () : string {
return $this->sourceProject;
}
///
/// Helper methods to populate object members
///
/**
* Fetches API and call sign.
*
* @return bool true if all requirement have been fetched
*/
private function fetchRequirements () : bool {
return $this->fetchAPI() && $this->fetchCallSign();
}
/**
* Fetches the Phabricator API to use for the current source project.
*
* @return bool true if an API instance has been fetched
*/
private function fetchAPI () : bool {
$project = $this->getPhabricatorProject();
try {
$this->api = PhabricatorAPI::getForProject($project);
return true;
} catch (RuntimeException $ex) {
return false;
}
}
/**
* Fetches the call sign matching the repository.
*
* @return bool true if a call sign have been found ; otherwise, false.
*/
private function fetchCallSign () : bool {
$this->callSign = $this->getCallSign();
return $this->callSign !== "";
}
///
/// Helper methods to query Phabricator API
///
/**
* Gets the call sign matching the repository URL (e.g. "OPS").
*
* @return string the repository call sign, or "" if not in Phabricator
*/
private function getCallSign () : string {
$reply = $this->api->call(
'repository.query',
[ 'remoteURIs[0]' => $this->repository ]
);
if ($reply === null || !count($reply)) {
return "";
}
return API::getFirstResult($reply)->callsign;
}
/**
* Calls the diffusion.looksoon API method.
*
* @throws PhabricatorAPIException
*/
private function callDiffusionLookSoon () : void {
$this->api->call(
'diffusion.looksoon',
[ 'callsigns[0]' => $this->callSign ]
);
}
}
diff --git a/app/Jobs/SendMessageToBroker.php b/app/Jobs/SendMessageToBroker.php
index c4b3676..014f17c 100644
--- a/app/Jobs/SendMessageToBroker.php
+++ b/app/Jobs/SendMessageToBroker.php
@@ -1,113 +1,112 @@
<?php
namespace Nasqueron\Notifications\Jobs;
use Nasqueron\Notifications\Actions\ActionError;
use Nasqueron\Notifications\Actions\AMQPAction;
use Nasqueron\Notifications\Events\ReportEvent;
-use Nasqueron\Notifications\Jobs\Job;
+use Nasqueron\Notifications\Facades\Broker;
-use Broker;
-use Event;
-use Log;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Log;
class SendMessageToBroker extends Job {
///
/// Private members
///
/**
* The routing key, for topic exchange
*
* @var string
*/
private $routingKey = '';
/**
* The message to send
*
* @var string
*/
private $message = '';
/**
* The target exchange
*
* @var string
*/
private $target = '';
/**
* If not null, an exception thrown during the task
*
* @var \Exception
*/
private $exception;
///
/// Constructor
///
/**
* Creates a new job instance.
*
* @param string $target The queue or exchange to send the message to
* @param string $routingKey The routing key, for topic exchange
* @param string $message The message to send
*
* @return void
*/
public function __construct (
string $target,
string $routingKey,
string $message
) {
$this->target = $target;
$this->routingKey = $routingKey;
$this->message = $message;
}
///
/// Task
///
/**
* Executes the job.
*
* @return void
*/
public function handle() : void {
$this->sendMessage();
$this->report();
}
/**
* Sends the message to the broker.
*/
protected function sendMessage () : void {
try {
Broker::setExchangeTarget($this->target, "topic", true)
->routeTo($this->routingKey)
->sendMessage($this->message);
} catch (\Exception $ex) {
$this->exception = $ex;
Log::error($ex);
}
}
/**
* Prepares a report and fires a report event.
*/
protected function report () : void {
$actionToReport = new AMQPAction(
"publish",
$this->target,
$this->routingKey
);
if ($this->exception !== null) {
$actionToReport->attachError(new ActionError($this->exception));
}
- Event::fire(new ReportEvent($actionToReport));
+ Event::dispatch(new ReportEvent($actionToReport));
}
}
diff --git a/app/Jobs/TriggerDockerHubBuild.php b/app/Jobs/TriggerDockerHubBuild.php
index 7d3a5bb..fc1bab7 100644
--- a/app/Jobs/TriggerDockerHubBuild.php
+++ b/app/Jobs/TriggerDockerHubBuild.php
@@ -1,86 +1,85 @@
<?php
namespace Nasqueron\Notifications\Jobs;
use Nasqueron\Notifications\Actions\ActionError;
use Nasqueron\Notifications\Actions\TriggerDockerHubBuildAction;
use Nasqueron\Notifications\Events\ReportEvent;
-
-use DockerHub;
-use Event;
+use Nasqueron\Notifications\Facades\DockerHub;
use Exception;
+use Illuminate\Support\Facades\Event;
/**
* This class allows to trigger a new Docker Hub build.
*/
class TriggerDockerHubBuild extends Job {
///
/// Private members
///
/**
* @var string The Docker image to trigger a build for
*/
private $image;
/**
* @var TriggerDockerHubBuildAction
*/
private $actionToReport;
///
/// Constructor
///
/**
* Initializes a new instance of TriggerDockerHubBuild.
*/
public function __construct ($image) {
$this->image = $image;
}
///
/// Task
///
/**
* Executes the job.
*
* @return void
*/
public function handle () : void {
$this->initializeReport();
$this->triggerBuild();
$this->sendReport();
}
/**
* Initializes the actions report.
*/
private function initializeReport () : void {
$this->actionToReport = new TriggerDockerHubBuildAction($this->image);
}
/**
* Triggers a new Docker Hub build.
*/
private function triggerBuild () : void {
try {
DockerHub::build($this->image);
} catch (Exception $ex) {
$actionError = new ActionError($ex);
$this->actionToReport->attachError($actionError);
}
}
/**
* Fires a report event with the actions report.
*/
private function sendReport () : void {
$event = new ReportEvent($this->actionToReport);
- Event::fire($event);
+ Event::dispatch($event);
}
}
diff --git a/app/Listeners/AMQPEventListener.php b/app/Listeners/AMQPEventListener.php
index a2fa279..9caf706 100644
--- a/app/Listeners/AMQPEventListener.php
+++ b/app/Listeners/AMQPEventListener.php
@@ -1,72 +1,52 @@
<?php
namespace Nasqueron\Notifications\Listeners;
use Nasqueron\Notifications\Events\NotificationEvent;
use Nasqueron\Notifications\Jobs\SendMessageToBroker;
use Nasqueron\Notifications\Notifications\Notification;
-use Illuminate\Events\Dispatcher;
-
-use Config;
+use Illuminate\Support\Facades\Config;
class AMQPEventListener {
///
/// Notifications
///
/**
* Handles a notification event.
*
* @param NotificationEvent $event
*/
- public function onNotification(NotificationEvent $event) : void {
+ public function handle (NotificationEvent $event) : void {
$this->sendNotification($event->notification);
}
protected static function getNotificationRoutingKey (
Notification $notification
) : string {
$keyParts = [
$notification->project,
$notification->group,
$notification->service,
$notification->type,
];
return strtolower(implode('.', $keyParts));
}
/**
* Sends the notification to the broker target for distilled notifications.
*
* @param Notification The notification to send
*/
protected function sendNotification(Notification $notification) : void {
$target = Config::get('broker.targets.notifications');
$routingKey = static::getNotificationRoutingKey($notification);
$message = json_encode($notification);
$job = new SendMessageToBroker($target, $routingKey, $message);
$job->handle();
}
-
- ///
- /// Events listening
- ///
-
- /**
- * Registers the listeners for the subscriber.
- *
- * @param Dispatcher $events
- */
- public function subscribe (Dispatcher $events) : void {
- $class = AMQPEventListener::class;
- $events->listen(
- NotificationEvent::class,
- "$class@onNotification"
- );
- }
-
}
diff --git a/app/Listeners/DockerHubListener.php b/app/Listeners/DockerHubListener.php
index 33acfe6..46133e3 100644
--- a/app/Listeners/DockerHubListener.php
+++ b/app/Listeners/DockerHubListener.php
@@ -1,81 +1,60 @@
<?php
namespace Nasqueron\Notifications\Listeners;
use Nasqueron\Notifications\Events\GitHubPayloadEvent;
+use Nasqueron\Notifications\Facades\DockerHub;
use Nasqueron\Notifications\Jobs\TriggerDockerHubBuild;
-use Illuminate\Events\Dispatcher;
-
-use DockerHub;
-
/**
* Listens to events Docker Hub is interested by.
*/
class DockerHubListener {
///
/// GitHub → Docker Hub
///
/**
* Handles payload events.
*
* @param GitHubPayloadEvent $event The GitHub payload event
*/
- public function onGitHubPayload (GitHubPayloadEvent $event) : void {
+ public function handle (GitHubPayloadEvent $event) : void {
if ($this->shouldNotify($event)) {
$this->notifyNewCommits($event);
}
}
/**
* Determines if the event should be notified to Docker Hub.
* We're interested by push events, for repos with Docker images
* we've a token to trigger a build.
*
* @param GitHubPayloadEvent $event The GitHub payload event
* @return bool
*/
public function shouldNotify (GitHubPayloadEvent $event) : bool {
return $event->event === 'push'
&& DockerHub::hasToken($this->getRepository($event));
}
/**
* Notifies Docker Hub to rebuild image.
*
* @param GitHubPayloadEvent $event The GitHub payload event
*/
public function notifyNewCommits (GitHubPayloadEvent $event) : void {
$job = new TriggerDockerHubBuild($this->getRepository($event));
$job->handle();
}
/**
* Extracts repository fullname (e.g. acme/foo) from event.
*
* @var string
*/
private function getRepository (GitHubPayloadEvent $event) : string {
return $event->payload->repository->full_name;
}
-
- ///
- /// Events listening
- ///
-
- /**
- * Registers the listeners for the subscriber.
- *
- * @param Dispatcher $events
- */
- public function subscribe (Dispatcher $events) : void {
- $class = DockerHubListener::class;
- $events->listen(
- GitHubPayloadEvent::class,
- "$class@onGitHubPayload"
- );
- }
-
}
diff --git a/app/Listeners/LastPayloadSaver.php b/app/Listeners/LastPayloadSaver.php
index 3045596..6ec4da1 100644
--- a/app/Listeners/LastPayloadSaver.php
+++ b/app/Listeners/LastPayloadSaver.php
@@ -1,53 +1,29 @@
<?php
namespace Nasqueron\Notifications\Listeners;
use Nasqueron\Notifications\Events\Event;
class LastPayloadSaver {
///
/// Events handling
///
/**
* Handles payload events
*/
- public function onPayload (Event $event) : void {
+ public function handle (Event $event) : void {
self::savePayload($event->payload);
}
/**
* Saves payload to log file
*
* @param mixed $payload The payload to save
*/
public static function savePayload ($payload) : void {
$filename = storage_path('logs/payload.json');
$content = json_encode($payload);
file_put_contents($filename, $content);
}
-
- ///
- /// Events listening
- ///
-
- /**
- * Register the listeners for the subscriber.
- *
- * @param \Illuminate\Events\Dispatcher $events
- */
- public function subscribe (\Illuminate\Events\Dispatcher $events) : void {
- $ns = 'Nasqueron\Notifications\Events';
- $class = 'Nasqueron\Notifications\Listeners\LastPayloadSaver';
- $eventsToListen = [
- 'DockerHubPayloadEvent',
- 'GitHubPayloadEvent',
- 'JenkinsPayloadEvent',
- 'PhabricatorPayloadEvent',
- ];
-
- foreach ($eventsToListen as $event) {
- $events->listen("$ns\\$event", "$class@onPayload");
- }
- }
}
diff --git a/app/Listeners/NotificationListener.php b/app/Listeners/NotificationListener.php
index 991370d..70f8d47 100644
--- a/app/Listeners/NotificationListener.php
+++ b/app/Listeners/NotificationListener.php
@@ -1,96 +1,88 @@
<?php
namespace Nasqueron\Notifications\Listeners;
use Nasqueron\Notifications\Events\DockerHubPayloadEvent;
+use Nasqueron\Notifications\Events\Event;
use Nasqueron\Notifications\Events\GitHubPayloadEvent;
use Nasqueron\Notifications\Events\JenkinsPayloadEvent;
use Nasqueron\Notifications\Events\PhabricatorPayloadEvent;
use Nasqueron\Notifications\Jobs\FireDockerHubNotification;
use Nasqueron\Notifications\Jobs\FireGitHubNotification;
use Nasqueron\Notifications\Jobs\FireJenkinsNotification;
use Nasqueron\Notifications\Jobs\FirePhabricatorNotification;
+use InvalidArgumentException;
+
class NotificationListener {
///
/// Distill services' payloads into notifications
///
/**
* Handles a Docker Hub payload event.
*
* @param DockerHubPayloadEvent $event
* @return void
*/
public function onDockerHubPayload(DockerHubPayloadEvent $event) : void {
$job = new FireDockerHubNotification($event);
$job->handle();
}
/**
* Handles a GitHub payload event.
*
* @param GitHubPayloadEvent $event
* @return void
*/
public function onGitHubPayload(GitHubPayloadEvent $event) : void {
$job = new FireGitHubNotification($event);
$job->handle();
}
/**
* Handles a Phabricator payload event.
*
* @param PhabricatorPayloadEvent $event
* @return void
*/
public function onPhabricatorPayload(
PhabricatorPayloadEvent $event
) : void {
$job = new FirePhabricatorNotification($event);
$job->handle();
}
/**
* Handles a Jenkins payload event.
*
* @param JenkinsPayloadEvent $event
* @return void
*/
public function onJenkinsPayload (JenkinsPayloadEvent $event) : void {
$job = new FireJenkinsNotification($event);
$job->handle();
}
///
- /// Events listening
+ /// Events sorter
///
- /**
- * Register the listeners for the subscriber.
- *
- * @param \Illuminate\Events\Dispatcher $events
- */
- public function subscribe (\Illuminate\Events\Dispatcher $events) : void {
- $class = 'Nasqueron\Notifications\Listeners\NotificationListener';
- $events->listen(
- 'Nasqueron\Notifications\Events\DockerHubPayloadEvent',
- "$class@onDockerHubPayload"
- );
- $events->listen(
- 'Nasqueron\Notifications\Events\GitHubPayloadEvent',
- "$class@onGitHubPayload"
- );
- $events->listen(
- 'Nasqueron\Notifications\Events\JenkinsPayloadEvent',
- "$class@onJenkinsPayload"
- );
- $events->listen(
- 'Nasqueron\Notifications\Events\PhabricatorPayloadEvent',
- "$class@onPhabricatorPayload"
- );
+ private static function getEventHandlerMethod (string $eventClasss) : string {
+ $parts = explode('\\', $eventClasss);
+ $className = end($parts);
+
+ if (!str_ends_with($className, "Event")) {
+ throw new InvalidArgumentException("Events classes must be ended by 'Event'");
+ }
+ return "on" . substr($className, 0, strlen($className)-5);
}
+ public function handle (Event $event) : void {
+ $callable = [$this, self::getEventHandlerMethod($event::class)];
+ $callable($event);
+ }
}
diff --git a/app/Listeners/PhabricatorListener.php b/app/Listeners/PhabricatorListener.php
index d7acc7d..1268d93 100644
--- a/app/Listeners/PhabricatorListener.php
+++ b/app/Listeners/PhabricatorListener.php
@@ -1,59 +1,40 @@
<?php
namespace Nasqueron\Notifications\Listeners;
use Nasqueron\Notifications\Events\GitHubPayloadEvent;
use Nasqueron\Notifications\Jobs\NotifyNewCommitsToDiffusion;
-use Illuminate\Events\Dispatcher;
-
/**
* Listens to events Phabricator is interested by.
*/
class PhabricatorListener {
///
/// GitHub → Phabricator
///
/**
* Handles payload events.
*
* @param GitHubPayloadEvent $event The GitHub payload event
*/
- public function onGitHubPayload (GitHubPayloadEvent $event) : void {
+ public function handle (GitHubPayloadEvent $event) : void {
if ($event->event === 'push') {
$this->notifyNewCommits($event);
}
}
/**
* Notifies Phabricator there are new commits to pull.
*
* @param GitHubPayloadEvent $event The GitHub payload event
*/
public function notifyNewCommits (GitHubPayloadEvent $event) : void {
$job = new NotifyNewCommitsToDiffusion(
$event->door,
$event->payload->repository->clone_url
);
$job->handle();
}
-
- ///
- /// Events listening
- ///
-
- /**
- * Registers the listeners for the subscriber.
- *
- * @param Dispatcher $events
- */
- public function subscribe (Dispatcher $events) : void {
- $class = PhabricatorListener::class;
- $events->listen(
- GitHubPayloadEvent::class,
- "$class@onGitHubPayload"
- );
- }
}
diff --git a/app/Phabricator/PhabricatorAPI.php b/app/Phabricator/PhabricatorAPI.php
index e92ea0e..49270ed 100644
--- a/app/Phabricator/PhabricatorAPI.php
+++ b/app/Phabricator/PhabricatorAPI.php
@@ -1,164 +1,163 @@
<?php
namespace Nasqueron\Notifications\Phabricator;
use Nasqueron\Notifications\Contracts\APIClient;
-
-use Services;
+use Nasqueron\Notifications\Facades\Services;
class PhabricatorAPI implements APIClient {
///
/// Private members
///
/**
* The Phabricator main URL
*
* @var string
*/
private $endPoint;
/**
* The token generated at /settings/panel/apitokens/ to query the API
*
* @var string
*/
private $apiToken;
///
/// Constructors
///
/**
* Initializes a new instance of the Phabricator API class
*
* @param string $endPoint The Phabricator main URL, without trailing slash
* @param string $apiToken The token generated at /settings/panel/apitokens/
*/
public function __construct ($endPoint, $apiToken) {
$this->endPoint = $endPoint;
$this->apiToken = $apiToken;
}
/**
* @throws \RuntimeException when the service isn't in credentials.json
*/
public static function forInstance ($instance) : PhabricatorAPI {
$service = Services::findServiceByProperty(
'Phabricator',
'instance',
$instance
);
if ($service === null) {
throw new \RuntimeException(
"No credentials for Phabricator instance $instance."
);
}
return new self($service->instance, $service->secret);
}
/**
* @throws \RuntimeException when the service isn't in credentials.json
*/
public static function forProject ($project) {
$service = Services::findServiceByDoor('Phabricator', $project);
if ($service === null) {
throw new \RuntimeException(
"No credentials for Phabricator project $project."
);
}
return new self($service->instance, $service->secret);
}
///
/// APIClient implementation
///
/**
* Sets API end point
*
* @param string $url The API end point URL
*/
public function setEndPoint ($url) {
$this->endPoint = $url;
}
/**
* Calls a Conduit API method
*
* @param string $method The method to call (e.g. repository.create)
* @param array $arguments The arguments to use
* @return mixed The API result
*/
public function call ($method, $arguments = []) {
$url = $this->endPoint . '/api/' . $method;
$arguments['api.token'] = $this->apiToken;
$reply = json_decode(static::post($url, $arguments));
if ($reply->error_code !== null) {
throw new PhabricatorAPIException(
$reply->error_code,
$reply->error_info
);
}
return $reply->result;
}
///
/// Helper methods
///
/**
* Gets the first result of an API reply.
*
* @param iterable $reply
* @return mixed
*/
public static function getFirstResult ($reply) {
if (is_object($reply) && property_exists($reply, 'data')) {
$reply = $reply->data;
}
foreach ($reply as $value) {
return $value;
}
}
///
/// CURL session
///
protected static function getPostFields ($arguments) {
$items = [];
foreach ($arguments as $key => $value) {
$items[] = urlencode($key) . '=' . urlencode($value);
}
return implode('&', $items);
}
protected static function post ($url, $arguments) {
$options = [
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POSTFIELDS => static::getPostFields($arguments),
];
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
if ($result === false) {
throw new \RuntimeException(
"Can't reach Phabricator API endpoint: $url"
);
}
return $result;
}
}
diff --git a/app/Phabricator/PhabricatorStory.php b/app/Phabricator/PhabricatorStory.php
index 2464c8e..33822bb 100644
--- a/app/Phabricator/PhabricatorStory.php
+++ b/app/Phabricator/PhabricatorStory.php
@@ -1,331 +1,331 @@
<?php
namespace Nasqueron\Notifications\Phabricator;
use InvalidArgumentException;
class PhabricatorStory {
///
/// Properties
///
/**
* The Phabricator instance name
*
* @var string
*/
public $instanceName;
/**
* The unique identifier Phabricator assigns to each story
*
* @var int
*/
public $id;
/**
* Type of story (e.g. PhabricatorApplicationTransactionFeedStory)
*
* @var string
*/
public $type;
/**
* @var array|null
*/
public $data;
/**
* The person logged to Phabricator and triggering the event
*
* @var string
*/
public $authorPHID;
/**
* A short English textual description of the event
*
* @var string
*/
public $text;
/**
* The unixtime the event occured
*
* @var int
*/
public $epoch;
/**
* The projects attached to this story.
*
* When there is no project, [].
* When not yet queried, null.
*
* @var string[]|null
*/
private $projects = null;
///
/// Constructors
///
/**
* Initializes a new instance of the Phabricator story class
*
* @param string $instanceName The Phabricator instance name
*/
public function __construct ($instanceName) {
$this->instanceName = $instanceName;
}
/**
* Initializes a new instance of PhabricatorStory from an iterable.
*
* This is intended to parse the feed.hooks payloads.
*
* @param string $instanceName The Phabricator instance name
* @param iterable $payload The data submitted by Phabricator
* @return PhabricatorStory
*/
public static function loadFromIterable (
string $instanceName, iterable $payload
) {
$instance = new self($instanceName);
foreach ($payload as $key => $value) {
$property = self::mapPhabricatorFeedKey($key);
$instance->$property = $value;
}
return $instance;
}
public static function loadFromJson (
$instanceName,
$payload
) {
$array = json_decode($payload, true);
if (!is_array($array)) {
throw new InvalidArgumentException(<<<MSG
Payload should be deserializable as an array.
MSG
);
}
return self::loadFromIterable($instanceName, $array);
}
///
/// Helper methods
///
private function hasVoidObjectType () : bool {
return $this->data === null || !isset($this->data['objectPHID']);
}
/**
* Gets object type (e.g. TASK for PHID-TASK-l34fw5wievp6n6rnvpuk)
*
* @return string The object type, as a 4 letters string (e.g. 'TASK')
*/
public function getObjectType () {
if ($this->hasVoidObjectType()) {
return 'VOID';
}
return substr($this->data['objectPHID'], 5, 4);
}
/**
* Gets the identifier of the projets related to this task
*
* return string[] The list of project PHIDs
*/
public function getProjectsPHIDs () {
if (!array_key_exists('objectPHID', $this->data)) {
return [];
}
$objectPHID = $this->data['objectPHID'];
$objectType = $this->getObjectType();
switch ($objectType) {
case 'DREV':
return $this->getItemProjectsPHIDs(
'repository.query',
$this->getRepositoryPHID('differential.query')
);
case 'TASK':
return $this->getItemProjectsPHIDs(
'maniphest.query',
$objectPHID
);
case 'CMIT':
return $this->getItemProjectsPHIDs(
'repository.query',
$this->getRepositoryPHID('diffusion.querycommits')
);
case 'PSTE':
return $this->getItemProjectsPHIDsThroughApplicationSearch(
'paste.search',
$objectPHID
);
default:
return [];
}
}
/**
* Gets the PHID of a repository
*
* @param string $method The API method to call (e.g. differential.query)
* @return string The repository PHID or "" if not found
*/
public function getRepositoryPHID ($method) {
$objectPHID = $this->data['objectPHID'];
$api = PhabricatorAPI::forProject($this->instanceName);
$reply = $api->call(
$method,
[ 'phids[0]' => $objectPHID ]
);
if ($reply === []) {
return "";
}
$apiResult = PhabricatorAPI::getFirstResult($reply);
if ($apiResult === null) {
// Repository information can't be fetched (T1136).
// This occurs when the bot account used to fetch information
// doesn't have access to the repository, for example if it's
// in a private space or restricted to a group it doesn't belong to.
return "";
}
return $apiResult->repositoryPHID;
}
/**
* Gets the projects for a specific item
*
* @param string $method The API method to call (e.g. differential.query)
* @param string $objectPHID The object PHID to pass as method parameter
* @return string[] The list of project PHIDs
*/
public function getItemProjectsPHIDs ($method, $objectPHID) {
if (!$objectPHID) {
return [];
}
$api = PhabricatorAPI::forProject($this->instanceName);
$reply = $api->call(
$method,
[ 'phids[0]' => $objectPHID ]
);
if ($reply === []) {
return [];
}
return PhabricatorAPI::getFirstResult($reply)->projectPHIDs;
}
/**
* Gets the project for a specific item, using the new ApplicationSearch.
*
* This is a transitional method: when every Phabricator will have been
* migrated from info (generation 1) or query (generation 2) to search
* (generation 3), we'll rename it to getItemProjectsPHIDs and overwrite it.
*/
protected function getItemProjectsPHIDsThroughApplicationSearch (
$method,
$objectPHID
) {
if (!$objectPHID) {
return [];
}
$api = PhabricatorAPI::forProject($this->instanceName);
$reply = $api->call(
$method,
[
'constraints[phids][0]' => $objectPHID,
'attachments[projects]' => 1
]
);
$apiResult = PhabricatorAPI::getFirstResult($reply);
if ($apiResult === null) {
// Object information (e.g. a paste) can't be fetched (T1138).
// This occurs when the bot account used to fetch information
// doesn't have access to the object, for example if it's
// in a private space or restricted to a group it doesn't belong to.
return [];
}
return $apiResult->attachments->projects->projectPHIDs;
}
/**
* Gets the list of the projects associated to the story
*
* @return string[] The list of project PHIDs
*/
public function getProjects () {
if ($this->projects === null) {
$this->attachProjects();
}
return $this->projects;
}
/**
* Queries the list of the projects associated to the story
* and attached it to the projects property.
*/
public function attachProjects () {
$this->projects = [];
$PHIDs = $this->getProjectsPHIDs();
if (count($PHIDs) == 0) {
// No project is attached to the story's object
return;
}
$map = ProjectsMap::load($this->instanceName);
foreach ($PHIDs as $PHID) {
$this->projects[] = $map->getProjectName($PHID);
}
}
///
/// Static helper methods
///
/**
* Maps a field of the API reply to a property of the PhabricatorStory class
*
* @param string $key The field of the API reply
* @return string The property's name
*/
public static function mapPhabricatorFeedKey ($key) {
if ($key == "storyID") {
return "id";
}
- if (starts_with($key, "story") && strlen($key) > 5) {
+ if (str_starts_with($key, "story") && strlen($key) > 5) {
return lcfirst(substr($key, 5));
}
return $key;
}
}
diff --git a/app/Phabricator/ProjectsMap.php b/app/Phabricator/ProjectsMap.php
index 5e093d2..0596b70 100644
--- a/app/Phabricator/ProjectsMap.php
+++ b/app/Phabricator/ProjectsMap.php
@@ -1,285 +1,285 @@
<?php
namespace Nasqueron\Notifications\Phabricator;
use Nasqueron\Notifications\Contracts\APIClient as APIClient;
-use App;
-use Cache;
+use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\Cache;
class ProjectsMap implements \IteratorAggregate, \ArrayAccess {
///
/// Private properties and constants
///
/**
* The maximum number of projects to fetch
*/
const LIMIT = 1000;
/**
* The projects as an array with phid as keys, project names as $value
*
* @var string[]
*/
private $map = [];
/**
* The Phabricator instance name for this projects map
*
* @var string
*/
private $instanceName;
/**
*
* @var \Nasqueron\Notifications\Contracts\APIClient
*/
private $apiClient;
/**
* The source of the map
*
* @var string
*/
private $source = 'unloaded';
///
/// Constructor
///
/**
* Initializes a new instance of ProjectsMap.
*
* @param string $instanceName The Phabricator instance name
*/
public function __construct ($instanceName) {
$this->instanceName = $instanceName;
}
///
/// IteratorAggregate interface implementation
///
/**
* Gets iterator.
*
* @return \Traversable
*/
public function getIterator () {
return new \ArrayIterator($this->map);
}
///
/// ArrayAccess interface implementation
///
/**
* Determines whether an offset exists.
*
* @param mixed $offset The offset
* @return bool
*/
public function offsetExists ($offset) {
return array_key_exists($offset, $this->map);
}
/**
* Gets the value at the specified offset.
*
* @param mixed $offset The offset.
* @return mixed The value
*/
public function offsetGet ($offset) {
return $this->map[$offset];
}
/**
* Assigns a value to the specified offset.
*
* @param mixed $offset The offset
* @param mixed $value The value to assign
*/
public function offsetSet ($offset, $value) {
$this->map[$offset] = $value;
}
/**
* Unsets a value at the specified offset.
*
* @param mixed $offset The offset where to remove the value
*/
public function offsetUnset ($offset) {
unset($this->map[$offset]);
}
///
/// Static constructors
///
/**
* Gets a new ProjectsMap instance from cache or API when not cached.
*
* @param string $phabricatorInstanceName The Phabricator instance name
* @return ProjectsMap
*/
public static function load ($phabricatorInstanceName) {
$instance = new self($phabricatorInstanceName);
if ($instance->isCached()) {
$instance->loadFromCache();
} else {
$instance->fetchFromAPI();
}
return $instance;
}
/**
* Gets a new ProjectsMap instance and queries Phabricator API to fill it.
*/
public static function fetch (
string $phabricatorInstanceName,
?APIClient $apiClient = null
) {
$instance = new self($phabricatorInstanceName);
$instance->setAPIClient($apiClient);
$instance->fetchFromAPI();
return $instance;
}
///
/// API
///
/**
* @return \Nasqueron\Notifications\Contracts\APIClient
*/
public function getAPIClient () {
if ($this->apiClient === null) {
$factory = App::make('phabricator-api');
$this->apiClient = $factory->getForProject($this->instanceName);
}
return $this->apiClient;
}
/**
* @param \Nasqueron\Notifications\Contracts\APIClient|null $apiClient
*/
public function setAPIClient (?APIClient $apiClient = null) {
$this->apiClient = $apiClient;
}
/**
* Fetches the projects' map from the Phabricator API.
*
* @throws \Exception when API reply is empty or invalid.
*/
private function fetchFromAPI () {
$reply = $this->getAPIClient()->call(
'project.query',
[ 'limit' => self::LIMIT ]
);
if (!$reply) {
throw new \Exception(<<<MSG
Empty reply calling project.query at $this->instanceName Conduit API.
MSG
);
}
if (!property_exists($reply, 'data')) {
throw new \Exception(<<<MSG
Invalid reply calling project.query at $this->instanceName Conduit API.
MSG
);
}
foreach ($reply->data as $phid => $projectInfo) {
$this->offsetSet($phid, $projectInfo->name);
}
$this->source = 'api';
}
///
/// Cache
///
/**
* Gets cache key.
*
* @return string The cache key for the current projects map
*/
private function getCacheKey () {
return class_basename(get_class($this))
. '-'
. md5($this->instanceName);
}
/**
* Determines if the instance is cached
*
* @return bool true if cached; otherwise, false.
*/
public function isCached () {
return Cache::has($this->getCacheKey());
}
/**
* Saves data to cache
*/
public function saveToCache () {
Cache::forever($this->getCacheKey(), $this->map);
}
/**
* Loads data from cache
*
* Populates 'map' and 'source' properties
*/
public function loadFromCache () {
$cachedMap = Cache::get($this->getCacheKey());
if ($cachedMap !== null) {
$this->map = $cachedMap;
$this->source = 'cache';
}
}
///
/// Output
///
/**
* Gets project name, refreshing the cache if needed.
*
* @param string $projectPHID the PHID of the project to query the name
* @return string The name of the poject, or an empty string if not found
*/
public function getProjectName ($projectPHID) {
if ($this->offsetExists($projectPHID)) {
return $this->offsetGet($projectPHID);
}
if ($this->source !== 'api') {
$this->fetchFromAPI();
return $this->getProjectName($projectPHID);
}
return "";
}
/**
* Returns the projects map as an array.
*
* @return array An array, each row containing ['PHID', 'project name']
*/
public function toArray () {
$array = [];
foreach ($this->map as $phid => $projectName) {
$array[] = [$phid, $projectName];
}
return $array;
}
}
diff --git a/app/Phabricator/ProjectsMapFactory.php b/app/Phabricator/ProjectsMapFactory.php
index a787a5a..e19a9f6 100644
--- a/app/Phabricator/ProjectsMapFactory.php
+++ b/app/Phabricator/ProjectsMapFactory.php
@@ -1,27 +1,27 @@
<?php
namespace Nasqueron\Notifications\Phabricator;
class ProjectsMapFactory {
/**
* Loads projects map from cache or fetches it from API if not cached.
*
* @param string $instanceName The Phabricator instance name
* @return ProjectsMap
*/
- public function load ($instanceName) {
+ public function load (string $instanceName) {
return ProjectsMap::load($instanceName);
}
/**
* Fetches projects map from API.
*
* @param string $instanceName The Phabricator instance name
* @return ProjectsMap
*/
- public function fetch ($instanceName) {
+ public function fetch (string $instanceName) {
return ProjectsMap::fetch($instanceName);
}
}
diff --git a/app/Providers/DockerHubServiceProvider.php b/app/Providers/DockerHubServiceProvider.php
index e7c3020..7cb52f4 100644
--- a/app/Providers/DockerHubServiceProvider.php
+++ b/app/Providers/DockerHubServiceProvider.php
@@ -1,49 +1,50 @@
<?php
namespace Nasqueron\Notifications\Providers;
+use Keruald\DockerHub\Build\TriggerBuildFactory;
+
+use GuzzleHttp\Client;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
-use GuzzleHttp\Client;
-use Keruald\DockerHub\Build\TriggerBuildFactory;
class DockerHubServiceProvider extends ServiceProvider {
/**
* Bootstraps the application services.
*
* @return void
*/
public function boot() {
}
/**
* Gets the tokens to trigger build for the Docker Hub images.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return array
*/
public static function getTokens (Application $app) {
$file = $app->make('config')->get('services.dockerhub.tokens');
$fs = $app->make('filesystem')->disk('local');
if ($fs->exists($file)) {
$content = $fs->get($file);
return json_decode($content, true);
}
return [];
}
/**
* Registers the application services.
*
* @return void
*/
public function register() {
$this->app->singleton('dockerhub', function (Application $app) {
$tokens = DockerHubServiceProvider::getTokens($app);
return new TriggerBuildFactory(new Client, $tokens);
});
}
}
diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php
index a46d0e2..3f80e5e 100644
--- a/app/Providers/EventServiceProvider.php
+++ b/app/Providers/EventServiceProvider.php
@@ -1,30 +1,49 @@
<?php
namespace Nasqueron\Notifications\Providers;
-use Illuminate\{
- Contracts\Events\Dispatcher as DispatcherContract,
- Foundation\Support\Providers\EventServiceProvider as ServiceProvider
-};
+use Nasqueron\Notifications\Events\DockerHubPayloadEvent;
+use Nasqueron\Notifications\Events\GitHubPayloadEvent;
+use Nasqueron\Notifications\Events\JenkinsPayloadEvent;
+use Nasqueron\Notifications\Events\NotificationEvent;
+use Nasqueron\Notifications\Events\PhabricatorPayloadEvent;
+use Nasqueron\Notifications\Listeners\AMQPEventListener;
+use Nasqueron\Notifications\Listeners\DockerHubListener;
+use Nasqueron\Notifications\Listeners\LastPayloadSaver;
+use Nasqueron\Notifications\Listeners\NotificationListener;
+use Nasqueron\Notifications\Listeners\PhabricatorListener;
-use Config;
+use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
/**
- * Registers all our listeners as subscriber classes
- */
- private function subscribeListeners () {
- $this->subscribe += Config::get('app.listeners');
- }
-
- /**
- * Register any other events for your application.
+ * The event listener mappings for the application.
*
- * @return void
+ * @var array
*/
- public function boot() {
- $this->subscribeListeners();
- parent::boot();
- }
+ protected $listen = [
+ DockerHubPayloadEvent::class => [
+ LastPayloadSaver::class,
+ NotificationListener::class,
+ ],
+ GitHubPayloadEvent::class => [
+ DockerHubListener::class,
+ LastPayloadSaver::class,
+ NotificationListener::class,
+ PhabricatorListener::class,
+ ],
+ JenkinsPayloadEvent::class => [
+ LastPayloadSaver::class,
+ NotificationListener::class,
+ ],
+ NotificationEvent::class => [
+ AMQPEventListener::class,
+ ],
+ PhabricatorPayloadEvent::class => [
+ LastPayloadSaver::class,
+ NotificationListener::class,
+ ],
+ ];
+
}
diff --git a/app/Providers/MailgunServiceProvider.php b/app/Providers/MailgunServiceProvider.php
index c76508c..f275ea1 100644
--- a/app/Providers/MailgunServiceProvider.php
+++ b/app/Providers/MailgunServiceProvider.php
@@ -1,33 +1,33 @@
<?php
namespace Nasqueron\Notifications\Providers;
-use Illuminate\Contracts\Foundation\Application;
-use Illuminate\Support\ServiceProvider;
+use Keruald\Mailgun\MailgunMessageFactory;
use GuzzleHttp\Client;
-use Keruald\Mailgun\MailgunMessageFactory;
+use Illuminate\Contracts\Foundation\Application;
+use Illuminate\Support\ServiceProvider;
class MailgunServiceProvider extends ServiceProvider {
/**
* Bootstraps the application services.
*
* @return void
*/
public function boot() {
}
/**
* Registers the application services.
*
* @return void
*/
public function register() {
$this->app->singleton('mailgun', function (Application $app) {
$config = $app->make('config');
$key = $config->get('services.mailgun.secret');
return new MailgunMessageFactory(new Client, $key);
});
}
}
diff --git a/app/Providers/PhabricatorAPIServiceProvider.php b/app/Providers/PhabricatorAPIServiceProvider.php
index dc7aaf0..13678ea 100644
--- a/app/Providers/PhabricatorAPIServiceProvider.php
+++ b/app/Providers/PhabricatorAPIServiceProvider.php
@@ -1,29 +1,29 @@
<?php
namespace Nasqueron\Notifications\Providers;
use Illuminate\Support\ServiceProvider;
use Nasqueron\Notifications\Phabricator\PhabricatorAPIFactory;
class PhabricatorAPIServiceProvider extends ServiceProvider {
/**
* Bootstraps the application services.
*
* @return void
*/
public function boot() {
}
/**
* Registers the application services.
*
* @return void
*/
public function register() {
- $this->app->singleton('phabricator-api', function () {
+ $this->app->singleton('phabricator-api', static function () {
return new PhabricatorAPIFactory;
});
}
}
diff --git a/app/Providers/PhabricatorProjectsMapServiceProvider.php b/app/Providers/PhabricatorProjectsMapServiceProvider.php
index e762cfa..9610d00 100644
--- a/app/Providers/PhabricatorProjectsMapServiceProvider.php
+++ b/app/Providers/PhabricatorProjectsMapServiceProvider.php
@@ -1,29 +1,29 @@
<?php
namespace Nasqueron\Notifications\Providers;
use Illuminate\Support\ServiceProvider;
use Nasqueron\Notifications\Phabricator\ProjectsMapFactory;
class PhabricatorProjectsMapServiceProvider extends ServiceProvider {
/**
* Bootstraps the application services.
*
* @return void
*/
public function boot() {
}
/**
* Registers the application services.
*
* @return void
*/
public function register() {
- $this->app->singleton('phabricator-projectsmap', function () {
+ $this->app->singleton('phabricator-projectsmap', static function () {
return new ProjectsMapFactory;
});
}
}
diff --git a/app/Providers/ReportServiceProvider.php b/app/Providers/ReportServiceProvider.php
index 6a1666c..47d8a48 100644
--- a/app/Providers/ReportServiceProvider.php
+++ b/app/Providers/ReportServiceProvider.php
@@ -1,40 +1,40 @@
<?php
namespace Nasqueron\Notifications\Providers;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Nasqueron\Notifications\Actions\ActionsReport;
use Nasqueron\Notifications\Events\ReportEvent;
class ReportServiceProvider extends ServiceProvider {
/**
* Registers the application services.
*
* @return void
*/
public function register() {
$this->app->singleton('report', function (Application $app) {
$report = new ActionsReport();
static::listenToActionsForReport(
$report,
$app->make('events')
);
return $report;
});
}
public static function listenToActionsForReport (
ActionsReport $report,
Dispatcher $events
) {
$events->listen(
'Nasqueron\Notifications\Events\ReportEvent',
- function (ReportEvent $event) use ($report) {
+ static function (ReportEvent $event) use ($report) {
$report->addAction($event->action);
}
);
}
}
diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php
index 3df3dde..04507b6 100644
--- a/app/Providers/RouteServiceProvider.php
+++ b/app/Providers/RouteServiceProvider.php
@@ -1,43 +1,41 @@
<?php
namespace Nasqueron\Notifications\Providers;
-use Illuminate\{
- Routing\Router,
- Foundation\Support\Providers\RouteServiceProvider as ServiceProvider
-};
+use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
+use Illuminate\Routing\Router;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'Nasqueron\Notifications\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot() {
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router) {
- $router->group(['namespace' => $this->namespace], function ($router) {
+ $router->group(['namespace' => $this->namespace], static function ($router) {
require app_path('Http/routes.php');
});
}
}
diff --git a/composer.json b/composer.json
index 0679c6b..a2d06da 100644
--- a/composer.json
+++ b/composer.json
@@ -1,60 +1,67 @@
{
"name": "nasqueron/notifications",
"description": "Nasqueron notifications center",
"keywords": [
"nasqueron",
"activemq",
"AMQP",
"notifications"
],
"license": "BSD-2-Clause",
"type": "project",
"require": {
- "php": ">=7.1.0",
- "laravel/framework": "5.3.*",
+ "php": ">=8.1.0",
+ "laravel/framework": "8.*",
"guzzlehttp/guzzle": "^6.2",
"keruald/dockerhub": "^0.0.3",
"keruald/github": "^0.2.1",
"keruald/broker": "^0.4.1",
"keruald/mailgun": "^0.0.1",
"netresearch/jsonmapper": "^1.1.1",
"sentry/sentry": "^0.13.0"
},
"require-dev": {
- "phan/phan": "^3.2.2",
"fzaninotto/faker": "~1.4",
- "mockery/mockery": "0.9.*",
- "pdepend/pdepend": "^2.4.1",
- "phploc/phploc": "^3.0.1",
- "phpmd/phpmd" : "@stable",
- "phpunit/phpunit": "~5.4",
- "phpspec/phpspec": "~2.1",
- "sebastian/phpcpd": "^2.0.4",
- "squizlabs/php_codesniffer": "2.*",
- "symfony/css-selector": "~3.0",
- "symfony/dom-crawler": "~3.0"
+ "laravel/browser-kit-testing": "^v6.3.0",
+ "mockery/mockery": "^1.5.0",
+ "nasqueron/codestyle": "^0.1.0",
+ "pdepend/pdepend": "^2.10",
+ "phan/phan": "^5.3",
+ "sebastian/phpcpd": "6.0.3",
+ "phploc/phploc": "7.0.2",
+ "phpmd/phpmd": "^2.12",
+ "phpspec/phpspec": "^7.2",
+ "phpunit/phpunit": "^9.5.20",
+ "rector/rector": "^0.12.21",
+ "squizlabs/php_codesniffer": "^3.6",
+ "symfony/css-selector": "^6.0",
+ "symfony/dom-crawler": "^6.0"
+
},
"autoload": {
"psr-4": {
"Nasqueron\\Notifications\\": "app/",
"Nasqueron\\Notifications\\Tests\\": "tests/"
}
},
"scripts": {
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
],
"phpmd": [
"vendor/bin/phpmd app/ xml ruleset.xml"
],
"test": [
"phpunit --no-coverage"
]
},
"config": {
- "preferred-install": "dist"
+ "preferred-install": "dist",
+ "allow-plugins": {
+ "kylekatarnls/update-helper": true
+ }
}
}
diff --git a/config/app.php b/config/app.php
index c7226aa..84fd5ac 100644
--- a/config/app.php
+++ b/config/app.php
@@ -1,282 +1,264 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/
'name' => 'Notifications',
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://localhost',
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
/*
|--------------------------------------------------------------------------
| Features
|--------------------------------------------------------------------------
|
| This array contains the features provided by the notifications center.
|
| It allows to toggle a feature on the fly, with a boolean to enable it.
|
*/
'features' => [
// Enable the API entry point at the /gate URL
'Gate' => true,
// Enable the configuration report entry point at the /config URL
'GetConfig' => true,
// Send a response to inform the caller of the different actions done.
// If disabled, send an empty 200 response instead.
'ActionsReport' => true,
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Application Service Providers...
*/
Nasqueron\Notifications\Providers\AppServiceProvider::class,
Nasqueron\Notifications\Providers\BrokerServiceProvider::class,
Nasqueron\Notifications\Providers\DockerHubServiceProvider::class,
Nasqueron\Notifications\Providers\EventServiceProvider::class,
Nasqueron\Notifications\Providers\MailgunServiceProvider::class,
Nasqueron\Notifications\Providers\PhabricatorAPIServiceProvider::class,
Nasqueron\Notifications\Providers\PhabricatorProjectsMapServiceProvider::class,
Nasqueron\Notifications\Providers\ReportServiceProvider::class,
Nasqueron\Notifications\Providers\RouteServiceProvider::class,
Nasqueron\Notifications\Providers\SentryServiceProvider::class,
Nasqueron\Notifications\Providers\ServicesServiceProvider::class
],
- /*
- |--------------------------------------------------------------------------
- | Events listeners
- |--------------------------------------------------------------------------
- |
- | The events listeners listed here will be automatically loaded on the
- | request to your application.
- |
- */
-
- 'listeners' => [
- Nasqueron\Notifications\Listeners\AMQPEventListener::class,
- Nasqueron\Notifications\Listeners\DockerHubListener::class,
- Nasqueron\Notifications\Listeners\LastPayloadSaver::class,
- Nasqueron\Notifications\Listeners\NotificationListener::class,
- Nasqueron\Notifications\Listeners\PhabricatorListener::class,
- ],
-
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
/*
* Laravel Framework aliases...
*/
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
- 'Input' => Illuminate\Support\Facades\Input::class,
+ 'Input' => \Illuminate\Support\Facades\Request::class,
'Inspiring' => Illuminate\Foundation\Inspiring::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
/*
* App aliases...
*/
'Broker' => Nasqueron\Notifications\Facades\Broker::class,
'DockerHub' => Nasqueron\Notifications\Facades\DockerHub::class,
'Mailgun' => Nasqueron\Notifications\Facades\Mailgun::class,
'PhabricatorAPI' => Nasqueron\Notifications\Facades\PhabricatorAPI::class,
'ProjectsMap' => Nasqueron\Notifications\Facades\ProjectsMap::class,
'Raven' => Nasqueron\Notifications\Facades\Raven::class,
'Report' => Nasqueron\Notifications\Facades\Report::class,
'Services' => Nasqueron\Notifications\Facades\Services::class,
],
];
diff --git a/phpcs.xml b/phpcs.xml
new file mode 100644
index 0000000..1f2e61f
--- /dev/null
+++ b/phpcs.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0"?>
+<ruleset name="Nasqueron">
+ <rule ref="vendor/nasqueron/codestyle/CodeSniffer/ruleset.xml" />
+
+ <file>app</file>
+ <file>config</file>
+ <file>tests</file>
+</ruleset>
diff --git a/tests/Actions/AMQPActionTest.php b/tests/Actions/AMQPActionTest.php
index 57a6fe4..938fd6a 100644
--- a/tests/Actions/AMQPActionTest.php
+++ b/tests/Actions/AMQPActionTest.php
@@ -1,25 +1,23 @@
<?php
namespace Nasqueron\Notifications\Tests\Actions;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
use Nasqueron\Notifications\Actions\AMQPAction;
use Nasqueron\Notifications\Tests\TestCase;
class AMQPActionTest extends TestCase {
protected $action;
- public function setUp () {
+ public function setUp (): void {
$this->action = new AMQPAction(
'method',
'target'
);
}
public function testPublicProperties () {
$this->assertNull($this->action->error);
$this->assertSame('AMQPAction', $this->action->action);
}
}
diff --git a/tests/Actions/ActionErrorTest.php b/tests/Actions/ActionErrorTest.php
index b897328..7c23522 100644
--- a/tests/Actions/ActionErrorTest.php
+++ b/tests/Actions/ActionErrorTest.php
@@ -1,23 +1,21 @@
<?php
namespace Nasqueron\Notifications\Tests\Actions;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
use Nasqueron\Notifications\Actions\ActionError;
use Nasqueron\Notifications\Tests\TestCase;
class ActionErrorTest extends TestCase {
protected $actionError;
- public function setUp () {
+ public function setUp () : void {
$ex = new \RuntimeException('Lorem ipsum dolor');
$this->actionError = new ActionError($ex);
}
public function testPublicProperties () {
$this->assertSame('RuntimeException', $this->actionError->type);
$this->assertSame('Lorem ipsum dolor', $this->actionError->message);
}
}
diff --git a/tests/Actions/ActionsReportTest.php b/tests/Actions/ActionsReportTest.php
index 6a86119..5bc04db 100644
--- a/tests/Actions/ActionsReportTest.php
+++ b/tests/Actions/ActionsReportTest.php
@@ -1,63 +1,55 @@
<?php
namespace Nasqueron\Notifications\Tests\Actions;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
use Nasqueron\Notifications\Actions\ActionError;
use Nasqueron\Notifications\Actions\ActionsReport;
use Nasqueron\Notifications\Actions\AMQPAction;
use Nasqueron\Notifications\Tests\TestCase;
class ActionsReportTest extends TestCase {
protected $report;
- public function setUp () {
+ public function setUp (): void {
$this->report = new ActionsReport();
}
public function testReport () {
// Empty report
$this->assertEmpty($this->report->gate);
$this->assertEmpty($this->report->door);
$this->assertFalse($this->report->containsError());
$this->assertSame(0, count($this->report->actions));
// Adds a first action
// Our report should be valid.
$action = new AMQPAction(
'method',
'target'
);
$this->report->addAction($action);
$this->assertSame(1, count($this->report->actions));
$this->assertFalse($this->report->containsError());
// Let's attach an exception to a new action.
// Our report should then be invalid.
$action = new AMQPAction(
'methodWithException',
'target'
);
$ex = new \RuntimeException('Lorem ipsum dolor');
$action->attachError(new ActionError($ex));
$this->report->addAction($action);
$this->assertSame(2, count($this->report->actions));
$this->assertTrue($this->report->containsError());
+ $this->assertIsNumeric($this->report->created);
// Attaches to gate
$this->report->attachToGate('QuuxGate', 'Quuxians');
$this->assertSame('QuuxGate', $this->report->gate);
$this->assertSame('Quuxians', $this->report->door);
-
- // Test rendering
- $actualReport = (string)$this->report;
- $expectedReport = file_get_contents(__DIR__ . '/../data/report.json');
-
- $score = similar_text($expectedReport, $actualReport);
- $this->assertGreaterThan(550, $score, 'data/report.json and rendered report differ too much. Try $this->assertEquals($expectedReport, $actualReport) to see a diff.');
}
}
diff --git a/tests/Actions/NotifyNewCommitsActionTest.php b/tests/Actions/NotifyNewCommitsActionTest.php
index 75e6042..5d2d89b 100644
--- a/tests/Actions/NotifyNewCommitsActionTest.php
+++ b/tests/Actions/NotifyNewCommitsActionTest.php
@@ -1,24 +1,22 @@
<?php
namespace Nasqueron\Notifications\Tests\Actions;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
use Nasqueron\Notifications\Actions\NotifyNewCommitsAction;
use Nasqueron\Notifications\Tests\TestCase;
class NotifyNewCommitsActionTest extends TestCase {
protected $action;
- public function setUp () {
+ public function setUp () : void {
$this->action = new NotifyNewCommitsAction(
'QUUX'
);
}
public function testPublicProperties () {
$this->assertNull($this->action->error);
$this->assertSame('NotifyNewCommitsAction', $this->action->action);
}
}
diff --git a/tests/Actions/TriggerDockerHubBuildActionTest.php b/tests/Actions/TriggerDockerHubBuildActionTest.php
index e03a9a2..6b8cb4a 100644
--- a/tests/Actions/TriggerDockerHubBuildActionTest.php
+++ b/tests/Actions/TriggerDockerHubBuildActionTest.php
@@ -1,25 +1,23 @@
<?php
namespace Nasqueron\Notifications\Tests\Actions;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
use Nasqueron\Notifications\Actions\TriggerDockerHubBuildAction;
use Nasqueron\Notifications\Tests\TestCase;
class TriggerDockerHubBuildActionTest extends TestCase {
protected $action;
- public function setUp () {
+ public function setUp () : void {
$this->action = new TriggerDockerHubBuildAction(
'acme/foo'
);
}
public function testPublicProperties () {
$this->assertNull($this->action->error);
$this->assertSame('acme/foo', $this->action->image);
$this->assertSame('TriggerDockerHubBuildAction', $this->action->action);
}
}
diff --git a/tests/Analyzers/GitHub/Events/CreateEventTest.php b/tests/Analyzers/GitHub/Events/CreateEventTest.php
index 0073cef..9e76151 100644
--- a/tests/Analyzers/GitHub/Events/CreateEventTest.php
+++ b/tests/Analyzers/GitHub/Events/CreateEventTest.php
@@ -1,41 +1,41 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\CreateEvent;
use Nasqueron\Notifications\Tests\TestCase;
+use InvalidArgumentException;
+
class CreateEventTest extends TestCase {
/**
* @var CreateEvent
*/
private $event;
- public function setUp () {
+ public function setUp (): void {
$payload = new \stdClass;
$payload->repository = new \stdClass;
$payload->repository->full_name = 'baxterthehacker/public-repo';
$payload->repository->html_url = 'https://github.com/baxterthehacker/public-repo';
$payload->ref_type = 'bookmark';
$payload->ref = 'quux';
$this->event = new CreateEvent($payload);
parent::setUp();
}
public function testNonExistingRefType () {
$this->assertSame(
"Unknown create reference: bookmark quux",
$this->event->getDescription()
);
}
- /**
- * @expectedException InvalidArgumentException
- */
public function testNonExistingRefTypeLinkException () {
+ $this->expectException(InvalidArgumentException::class);
$this->event->getLink();
}
}
diff --git a/tests/Analyzers/GitHub/Events/DeleteEventTest.php b/tests/Analyzers/GitHub/Events/DeleteEventTest.php
index f8921cb..304fce1 100644
--- a/tests/Analyzers/GitHub/Events/DeleteEventTest.php
+++ b/tests/Analyzers/GitHub/Events/DeleteEventTest.php
@@ -1,41 +1,41 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\DeleteEvent;
use Nasqueron\Notifications\Tests\TestCase;
+use InvalidArgumentException;
+
class DeleteEventTest extends TestCase {
/**
* @var DeleteEvent
*/
private $event;
- public function setUp () {
+ public function setUp (): void {
$payload = new \stdClass;
$payload->repository = new \stdClass;
$payload->repository->full_name = 'baxterthehacker/public-repo';
$payload->repository->html_url = 'https://github.com/baxterthehacker/public-repo';
$payload->ref_type = 'bookmark';
$payload->ref = 'quux';
$this->event = new DeleteEvent($payload);
parent::setUp();
}
public function testNonExistingRefType () {
$this->assertSame(
"Unknown delete reference: bookmark quux",
$this->event->getDescription()
);
}
- /**
- * @expectedException InvalidArgumentException
- */
public function testNonExistingRefTypeLinkException () {
+ $this->expectException(InvalidArgumentException::class);
$this->event->getLink();
}
}
diff --git a/tests/Analyzers/GitHub/Events/EventTest.php b/tests/Analyzers/GitHub/Events/EventTest.php
index 45e7366..1b5e03e 100644
--- a/tests/Analyzers/GitHub/Events/EventTest.php
+++ b/tests/Analyzers/GitHub/Events/EventTest.php
@@ -1,108 +1,108 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\Event;
use Nasqueron\Notifications\Tests\TestCase;
+use InvalidArgumentException;
+
class EventTest extends TestCase {
public function testGetClass () {
$this->assertSame(
'Nasqueron\Notifications\Analyzers\GitHub\Events\CommitCommentEvent',
Event::getClass('commit_comment')
);
}
public function testForPayload () {
$this->assertInstanceOf(
'Nasqueron\Notifications\Analyzers\GitHub\Events\CommitCommentEvent',
Event::forPayload('commit_comment', new \stdClass)
);
}
- /**
- * @expectedException InvalidArgumentException
- */
public function testForPayloadWithException () {
+ $this->expectException(InvalidArgumentException::class);
Event::forPayload('not_existing', new \stdClass);
}
public function testCut () {
$this->assertSame('', Event::cut(''));
$this->assertSame('', Event::cut('', 0));
$this->assertSame('…', Event::cut('Lorem ipsum dolor', 0));
$this->assertSame('Lorem…', Event::cut('Lorem ipsum dolor', 6));
$this->assertSame('Lorem ipsum dolor', Event::cut('Lorem ipsum dolor'));
}
/**
* @dataProvider payloadDescriptionProvider
*/
public function testGetDescriptionAndLink ($eventName,
$expectedDescription,
$expectedLink) {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/$eventName.json";
$payload = json_decode(file_get_contents($filename));
$event = Event::forPayload($eventName, $payload);
$this->assertSame($expectedDescription, $event->getDescription());
$this->assertSame($expectedLink, $event->getLink());
}
public function payloadDescriptionProvider () {
return [
'CommitCommentEvent' => [
'commit_comment',
'baxterthehacker added a comment to 9049f126: This is a really good change! :+1:',
'https://github.com/baxterthehacker/public-repo/commit/9049f1265b7d61be4a8904a9a27120d2064dab3b#commitcomment-11056394'
],
'CreateEvent' => [
'create',
'New tag on baxterthehacker/public-repo: 0.0.1',
'https://github.com/baxterthehacker/public-repo/releases/tag/0.0.1'
],
'DeleteEvent' => [
'delete',
'Removed tag on baxterthehacker/public-repo: simple-tag',
'https://github.com/baxterthehacker/public-repo/tags'
],
'IssueCommentEvent' => [
'issue_comment',
"baxterthehacker added a comment to issue #2 — Spelling error in the README file: You are totally right! I'll get this fixed right away.",
'https://github.com/baxterthehacker/public-repo/issues/2#issuecomment-99262140'
],
'ForkEvent' => [
'fork',
'baxterthehacker/public-repo has been forked to baxterandthehackers/public-repo',
'https://github.com/baxterandthehackers/public-repo'
],
'PullRequestEvent' => [
'pull_request',
'baxterthehacker has opened a pull request: #1 — Update the README with new information',
'https://github.com/baxterthehacker/public-repo/pull/1'
],
'PushEvent' => [
'push',
'baxterthehacker committed Update README.md',
'https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c'
],
'RepositoryEvent' => [
'repository',
'New repository baxterandthehackers/new-repository',
'https://github.com/baxterandthehackers/new-repository'
],
'StatusEvent' => [
'status',
'Status of 9049f126: default — success',
''
],
'WatchEvent' => [
'watch',
'baxterthehacker starred baxterthehacker/public-repo',
'https://github.com/baxterthehacker'
],
];
}
}
diff --git a/tests/Analyzers/GitHub/Events/IssueCommentEventTest.php b/tests/Analyzers/GitHub/Events/IssueCommentEventTest.php
index 6f87c47..73f030c 100644
--- a/tests/Analyzers/GitHub/Events/IssueCommentEventTest.php
+++ b/tests/Analyzers/GitHub/Events/IssueCommentEventTest.php
@@ -1,44 +1,44 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\IssueCommentEvent;
use Nasqueron\Notifications\Tests\TestCase;
class IssueCommentEventTest extends TestCase {
/**
* @var \stdClass
*/
private $payload;
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/issue_comment.json";
$this->payload = json_decode(file_get_contents($filename));
parent::setUp();
}
/**
* @dataProvider payloadDescriptionProvider
*/
public function testWhenRepositoryPerAction ($action, $description) {
$this->payload->action = $action;
$event = new IssueCommentEvent($this->payload);
$this->assertSame($description, $event->getDescription());
}
/**
* Provides actions and descritions for testWhenRepositoryPerAction
*
* See https://developer.github.com/v3/activity/events/types/#issuecommentevent
*/
public function payloadDescriptionProvider () {
return [
['created', "baxterthehacker added a comment to issue #2 — Spelling error in the README file: You are totally right! I'll get this fixed right away."],
['edited', "baxterthehacker edited a comment to issue #2 — Spelling error in the README file: You are totally right! I'll get this fixed right away."],
['deleted', "baxterthehacker deleted a comment to issue #2 — Spelling error in the README file"],
];
}
}
diff --git a/tests/Analyzers/GitHub/Events/PullRequestEventTest.php b/tests/Analyzers/GitHub/Events/PullRequestEventTest.php
index 44602ad..d95d898 100644
--- a/tests/Analyzers/GitHub/Events/PullRequestEventTest.php
+++ b/tests/Analyzers/GitHub/Events/PullRequestEventTest.php
@@ -1,50 +1,50 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\PullRequestEvent;
use Nasqueron\Notifications\Tests\TestCase;
class PullRequestEventTest extends TestCase {
/**
* @var \stdClass
*/
private $payload;
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/pull_request.json";
$this->payload = json_decode(file_get_contents($filename));
parent::setUp();
}
/**
* @dataProvider payloadDescriptionProvider
*/
public function testWhenRepositoryPerAction ($action, $description) {
$this->payload->action = $action;
$event = new PullRequestEvent($this->payload);
$this->assertSame($description, $event->getDescription());
}
/**
* Provides actions and descritions for testWhenRepositoryPerAction
*
* See https://developer.github.com/v3/activity/events/types/#pullrequestevent
*/
public function payloadDescriptionProvider () {
return [
['assigned', "baxterthehacker has assigned the pull request #1 — Update the README with new information to alken-orin"],
['unassigned', "baxterthehacker has edited the assignees from the pull request #1 — Update the README with new information"],
['labeled', "baxterthehacker has labeled the pull request #1 — Update the README with new information"],
['unlabeled', "baxterthehacker has removed a label from the pull request #1 — Update the README with new information"],
['opened', "baxterthehacker has opened a pull request: #1 — Update the README with new information"],
['edited', "baxterthehacker has edited the pull request #1 — Update the README with new information"],
['closed', "baxterthehacker has closed the pull request #1 — Update the README with new information"],
['reopened', "baxterthehacker has reopened the pull request #1 — Update the README with new information"],
['quuxed', "Unknown pull request action: quuxed"],
];
}
}
diff --git a/tests/Analyzers/GitHub/Events/PushEventTest.php b/tests/Analyzers/GitHub/Events/PushEventTest.php
index 1d074ca..6210ab3 100644
--- a/tests/Analyzers/GitHub/Events/PushEventTest.php
+++ b/tests/Analyzers/GitHub/Events/PushEventTest.php
@@ -1,99 +1,99 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\PushEvent;
use Nasqueron\Notifications\Tests\TestCase;
class PushEventTest extends TestCase {
/**
* @var \stdClass[]
*/
private $payloads;
- public function setUp () {
+ public function setUp (): void {
$payloadsToPrepare = [
'0' => 'GitHubPushForceZeroPayload.json',
'1' => 'GitHubEvents/push.json',
'n' => 'GitHubPushSeveralCommitsPayload.json',
];
foreach ($payloadsToPrepare as $key => $filename) {
$filename = __DIR__ . "/../../../data/payloads/" . $filename;
$this->payloads[$key] = json_decode(file_get_contents($filename));
}
parent::setUp();
}
///
/// WithRepoAndBranch trait
///
public function testGetRepositoryAndBranch () {
$this->assertSame("", PushEvent::getRepositoryAndBranch("", "master"));
$this->assertSame("", PushEvent::getRepositoryAndBranch("", "foo"));
$this->assertSame("quux", PushEvent::getRepositoryAndBranch("quux", "master"));
$this->assertSame("quux", PushEvent::getRepositoryAndBranch("quux", "refs/heads/master"));
$this->assertSame("quux", PushEvent::getRepositoryAndBranch("quux", ""));
$this->assertSame("quux (branch foo)", PushEvent::getRepositoryAndBranch("quux", "refs/heads/foo"));
$this->assertSame("quux (branch feature/foo)", PushEvent::getRepositoryAndBranch("quux", "refs/heads/feature/foo"));
$this->assertSame("quux (branch feature/foo)", PushEvent::getRepositoryAndBranch("quux", "feature/foo"));
$this->assertSame("quux (branch foo)", PushEvent::getRepositoryAndBranch("quux", "foo"));
$this->assertSame("quux (branch 0)", PushEvent::getRepositoryAndBranch("quux", "0"));
}
///
/// WithCommit trait
///
public function testGetCommitTitle () {
$this->assertSame("", PushEvent::getCommitTitle(""));
$this->assertSame("Lorem ipsum dolor", PushEvent::getCommitTitle("Lorem ipsum dolor"));
$longCommitMessages = [
"I was born in a water moon. Some people, especially its inhabitants, called it a planet, but as it was only a little over two hundred kilometres in diameter, 'moon' seems the more accurate term. The moon was made entirely of water, by which I mean it was a globe that not only had no land, but no rock either, a sphere with no solid core at all, just liquid water, all the way down to the very centre of the globe.",
"I was born in a water moon. Some people, especially its inhabitants, called it a planet, but as it was only a little over two hundred kilometres in diameter, 'moon' seems the more accurate term. The moon was made entirely of water, by which I mean it was a globe that not only had no land, but no rock either, a sphere with no solid core at all, just liquid water, all the way down to the very centre of the globe.\n\nIf it had been much bigger the moon would have had a core of ice, for water, though supposedly incompressible, is not entirely so, and will change under extremes of pressure to become ice. (If you are used to living on a planet where ice floats on the surface of water, this seems odd and even wrong, but nevertheless it is the case.) The moon was not quite of a size for an ice core to form, and therefore one could, if one was sufficiently hardy, and adequately proof against the water pressure, make one's way down, through the increasing weight of water above, to the very centre of the moon.",
];
$shortCommitTitle = "I was born in a water moon. Some people, especially its inhabitants, ca…";
foreach ($longCommitMessages as $longCommitMessage) {
$this->assertSame(
$shortCommitTitle,
PushEvent::getCommitTitle($longCommitMessage)
);
}
}
public function testWhenTheCommitterAndAuthorAreDifferent () {
$payload = clone $this->payloads['1'];
$payload->head_commit->author->username = "Skrunge";
$event = new PushEvent($payload);
$this->assertSame(
"baxterthehacker committed Update README.md (authored by Skrunge)",
$event->getDescription()
);
}
public function testOnGitPushForce () {
$event = new PushEvent($this->payloads['0']);
$this->assertSame(
"dereckson forcely updated docker-nginx-php-fpm (branch novolume)",
$event->getDescription()
);
- $this->assertContains("compare", $event->getLink());
+ $this->assertStringContainsString("compare", $event->getLink());
}
public function testOnGitPushWithSeveralCommits () {
$event = new PushEvent($this->payloads['n']);
$this->assertSame(
"dereckson pushed 2 commits to notifications",
$event->getDescription()
);
- $this->assertContains("compare", $event->getLink());
+ $this->assertStringContainsString("compare", $event->getLink());
}
}
diff --git a/tests/Analyzers/GitHub/Events/RepositoryEventTest.php b/tests/Analyzers/GitHub/Events/RepositoryEventTest.php
index 3260600..8264894 100644
--- a/tests/Analyzers/GitHub/Events/RepositoryEventTest.php
+++ b/tests/Analyzers/GitHub/Events/RepositoryEventTest.php
@@ -1,72 +1,72 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\RepositoryEvent;
use Nasqueron\Notifications\Tests\TestCase;
class RepositoryEventTest extends TestCase {
/**
* @var \stdClass
*/
private $payload;
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/repository.json";
$this->payload = json_decode(file_get_contents($filename));
parent::setUp();
}
public function testWhenRepositoryIsForked () {
$payload = clone $this->payload;
$payload->repository->fork = true;
$event = new RepositoryEvent($payload);
- $this->assertContains("fork", $event->getDescription());
+ $this->assertStringContainsString("fork", $event->getDescription());
}
public function testWhenRepositoryContainsDescription () {
$payload = clone $this->payload;
$payload->repository->description = "Lorem ipsum dolor";
$event = new RepositoryEvent($payload);
- $this->assertContains("Lorem ipsum dolor", $event->getDescription());
+ $this->assertStringContainsString("Lorem ipsum dolor", $event->getDescription());
}
public function testWhenRepositoryIsForkedAndContainsDescription () {
$payload = clone $this->payload;
$payload->repository->fork = true;
$payload->repository->description = "Lorem ipsum dolor";
$event = new RepositoryEvent($payload);
- $this->assertContains("fork", $event->getDescription());
- $this->assertContains("Lorem ipsum dolor", $event->getDescription());
+ $this->assertStringContainsString("fork", $event->getDescription());
+ $this->assertStringContainsString("Lorem ipsum dolor", $event->getDescription());
}
/**
* @dataProvider payloadDescriptionProvider
*/
public function testWhenRepositoryPerAction ($action, $description) {
$this->payload->action = $action;
$event = new RepositoryEvent($this->payload);
$this->assertSame($description, $event->getDescription());
}
/**
* Provides actions and descritions for testWhenRepositoryPerAction
*
* See https://developer.github.com/v3/activity/events/types/#repositoryevent
*/
public function payloadDescriptionProvider () {
return [
['created', "New repository baxterandthehackers/new-repository"],
['deleted', "Repository baxterandthehackers/new-repository deleted (danger zone)"],
['publicized', "Repository baxterandthehackers/new-repository is now public"],
['privatized', "Repository baxterandthehackers/new-repository is now private"],
['quuxed', "Unknown repository action: quuxed"],
];
}
}
diff --git a/tests/Analyzers/GitHub/Events/StatusEventTest.php b/tests/Analyzers/GitHub/Events/StatusEventTest.php
index 1ef388f..ad2768f 100644
--- a/tests/Analyzers/GitHub/Events/StatusEventTest.php
+++ b/tests/Analyzers/GitHub/Events/StatusEventTest.php
@@ -1,33 +1,33 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\StatusEvent;
use Nasqueron\Notifications\Tests\TestCase;
class StatusEventTest extends TestCase {
/**
* @var \stdClass
*/
private $payload;
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/status.json";
$this->payload = json_decode(file_get_contents($filename));
parent::setUp();
}
public function testWhenStatusContainsUrl () {
$payload = clone $this->payload;
$payload->target_url = "http://www.perdu.com/";
$event = new StatusEvent($payload);
$this->assertSame(
"http://www.perdu.com/",
$event->getLink()
);
}
}
diff --git a/tests/Analyzers/GitHub/Events/UnknownEventTest.php b/tests/Analyzers/GitHub/Events/UnknownEventTest.php
index 21e43a6..9d0cf43 100644
--- a/tests/Analyzers/GitHub/Events/UnknownEventTest.php
+++ b/tests/Analyzers/GitHub/Events/UnknownEventTest.php
@@ -1,28 +1,28 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\GitHub\Events;
use Nasqueron\Notifications\Analyzers\GitHub\Events\UnknownEvent;
use Nasqueron\Notifications\Tests\TestCase;
class UnknownEventTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Analyzers\GitHub\Events\UnknownEvent
*/
private $event;
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . "/../../../data/payloads/GitHubEvents/push.json";
$payload = json_decode(file_get_contents($filename));
$this->event = new UnknownEvent("quux", $payload);
parent::setUp();
}
public function testUnknownEvent () {
$this->assertInstanceOf("Nasqueron\Notifications\Analyzers\GitHub\Events\UnknownEvent", $this->event);
$this->assertSame("Some quux happened", $this->event->getDescription());
$this->assertEmpty($this->event->getLink());
}
}
diff --git a/tests/Analyzers/GitHub/GitHubPayloadAnalyzerTest.php b/tests/Analyzers/GitHub/GitHubPayloadAnalyzerTest.php
index c072e2b..a4b0952 100644
--- a/tests/Analyzers/GitHub/GitHubPayloadAnalyzerTest.php
+++ b/tests/Analyzers/GitHub/GitHubPayloadAnalyzerTest.php
@@ -1,140 +1,134 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers;
use Nasqueron\Notifications\Analyzers\GitHub\GitHubPayloadAnalyzer;
use Nasqueron\Notifications\Tests\TestCase;
class GitHubPayloadAnalyzerTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Analyzers\GitHub\GitHubPayloadAnalyzer
*/
private $unknownEventAnalyzer;
/**
* @var \Nasqueron\Notifications\Analyzers\GitHub\GitHubPayloadAnalyzer
*/
private $pingAnalyzer;
/**
* @var \Nasqueron\Notifications\Analyzers\GitHub\GitHubPayloadAnalyzer
*/
private $pushAnalyzer;
/**
* @var \Nasqueron\Notifications\Analyzers\GitHub\GitHubPayloadAnalyzer
*/
private $pushToMappedRepositoryAnalyzer;
/**
* Prepares the tests
*/
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->unknownEventAnalyzer = new GitHubPayloadAnalyzer(
"Acme", // Expected without known config file
"quux",
new \stdClass
);
$this->pingAnalyzer = new GitHubPayloadAnalyzer(
"Nasqueron", // Expected with known config file
"ping",
new \stdClass
);
$filename = __DIR__ . "/../../data/payloads/GitHubEvents/push.json";
$payloadRawContent = file_get_contents($filename);
$payload = json_decode($payloadRawContent);
$this->pushAnalyzer = new GitHubPayloadAnalyzer(
"Nasqueron", // Expected with known config
"push",
$payload
);
$dockerPayload = json_decode($payloadRawContent);
$dockerPayload->repository->name = "docker-someapp";
$this->pushToMappedRepositoryAnalyzer = new GitHubPayloadAnalyzer(
"Nasqueron", // Expected with known config
"push",
$dockerPayload
);
}
- ///
- /// Test constructor
- ///
-
- /**
- * @expectedException TypeError
- */
- public function testConstructorThrowsAnExceptionWhenPayloadIsInvalid () {
+ public function testConstructorThrowsAnExceptionWhenPayloadIsInvalid() {
+ $this->expectException(\TypeError::class);
new GitHubPayloadAnalyzer(
"Acme",
"push",
"This is not an object deserialized from JSON but a string."
);
}
///
/// Test getConfigurationFileName
///
public function testGetConfigurationFileNameWhenConfigExists () {
$this->assertSame(
"GitHubPayloadAnalyzer/Nasqueron.json",
$this->pingAnalyzer->getConfigurationFileName()
);
}
public function testGetConfigurationFileNameWhenConfigDoesNotExist () {
$this->assertSame(
"GitHubPayloadAnalyzer/default.json",
$this->unknownEventAnalyzer->getConfigurationFileName()
);
}
///
/// Test getItemName
///
public function testGetItemNameWhenEventIsAdministrative () {
$this->assertEmpty($this->pingAnalyzer->getItemName());
}
public function testGetItemNameWhenEventIsRepositoryRelative () {
$this->assertSame("public-repo", $this->pushAnalyzer->getItemName());
}
///
/// Test getGroup
///
public function testGetGroupWhenEventIsAdministrative () {
$this->assertSame("orgz", $this->pingAnalyzer->getGroup());
}
public function testGetGroupOnPushToMappedRepository () {
$this->assertSame("docker", $this->pushToMappedRepositoryAnalyzer->getGroup());
}
public function testGetGroupOnPushToNotMappedRepository () {
$this->assertSame("nasqueron", $this->pushAnalyzer->getGroup());
}
///
/// Test if our fallback is correct when the GitHub event type is unknown
///
public function testDescriptionContainsTypeWhenEventTypeIsUnknown () {
- $this->assertContains(
+ $this->assertStringContainsString(
"quux",
$this->unknownEventAnalyzer->getDescription()
);
}
}
diff --git a/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerConfigurationTest.php b/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerConfigurationTest.php
index 8ecfd66..e9b0096 100644
--- a/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerConfigurationTest.php
+++ b/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerConfigurationTest.php
@@ -1,62 +1,60 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
-use Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzerConfiguration;
use Nasqueron\Notifications\Analyzers\ItemGroupMapping;
+use Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzerConfiguration;
use Nasqueron\Notifications\Tests\TestCase;
class JenkinsPayloadAnalyzerConfigurationTest extends TestCase {
/**
* Configuration
*
* @var \Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzerConfiguration
*/
protected $configuration;
/**
* Prepares the test
*/
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . '/../../data/JenkinsPayloadAnalyzer/Nasqueron.json';
$mapper = new \JsonMapper();
$this->configuration = $mapper->map(
json_decode(file_get_contents($filename)),
new JenkinsPayloadAnalyzerConfiguration('Nasqueron')
);
parent::setUp();
}
/**
* Determines the JSON object is well parsed
*/
public function testProperties () {
$this->assertSame("ci", $this->configuration->defaultGroup);
foreach ($this->configuration->map as $item) {
$this->assertInstanceOf(ItemGroupMapping::class, $item);
}
}
///
/// Tests for getDefaultGroup
///
public function testGetDefaultGroup () {
$this->configuration->defaultGroup = "quux";
$this->assertSame("quux", $this->configuration->getDefaultGroup());
}
public function testGetDefaultGroupWhenNotInConfig () {
$this->configuration->defaultGroup = "";
$this->assertSame("nasqueron", $this->configuration->getDefaultGroup());
$this->configuration->defaultGroup = null;
$this->assertSame("nasqueron", $this->configuration->getDefaultGroup());
}
}
diff --git a/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerTest.php b/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerTest.php
index 111a3b2..d639404 100644
--- a/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerTest.php
+++ b/tests/Analyzers/Jenkins/JenkinsPayloadAnalyzerTest.php
@@ -1,78 +1,77 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers;
use Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzer;
-use Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzerConfiguration;
use Nasqueron\Notifications\Tests\TestCase;
class JenkinsPayloadAnalyzerTest extends TestCase {
/**
* Jenkins analyzer to a successful build
*
* @var \Nasqueron\Notifications\Analyzers\Jenkins\JenkinsPayloadAnalyzer
*/
protected $analyzer;
/**
* @var \stdClass
*/
protected $payload;
/**
* Prepares the test
*/
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$filename = __DIR__ . '/../../data/payloads/JenkinsToIgnorePayload.json';
$this->payload = json_decode(file_get_contents($filename));
$this->analyzer = new JenkinsPayloadAnalyzer("Nasqueron", $this->payload);
}
public function testGetItemName () {
$this->assertSame("test-prod-env", $this->analyzer->getItemName());
}
public function testGetGroup () {
$this->assertSame("ops", $this->analyzer->getGroup());
}
public function testGetGroupWhenWeNeedDefaultFallback () {
$this->payload->name = "quux";
$this->assertSame("ci", $this->analyzer->getGroup());
}
public function testShouldNotifyWhenStatusIsUndefined () {
unset($this->payload->build->status);
$this->assertFalse($this->analyzer->shouldNotify());
}
/**
* @dataProvider payloadStatusProvider
*/
- public function testShouldNotifyByStatus ($status, $shouldNotify) {
+ public function testShouldNotifyByStatus(string $status, bool $shouldNotify) {
$this->payload->build->status = $status;
$this->assertSame($shouldNotify, $this->analyzer->shouldNotify());
}
/**
* Provides data for testShouldNotifyByStatus
*
* @return array
*/
public function payloadStatusProvider () {
return [
// Build status to notify
["FAILURE", true],
["ABORTED", true],
["UNSTABLE", true],
// Build status to ignore
["SUCCESS", false],
["NOT_BUILT", false],
];
}
}
diff --git a/tests/Analyzers/PayloadAnalyzerConfigurationTest.php b/tests/Analyzers/PayloadAnalyzerConfigurationTest.php
index 12725a0..10fdf5a 100644
--- a/tests/Analyzers/PayloadAnalyzerConfigurationTest.php
+++ b/tests/Analyzers/PayloadAnalyzerConfigurationTest.php
@@ -1,63 +1,61 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-
-use Nasqueron\Notifications\Analyzers\PayloadAnalyzerConfiguration;
use Nasqueron\Notifications\Analyzers\ItemGroupMapping;
+use Nasqueron\Notifications\Analyzers\PayloadAnalyzerConfiguration;
use Nasqueron\Notifications\Tests\TestCase;
class PayloadAnalyzerConfigurationTest extends TestCase {
/**
* Configuration
*
* @var \Nasqueron\Notifications\Analyzers\PayloadAnalyzerConfiguration
*/
protected $configuration;
/**
* Prepares the test
*/
- public function setUp () {
+ public function setUp (): void {
$filename = __DIR__ . '/../data/GitHubPayloadAnalyzer/Nasqueron.json';
$mapper = new \JsonMapper();
$this->configuration = $mapper->map(
json_decode(file_get_contents($filename)),
new PayloadAnalyzerConfiguration('Nasqueron')
);
parent::setUp();
}
/**
* Determines the JSON object is well parsed
*/
public function testProperties () {
$this->assertSame("orgz", $this->configuration->administrativeGroup);
$this->assertSame("nasqueron", $this->configuration->defaultGroup);
foreach ($this->configuration->map as $item) {
$this->assertInstanceOf(ItemGroupMapping::class, $item);
}
}
///
/// Tests for getDefaultGroup
///
public function testGetDefaultGroup () {
$this->configuration->defaultGroup = "quux";
$this->assertSame("quux", $this->configuration->getDefaultGroup());
}
public function testGetDefaultGroupWhenNotInConfig () {
$this->configuration->defaultGroup = "";
$this->assertSame("nasqueron", $this->configuration->getDefaultGroup());
$this->configuration->defaultGroup = null;
$this->assertSame("nasqueron", $this->configuration->getDefaultGroup());
}
}
diff --git a/tests/Analyzers/Phabricator/PhabricatorGroupMappingTest.php b/tests/Analyzers/Phabricator/PhabricatorGroupMappingTest.php
index ec01e40..fa0e9ca 100644
--- a/tests/Analyzers/Phabricator/PhabricatorGroupMappingTest.php
+++ b/tests/Analyzers/Phabricator/PhabricatorGroupMappingTest.php
@@ -1,90 +1,90 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\Phabricator;
use Nasqueron\Notifications\Analyzers\Phabricator\PhabricatorGroupMapping;
use Nasqueron\Notifications\Tests\TestCase;
class PhabricatorGroupMappingTest extends TestCase {
use WithConfiguration;
/**
* @var PhabricatorGroupMapping|]
*/
private $mappings;
/**
* @var PhabricatorStory
*/
private $story;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$config = $this->getPhabricatorPayloadAnalyzerConfiguration();
$keys = [
'projects',
'words',
'strongWords',
];
$this->mappings = array_combine($keys, $config->map);
$this->story = $this->getStory();
}
///
/// Tests
///
public function testDoesProjectBelong () {
$mapping = $this->mappings['projects'];
$this->assertFalse(
$mapping->doesItemBelong("")
);
$this->assertFalse(
$mapping->doesItemBelong("Tasacora")
);
$this->assertTrue(
$mapping->doesItemBelong("Docker images")
);
$this->assertFalse(
$mapping->doesItemBelong("Docker")
);
$this->assertFalse(
$mapping->doesItemBelong("Docker images quux")
);
}
public function testDoesStoryBelong () {
$mapping = $this->mappings['words'];
$this->assertFalse(
$mapping->doesStoryBelong($this->story)
);
$this->story->text = "Review the cartography elements.";
$this->assertTrue(
$mapping->doesStoryBelong($this->story)
);
}
/**
* Test to fix T773
*/
public function testDoesStoryBelongWhenWordIsInAnotherCase () {
$mapping = $this->mappings['words'];
$this->story->text = "Review the Cartography elements.";
$this->assertTrue(
$mapping->doesStoryBelong($this->story)
);
}
}
diff --git a/tests/Analyzers/Phabricator/PhabricatorPayloadAnalyzerTest.php b/tests/Analyzers/Phabricator/PhabricatorPayloadAnalyzerTest.php
index 0e11951..370a996 100644
--- a/tests/Analyzers/Phabricator/PhabricatorPayloadAnalyzerTest.php
+++ b/tests/Analyzers/Phabricator/PhabricatorPayloadAnalyzerTest.php
@@ -1,96 +1,94 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\Phabricator;
use Nasqueron\Notifications\Analyzers\Phabricator\PhabricatorPayloadAnalyzer;
use Nasqueron\Notifications\Tests\TestCase;
class PhabricatorPayloadAnalyzerTest extends TestCase {
use WithConfiguration;
/**
* @var PhabricatorPayloadAnalyzer
*/
private $analyzer;
/**
* @var PhabricatorStory
*/
private $story;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->story = $this->getStory();
$this->analyzer = new PhabricatorPayloadAnalyzer(
"Nasqueron",
$this->story
);
}
public function testGetConfigurationFileName () {
$this->assertSame(
"PhabricatorPayloadAnalyzer/Nasqueron.json",
$this->analyzer->getConfigurationFileName()
);
}
public function testGetGroupWhereEventIsAdministrative () {
$this->markTestIncomplete(
"Not yet implemented feature. See T664."
);
$this->assertSame(
"orgz",
$this->analyzer->getGroup()
);
}
public function testGetGroupWhereStoryDoesntMatchAnything () {
$this->attachProjectsToStoryMock($this->story, []);
$this->assertSame(
"nasqueron",
$this->analyzer->getGroup()
);
}
public function testGetGroupWhereStoryMatchesProject () {
$this->attachProjectsToStoryMock($this->story, ['Docker images']);
$this->assertSame(
"docker",
$this->analyzer->getGroup()
);
}
public function testGetGroupWhereStoryMatchesWords () {
$this->attachProjectsToStoryMock($this->story, []);
$this->story->text = "Review the cartography elements.";
$this->assertSame(
"tasacora",
$this->analyzer->getGroup()
);
}
public function testGetGroupWhereWordsAreStrong () {
$this->markTestIncomplete(
"Not yet implemented feature. See T748."
);
$this->attachProjectsToStoryMock($this->story, ['Docker images']);
$this->story->text = "Review the cartography elements on Dwellers.";
$this->assertSame(
"ops",
$this->analyzer->getGroup()
);
}
- /**
- * @expectedException \BadMethodCallException
- */
- public function testGetItemThrowsBadMethodCallException () {
+ public function testGetItemThrowsBadMethodCallException() {
+ $this->expectException(\BadMethodCallException::class);
$this->analyzer->getItemName();
}
}
diff --git a/tests/Analyzers/Phabricator/WithConfiguration.php b/tests/Analyzers/Phabricator/WithConfiguration.php
index a91e7ca..a6c86bb 100644
--- a/tests/Analyzers/Phabricator/WithConfiguration.php
+++ b/tests/Analyzers/Phabricator/WithConfiguration.php
@@ -1,36 +1,35 @@
<?php
namespace Nasqueron\Notifications\Tests\Analyzers\Phabricator;
use Nasqueron\Notifications\Analyzers\Phabricator\PhabricatorPayloadAnalyzerConfiguration;
-use Nasqueron\Notifications\Phabricator\PhabricatorStory;
/**
* Helper methods to construct needed objects
*/
trait WithConfiguration {
private function getPhabricatorPayloadAnalyzerConfiguration () {
$filename = __DIR__ . '/../../data/PhabricatorPayloadAnalyzer/Nasqueron.json';
$mapper = new \JsonMapper();
return $mapper->map(
json_decode(file_get_contents($filename)),
new PhabricatorPayloadAnalyzerConfiguration('Nasqueron')
);
}
private function getStory() {
return $this
->getMockBuilder("Nasqueron\Notifications\Phabricator\PhabricatorStory")
->setConstructorArgs(["Acme"])
->getMock();
}
private function attachProjectsToStoryMock ($mock, $projects) {
$mock
->expects($this->any())
->method("getProjects")
->will($this->returnValue($projects));
}
}
diff --git a/tests/Config/FeaturesTest.php b/tests/Config/FeaturesTest.php
index 38f795b..71e767a 100644
--- a/tests/Config/FeaturesTest.php
+++ b/tests/Config/FeaturesTest.php
@@ -1,30 +1,30 @@
<?php
namespace Nasqueron\Notifications\Tests\Config;
use Nasqueron\Notifications\Config\Features;
use Nasqueron\Notifications\Tests\TestCase;
class FeaturesTest extends TestCase {
public function testEnable () {
// Find it (en vain …)
$this->assertNotContains('Quux', Features::getEnabled());
$this->assertFalse(Features::isEnabled('Quux'));
// Enable it
Features::enable('Quux');
$this->assertTrue(Features::isEnabled('Quux'));
$this->assertContains('Quux', Features::getEnabled());
// Disable it
Features::disable('Quux');
$this->assertFalse(Features::isEnabled('Quux'));
// Count it
- $this->assertContains('Quux', Features::getAll());
+ $this->assertArrayHasKey('Quux', Features::getAll());
$this->assertContains('Quux', Features::getAvailable());
$this->assertNotContains('Quux', Features::getEnabled());
}
}
diff --git a/tests/Config/Reporting/FeatureReportEntryTest.php b/tests/Config/Reporting/FeatureReportEntryTest.php
index 2730d95..28f04d7 100644
--- a/tests/Config/Reporting/FeatureReportEntryTest.php
+++ b/tests/Config/Reporting/FeatureReportEntryTest.php
@@ -1,48 +1,48 @@
<?php
namespace Nasqueron\Notifications\Tests\Config\Reporting;
use Nasqueron\Notifications\Config\Reporting\FeatureReportEntry;
use Nasqueron\Notifications\Tests\TestCase;
class FeatureReportEntryTest extends TestCase {
/**
* @var FeatureReportEntry
*/
private $enabledFeatureEntry;
/**
* @var FeatureReportEntry
*/
private $disabledFeatureEntry;
- public function setUp () {
+ public function setUp (): void {
$this->enabledFeatureEntry = new FeatureReportEntry("foo", true);
$this->disabledFeatureEntry = new FeatureReportEntry("bar", false);
}
public function testToArray() {
$this->assertSame(
["foo", (string)true],
$this->enabledFeatureEntry->toArray()
);
$this->assertSame(
["bar", (string)false],
$this->disabledFeatureEntry->toArray()
);
}
public function testToFancyArray() {
$this->assertSame(
["foo", "✓"],
$this->enabledFeatureEntry->toFancyArray()
);
$this->assertSame(
["bar", ""],
$this->disabledFeatureEntry->toFancyArray()
);
}
}
diff --git a/tests/Config/Reporting/IntegrationTest.php b/tests/Config/Reporting/IntegrationTest.php
index 5001221..55d4792 100644
--- a/tests/Config/Reporting/IntegrationTest.php
+++ b/tests/Config/Reporting/IntegrationTest.php
@@ -1,32 +1,32 @@
<?php
namespace Nasqueron\Notifications\Tests\Config\Reporting;
use Nasqueron\Notifications\Tests\TestCase;
class IntegrationTest extends TestCase {
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->mockServices()
->shouldReceive('get')
->once()
->andReturn([]); // No service
}
/**
* Config works.
*/
public function testConfig() {
$json = $this->get('/config')
->response
->getContent();
$this->assertJsonStringEqualsJsonFile(
__DIR__ . "/../../data/config.json",
$json
);
}
}
diff --git a/tests/Config/Reporting/ServiceReportEntryTest.php b/tests/Config/Reporting/ServiceReportEntryTest.php
index e536293..d99956d 100644
--- a/tests/Config/Reporting/ServiceReportEntryTest.php
+++ b/tests/Config/Reporting/ServiceReportEntryTest.php
@@ -1,35 +1,34 @@
<?php
namespace Nasqueron\Notifications\Tests\Config\Reporting;
use Nasqueron\Notifications\Config\Reporting\ServiceReportEntry;
-use Nasqueron\Notifications\Config\Services\Service;
use Nasqueron\Notifications\Tests\TestCase;
class ServiceReportEntryTest extends TestCase {
/**
* @var ServiceReportEntry
*/
private $serviceEntry;
- public function setUp () {
+ public function setUp (): void {
$service = $this->mockService();
$this->serviceEntry = new ServiceReportEntry($service);
}
public function testToArray() {
$this->assertSame(
["Storm", "Acme", "http://www.perdu.com", ""],
$this->serviceEntry->toArray()
);
}
public function testToFancyArray() {
$this->assertSame(
["Storm", "Acme", "http://www.perdu.com", "✓"],
$this->serviceEntry->toFancyArray()
);
}
}
diff --git a/tests/Config/Services/ServiceTest.php b/tests/Config/Services/ServiceTest.php
index eeff34b..59a07eb 100644
--- a/tests/Config/Services/ServiceTest.php
+++ b/tests/Config/Services/ServiceTest.php
@@ -1,45 +1,45 @@
<?php
namespace Nasqueron\Notifications\Tests\Config\Services;
use Nasqueron\Notifications\Config\Services\Service;
use Nasqueron\Notifications\Tests\TestCase;
class ServiceTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Config\Services\Service
*/
private $serviceWithInstance;
/**
* @var \Nasqueron\Notifications\Config\Services\Service
*/
private $serviceWithoutInstance;
- public function setUp () {
+ public function setUp (): void {
$this->serviceWithoutInstance = new Service();
$this->serviceWithInstance = clone $this->serviceWithoutInstance;
$this->serviceWithInstance->instance = "http://www.perdu.com";
}
///
/// Tests for getInstanceName()
///
public function testGetInstanceName () {
$this->assertSame(
"http://www.perdu.com",
$this->serviceWithInstance->getInstanceName()
);
}
public function testGetInstanceNameWhenThereIsNoInstance () {
$this->assertSame(
"ø",
$this->serviceWithoutInstance->getInstanceName()
);
}
}
diff --git a/tests/Config/Services/ServicesTest.php b/tests/Config/Services/ServicesTest.php
index ecb5901..834ea91 100644
--- a/tests/Config/Services/ServicesTest.php
+++ b/tests/Config/Services/ServicesTest.php
@@ -1,90 +1,90 @@
<?php
namespace Nasqueron\Notifications\Tests\Config\Services;
use Nasqueron\Notifications\Config\Services\Services;
use Nasqueron\Notifications\Tests\TestCase;
class ServicesTest extends TestCase {
private $services;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->services = Services::loadFromJson('credentials.json');
}
public function testGet () {
$actualServices = $this->services->get();
$this->assertGreaterThan(0, $actualServices);
$this->assertSame(
$this->services->services, // This is public, so testable
$actualServices
);
foreach ($actualServices as $service) {
$this->assertInstanceOf(
'Nasqueron\Notifications\Config\Services\Service',
$service
);
}
}
public function testGetForGate () {
$actualServices = $this->services->getForGate('GitHub');
$this->assertGreaterThan(0, $actualServices);
foreach ($actualServices as $service) {
$this->assertInstanceOf(
'Nasqueron\Notifications\Config\Services\Service',
$service
);
$this->assertSame('GitHub', $service->gate);
}
}
public function testFindServiceByDoor () {
// Search gives a result
$service = $this->services->findServiceByDoor('GitHub', 'Acme');
$this->assertInstanceOf(
'Nasqueron\Notifications\Config\Services\Service',
$service
);
$this->assertSame('GitHub', $service->gate);
$this->assertSame('Acme', $service->door);
// Search doesn't give any result
$service = $this->services->findServiceByDoor('GitHub', 'Quux');
$this->assertNull($service);
}
public function testFindServiceByProperty () {
// Search gives a result
$service = $this->services->findServiceByProperty(
'Phabricator',
'instance',
'https://phabricator.acme.tld'
);
$this->assertInstanceOf(
'Nasqueron\Notifications\Config\Services\Service',
$service
);
$this->assertSame('Phabricator', $service->gate);
$this->assertSame('Acme', $service->door);
// Search doesn't give any result
$service = $this->services->findServiceByProperty(
'Phabricator',
'instance',
'https://notfound.acme.tld'
);
$this->assertNull($service);
}
}
diff --git a/tests/Console/Commands/ConfigShowTest.php b/tests/Console/Commands/ConfigShowTest.php
index d7e03c2..9d437f8 100644
--- a/tests/Console/Commands/ConfigShowTest.php
+++ b/tests/Console/Commands/ConfigShowTest.php
@@ -1,105 +1,103 @@
<?php
namespace Nasqueron\Notifications\Tests\Console\Commands;
use Nasqueron\Notifications\Config\Features;
-use Nasqueron\Notifications\Config\Services\Service;
-
use Mockery;
class ConfigShowTest extends TestCase {
/**
* @var string
*/
protected $class = 'Nasqueron\Notifications\Console\Commands\ConfigShow';
/**
* Nasqueron\Notifications\Config\Services\Services
*/
private $servicesMock;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->servicesMock = $this->mockServices();
}
public function testRegularExecute () {
//Our command calls Services::get()
$this->servicesMock->shouldReceive('get')->once()->andReturn([]);
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay('/Gates/');
$this->assertRegexpInDisplay('/Features/');
$this->assertRegexpInDisplay('/Services declared/');
}
public function testRegularExecuteWithService () {
$service = $this->mockService();
$this->servicesMock
->shouldReceive('get')
->once()
->andReturn([$service]);
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay('/Storm/');
}
public function testRegularExecuteWithPhabricatorService () {
$this->mockPhabricatorAPIForProjectsMap();
$service = $this->mockService('Phabricator');
$this->servicesMock
->shouldReceive('get')
->once()
->andReturn([$service]);
$this->servicesMock
->shouldReceive('findServiceByProperty');
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay(
'/Phabricator.*Projects map not cached./'
);
}
protected function mockProjectsMap () {
$mock = Mockery::mock(
'Nasqueron\Notifications\Phabricator\ProjectsMap'
);
$this->app->instance('phabricator-projectsmap', $mock);
return $mock;
}
public function testRegularExecuteWithPhabricatorServiceWhenTheProjectsMapIsCached () {
// The services list will return only one, for the Phabricator gate.
$service = $this->mockService('Phabricator');
$this->servicesMock
->shouldReceive('get')->once()->andReturn([$service]);
// The project map (built by the factory) will say it's cached.
$this->mockProjectsMap()
->shouldReceive('fetch->isCached')->once()->andReturn(true);
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay('/Phabricator.*✓/');
}
public function testExecuteWhenSomeFeatureIsDisabled () {
Features::disable('ActionsReport');
$this->servicesMock->shouldReceive('get')->once()->andReturn([]);
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay(
'/Gate *\| *✓ *\|/'
);
$this->assertRegexpInDisplay(
'/ActionsReport *\| *\|/'
);
}
}
diff --git a/tests/Console/Commands/ConfigValidateTest.php b/tests/Console/Commands/ConfigValidateTest.php
index bc6231e..10626bc 100644
--- a/tests/Console/Commands/ConfigValidateTest.php
+++ b/tests/Console/Commands/ConfigValidateTest.php
@@ -1,60 +1,60 @@
<?php
namespace Nasqueron\Notifications\Tests\Console\Commands;
-use Storage;
+use Illuminate\Support\Facades\Storage;
class ConfigValidateTest extends TestCase {
/**
* @var string
*/
protected $class = 'Nasqueron\Notifications\Console\Commands\ConfigValidate';
const TEST_FILE = 'bug.json';
public function testRegularExecute () {
$this->tester->execute(['command' => $this->command->getName()]);
// When all files are valid, nothing is displayed
$this->assertEquals('', $this->tester->getDisplay());
}
/**
* @dataProvider provideErrors
*/
public function testSyntaxErrorExecute (string $content, string $error) {
$this->populateTestFile($content); // Not JSON
$this->tester->execute(['command' => $this->command->getName()]);
// When all files are valid, nothing is displayed
$this->assertRegexpInDisplay("/$error/");
}
/**
* Provides invalid JSON strings and associated error
*/
public function provideErrors () : array {
return [
["lorem ipsum dolor", "Syntax error"],
['{"}', "Control character error"]
];
}
private function populateTestFile (string $content) : void {
Storage::disk('local')->put(self::TEST_FILE, $content);
}
private function deleteTestFile () : void {
$fs = Storage::disk('local');
if ($fs->exists(self::TEST_FILE)) {
$fs->delete(self::TEST_FILE);
}
}
- public function tearDown () {
+ public function tearDown () : void {
$this->deleteTestFile();
parent::tearDown();
}
}
diff --git a/tests/Console/Commands/NotificationsPayloadTest.php b/tests/Console/Commands/NotificationsPayloadTest.php
index d415fc7..7177941 100644
--- a/tests/Console/Commands/NotificationsPayloadTest.php
+++ b/tests/Console/Commands/NotificationsPayloadTest.php
@@ -1,86 +1,84 @@
<?php
namespace Nasqueron\Notifications\Tests\Console\Commands;
use Nasqueron\Notifications\Console\Commands\NotificationsPayload;
class NotificationsPayloadTest extends TestCase {
/**
* @var string
*/
protected $class = NotificationsPayload::class;
public function testRegularExecute () {
$path = __DIR__ . '/../../data/payloads/DockerHubPushPayload.json';
$this->tester->execute([
'command' => $this->command->getName(),
'service' => 'DockerHub',
'payload' => $path,
'args' => [
'Acme',
'push'
],
]);
$this->assertDisplayContains('"service": "DockerHub"');
$this->assertDisplayContains('"project": "Acme"');
$this->assertDisplayContains('svendowideit\/testhook');
}
public function testPhabricatorPayload () {
$path = __DIR__ . '/../../data/payloads/PhabricatorPastePayload.json';
$this->tester->execute([
'command' => $this->command->getName(),
'service' => 'Phabricator',
'payload' => $path,
'args' => [
'Acme',
],
]);
$this->assertDisplayContains('"service": "Phabricator"');
$this->assertDisplayContains('"project": "Acme"');
$this->assertDisplayContains('"type": "PSTE"');
}
- /**
- * @expectedException InvalidArgumentException
- */
- public function testArgumentsArrayCombine () {
+ public function testArgumentsArrayCombine() {
+ $this->expectException(\InvalidArgumentException::class);
NotificationsPayload::argumentsArrayCombine(['foo'], []);
}
public function testFileNotFound () {
$this->tester->execute([
'command' => $this->command->getName(),
'service' => 'DockerHub',
'payload' => "/tmp/not.found",
'args' => [
'Acme',
'push'
],
]);
$this->assertDisplayContains('File not found: /tmp/not.found');
}
public function testServiceNotFound () {
$path = __DIR__ . '/../../data/payloads/DockerHubPushPayload.json';
$this->tester->execute([
'command' => $this->command->getName(),
'service' => 'InterdimensionalTeleport',
'payload' => $path,
'args' => [
'Acme',
'push'
],
]);
$this->assertDisplayContains(
'Unknown service: InterdimensionalTeleport'
);
}
}
diff --git a/tests/Console/Commands/PhabricatorProjectsMapTest.php b/tests/Console/Commands/PhabricatorProjectsMapTest.php
index 2f10021..3bc2e46 100644
--- a/tests/Console/Commands/PhabricatorProjectsMapTest.php
+++ b/tests/Console/Commands/PhabricatorProjectsMapTest.php
@@ -1,34 +1,33 @@
<?php
namespace Nasqueron\Notifications\Tests\Console\Commands;
-use Nasqueron\Notifications\Config\Services\Service;
use Nasqueron\Notifications\Console\Commands\PhabricatorProjectsMap;
class PhabricatorProjectsMapTest extends TestCase {
/**
* @var string
*/
protected $class = PhabricatorProjectsMap::class;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$service = $this->mockService('Phabricator');
$this->mockServices()
->shouldReceive('getForGate')
->once()
->andReturn([$service]);
$this->mockPhabricatorAPIForProjectsMap();
}
public function testRegularExecute () {
$this->tester->execute(['command' => $this->command->getName()]);
$this->assertRegexpInDisplay('/PHID.*Project name/');
$this->assertRegexpInDisplay(
'/PHID-PROJ-cztcgpvqr6smnnekotq7.*Agora/'
);
}
}
diff --git a/tests/Console/Commands/TestCase.php b/tests/Console/Commands/TestCase.php
index 79f81a8..fe3ac60 100644
--- a/tests/Console/Commands/TestCase.php
+++ b/tests/Console/Commands/TestCase.php
@@ -1,52 +1,49 @@
<?php
namespace Nasqueron\Notifications\Tests\Console\Commands;
-use Nasqueron\Notifications\Config\Services\Service;
use Nasqueron\Notifications\Tests\TestCase as BaseTestCase;
use Illuminate\Contracts\Console\Kernel;
use Symfony\Component\Console\Tester\CommandTester;
-use Mockery;
-
class TestCase extends BaseTestCase {
///
/// Commands test environment
///
/**
* @var Symfony\Component\Console\Command
*/
protected $command;
/**
* @var Symfony\Component\Console\Tester\CommandTester;
*/
protected $tester;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$kernel = $this->app->make(Kernel::class);
$this->command = $kernel->getByClass($this->class);
$this->tester = new CommandTester($this->command);
}
///
/// Display assertions
///
public function assertDisplayContains(string $expectedNeedle) {
- $this->assertContains(
+ $this->assertStringContainsString(
$expectedNeedle,
$this->tester->getDisplay()
);
}
public function assertRegexpInDisplay (string $pattern) {
- $this->assertRegexp($pattern, $this->tester->getDisplay());
+ $this->assertMatchesRegularExpression($pattern, $this->tester->getDisplay());
}
}
diff --git a/tests/Console/KernelTest.php b/tests/Console/KernelTest.php
index af4c756..baab04e 100644
--- a/tests/Console/KernelTest.php
+++ b/tests/Console/KernelTest.php
@@ -1,125 +1,118 @@
<?php
namespace Nasqueron\Notifications\Tests\Console;
use Nasqueron\Notifications\Tests\TestCase;
-use Nasqueron\Notifications\Console\Kernel;
use Illuminate\Contracts\Console\Kernel as BaseKernel;
-
-use Artisan;
-use File;
+use Illuminate\Support\Facades\File;
class KernelTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Console\Kernel
*/
private $kernel;
/**
* The actual list of services providers
*
* @var string[]
*/
private $commands;
/**
* The service providers' namespace
*
* @var string
*/
private $namespace;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->kernel = $this->app->make(BaseKernel::class);
$this->commands = $this->kernel->all();
$this->namespace = $this->app->getInstance()->getNamespace()
. 'Console\\Commands\\';
}
public function testOmittedFiles () {
$files = File::allFiles(app_path('Console/Commands'));
foreach ($files as $file) {
$class = $this->namespace . $file->getBasename('.php');
$this->assertArrayContainsInstanceOf(
$class,
$this->commands,
"The class $class should be added to app/Console/Kernel.php."
);
}
}
public function testGet () {
$this->assertInstanceOf(
\Nasqueron\Notifications\Console\Commands\Inspire::class,
$this->kernel->get('inspire')
);
}
- /**
- * @expectedException \RuntimeException
- */
- public function testGetWhenCommandDoesNotExist () {
+ public function testGetWhenCommandDoesNotExist() {
+ $this->expectException(\RuntimeException::class);
$this->kernel->get('notexisting');
}
public function testGetByClass () {
$class = \Nasqueron\Notifications\Console\Commands\Inspire::class;
$this->assertInstanceOf($class, $this->kernel->getByClass($class));
}
- /**
- * @expectedException \RuntimeException
- */
- public function testGetByClassWhenCommandDoesNotExist () {
+ public function testGetByClassWhenCommandDoesNotExist() {
+ $this->expectException(\RuntimeException::class);
$this->kernel->getByClass('notexisting');
}
///
/// Custom assertions
///
/**
* Asserts the specified array contains an element of an expected type.
*
* @param mixed $expectedType The type to find among the array elements
* @param array $haystack The array where to find
* @param string $message The test message
*/
public static function assertArrayContainsInstanceOf (
$expectedType,
$haystack,
$message = ''
) {
self::assertThat(
self::arrayContainsInstanceOf($expectedType, $haystack),
self::isTrue(),
$message
);
}
/**
* Determines if the specified array contains at least one instance of the
* specified type.
*
* @param mixed $expectedType The type to find among the array elements
* @param array $haystack The array where to find
* @return bool
*/
protected static function arrayContainsInstanceOf (
$expectedType,
$haystack
) {
foreach ($haystack as $item) {
if ($item instanceof $expectedType) {
return true;
}
}
return false;
}
}
diff --git a/tests/Exceptions/HandlerTest.php b/tests/Exceptions/HandlerTest.php
index ba60a36..3fb9170 100644
--- a/tests/Exceptions/HandlerTest.php
+++ b/tests/Exceptions/HandlerTest.php
@@ -1,53 +1,52 @@
<?php
namespace Nasqueron\Notifications\Tests\Exceptions;
-use Illuminate\Auth\Access\AuthorizationException;
use Nasqueron\Notifications\Exceptions\Handler;
use Nasqueron\Notifications\Tests\TestCase;
-use App;
-use Config;
+use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Support\Facades\Config;
use Mockery;
class HandlerTest extends TestCase {
/**
* Illuminate\Foundation\Exceptions\Handler
*/
private $handler;
/**
* Raven_Client
*/
private $ravenClientMock;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->handler = new Handler($this->app);
$this->mockRavenClient();
}
protected function mockRavenClient () {
// Inject into our container a mock of Raven_Client
$this->ravenClientMock = Mockery::mock('Raven_Client');
$this->app->instance('raven', $this->ravenClientMock);
// Environment shouldn't be 'testing' and DSN should be defined,
// so Handler::report will call Raven to report to Sentry
Config::set('app.env', 'testing-raven');
Config::set('services.sentry.dsn', 'mock');
}
public function testRavenReport () {
$this->ravenClientMock->shouldReceive('captureException')->once();
$this->handler->report(new \Exception);
}
public function testExceptionInDontReportArray () {
$this->ravenClientMock->shouldReceive('captureException')->never();
$this->handler->report(new AuthorizationException);
}
}
diff --git a/tests/Facades/DockerHubTest.php b/tests/Facades/DockerHubTest.php
index 1bff186..2bdb3c8 100644
--- a/tests/Facades/DockerHubTest.php
+++ b/tests/Facades/DockerHubTest.php
@@ -1,21 +1,19 @@
<?php
namespace Nasqueron\Notifications\Tests\Facades;
+use Nasqueron\Notifications\Facades\DockerHub;
use Nasqueron\Notifications\Tests\TestCase;
-use Config;
-use DockerHub;
-
use Keruald\DockerHub\Build\TriggerBuildFactory;
class DockerHubTest extends TestCase {
public function testIfFacadeAccessorCouldBeResolvedInAppContainer () {
$this->assertInstanceOf(
TriggerBuildFactory::class,
DockerHub::getFacadeRoot()
);
}
}
diff --git a/tests/Facades/MailgunTest.php b/tests/Facades/MailgunTest.php
index 13e031d..0d19459 100644
--- a/tests/Facades/MailgunTest.php
+++ b/tests/Facades/MailgunTest.php
@@ -1,21 +1,19 @@
<?php
namespace Nasqueron\Notifications\Tests\Facades;
+use Nasqueron\Notifications\Facades\Mailgun;
use Nasqueron\Notifications\Tests\TestCase;
-use Config;
-use Mailgun;
-
use Keruald\Mailgun\MailgunMessageFactory;
class MailgunTest extends TestCase {
public function testIfFacadeAccessorCouldBeResolvedInAppContainer () {
$this->assertInstanceOf(
MailgunMessageFactory::class,
Mailgun::getFacadeRoot()
);
}
}
diff --git a/tests/Facades/RavenTest.php b/tests/Facades/RavenTest.php
index 4497295..148889b 100644
--- a/tests/Facades/RavenTest.php
+++ b/tests/Facades/RavenTest.php
@@ -1,29 +1,29 @@
<?php
namespace Nasqueron\Notifications\Tests\Facades;
use Nasqueron\Notifications\Tests\TestCase;
+use Nasqueron\Notifications\Facades\Raven;
-use Config;
-use Raven;
+use Illuminate\Support\Facades\Config;
class RavenTest extends TestCase {
public function testIfFacadeAccessorCouldBeResolvedInAppContainer () {
$this->assertInstanceOf(
'Raven_Client',
Raven::getFacadeRoot()
);
}
public function testIsConfigured () {
Config::set("services.sentry.dsn", "something");
$this->assertTrue(Raven::isConfigured());
}
public function testIsConfiguredWhenItIsNot () {
Config::offsetUnset("services.sentry.dsn");
$this->assertFalse(Raven::isConfigured());
}
}
diff --git a/tests/Http/Controllers/GitHubGateControllerTest.php b/tests/Http/Controllers/GitHubGateControllerTest.php
index 14b5c7a..cd3a6dd 100644
--- a/tests/Http/Controllers/GitHubGateControllerTest.php
+++ b/tests/Http/Controllers/GitHubGateControllerTest.php
@@ -1,95 +1,95 @@
<?php
namespace Nasqueron\Notifications\Tests\Http\Controllers;
use Nasqueron\Notifications\Tests\TestCase;
class GitHubGateControllerTest extends TestCase {
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->disableEvents();
}
/**
* GitHub gate works.
*
* @return void
*/
public function testGet () {
$this->visit('/gate/GitHub')
->see('POST');
}
/**
* Tests a GitHub gate payload.
*/
public function testPost () {
$payload = file_get_contents(__DIR__ . '/../../data/payloads/GitHubPingPayload.json');
$this->sendPayload(
'/gate/GitHub/Quux', // A gate not existing in data/credentials.json
$payload,
'POST',
[
'X-Github-Event' => 'ping',
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c'
]
)
->seeJson([
'gate' => 'GitHub',
'door' => 'Quux',
'actions' => []
]);
$this->assertResponseOk();
}
/**
* Tests a malformed GitHub gate payload.
*/
public function testMalformedPost () {
$this->sendPayload(
'/gate/GitHub/Quux', // A gate not existing in data/credentials.json
"",
'POST',
[
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c',
]
);
$this->assertResponseStatus(400);
$this->sendPayload(
'/gate/GitHub/Quux', // A gate not existing in data/credentials.json
"",
'POST',
[
'X-Github-Event' => 'ping',
]
);
$this->assertResponseStatus(400);
$this->sendPayload(
'/gate/GitHub/Quux', // A gate not existing in data/credentials.json
"",
'POST',
[
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c',
'X-Github-Event' => 'ping',
]
);
$this->assertResponseStatus(400);
}
public function testEmptySignature () {
$this->sendPayload(
'/gate/GitHub/Acme', // A gate existing in data/credentials.json
"",
'POST',
[
'X-Github-Event' => 'ping',
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c',
]
);
$this->assertResponseStatus(403);
}
}
diff --git a/tests/Http/PayloadFullTest.php b/tests/Http/PayloadFullTest.php
index 0461da3..5d46784 100644
--- a/tests/Http/PayloadFullTest.php
+++ b/tests/Http/PayloadFullTest.php
@@ -1,183 +1,183 @@
<?php
namespace Nasqueron\Notifications\Tests;
use Keruald\Broker\BlackholeBroker;
use Nasqueron\Notifications\Config\Features;
class PayloadFullTest extends TestCase {
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->disableBroker();
}
/**
* Sends a GitHub ping payload to the application, with a valid signature
*/
protected function sendValidTestPayload () {
return $this->sendTestPayload('sha1=25f6cbd17ea4c6c69958b95fb88c879de4b66dcc');
}
/**
* Sends a GitHub ping payload to the application, with a valid signature
*/
protected function sendInvalidTestPayload () {
return $this->sendTestPayload('sha1=somethingwrong');
}
protected function sendTestPayload ($signature) {
$payload = file_get_contents(__DIR__ . '/../data/payloads/GitHubPingPayload.json');
$this->sendPayload(
'/gate/GitHub/Acme', // A gate existing in data/credentials.json
$payload,
'POST',
[
'X-Github-Event' => 'ping',
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c',
'X-Hub-Signature' => $signature,
]
);
return $this;
}
/**
* Tests a GitHub gate payload.
*/
public function testPost () {
$this->sendValidTestPayload()->seeJson([
'gate' => 'GitHub',
'door' => 'Acme',
'action' => 'AMQPAction'
]);
$this->assertResponseOk();
}
/**
* Tests a DockerHub gate payload.
*/
public function testDockerHubPayload () {
$payload = file_get_contents(__DIR__ . '/../data/payloads/DockerHubPushPayload.json');
$this->sendPayload(
'/gate/DockerHub/Acme', // A gate existing in data/credentials.json
$payload,
'POST',
[]
)->seeJson([
'gate' => 'DockerHub',
'door' => 'Acme',
'action' => 'AMQPAction'
]);
$this->assertResponseOk();
}
/**
* Tests a Jenkins gate payload.
*/
public function testJenkinsPayload () {
$payload = file_get_contents(__DIR__ . '/../data/payloads/JenkinsPayload.json');
$this->sendPayload(
'/gate/Jenkins/Acme', // A gate existing in data/credentials.json
$payload,
'POST',
[]
)->seeJson([
'gate' => 'Jenkins',
'door' => 'Acme',
'action' => 'AMQPAction'
]);
$this->assertResponseOk();
}
private function getDataForPhabricatorPayloadTests () {
return [
'storyID' => 3849,
'storyType' => 'PhabricatorApplicationTransactionFeedStory',
'storyData[objectPHID]' => 'PHID-TASK-l34fw5wievp6n6rnvpuk',
'storyData[transactionPHIDs][PHID-XACT-TASK-by2g3dtlfq3l2wc]' => 'PHID-XACT-TASK-by2g3dtlfq3l2wc',
'storyAuthorPHID' => 'PHID-USER-fnetlprx7zdotfm2hdrz',
'storyText' => 'quux moved T123: Lorem ipsum dolor to Backlog on the Foo workboard.',
'epoch' => 1450654419,
];
}
/**
* Tests a Phabricator gate payload.
*/
public function testPhabricatorPayload () {
$data = $this->getDataForPhabricatorPayloadTests();
$this->post('/gate/Phabricator/Acme', $data)->seeJson([
'gate' => 'Phabricator',
'door' => 'Acme',
'action' => 'AMQPAction'
]);
$this->assertResponseOk();
}
/**
* Tests a Phabricator gate payload, when the door doesn't exist.
*/
public function testPhabricatorPayloadOnNotExistingDoor () {
$data = $this->getDataForPhabricatorPayloadTests();
$this->post('/gate/Phabricator/NotExistingDoor', $data);
$this->assertResponseStatus(404);
}
/**
* Same than testPost, but without actions report.
*/
public function testPostWithoutActionsReport () {
Features::disable("ActionsReport");
$this->sendValidTestPayload();
$this->assertEmpty($this->response->getContent());
$this->assertResponseOk();
// Let's throw an Exception at broker level.
// Without ActionsReport, the client must always receive a 200 OK.
$this->app->instance('broker', function ($app) {
// A non omnipotent instance, so it doesn't mock connect().
return new BlackholeBroker;
});
$this->sendValidTestPayload();
$this->assertEmpty($this->response->getContent());
$this->assertResponseOk();
}
/**
* Tests a GitHub gate payload.
*/
public function testInvalidSignature () {
$this->sendInvalidTestPayload()
->assertResponseStatus(403);
}
public function testBrokerIssue () {
$this->mockNotOperationalBroker();
$payload = file_get_contents(__DIR__ . '/../data/payloads/GitHubPingPayload.json');
$this->sendPayload(
'/gate/GitHub/Acme', // A gate existing in data/credentials.json
$payload,
'POST',
[
'X-Github-Event' => 'ping',
'X-Github-Delivery' => 'e5dd9fc7-17ac-11e5-9427-73dad6b9b17c',
'X-Hub-Signature' => 'sha1=25f6cbd17ea4c6c69958b95fb88c879de4b66dcc',
]
)->seeJson([
'gate' => 'GitHub',
'door' => 'Acme',
'action' => 'AMQPAction',
'type' => 'RuntimeException',
]);
$this->assertResponseStatus(503);
}
}
diff --git a/tests/Http/PlaceholderTest.php b/tests/Http/PlaceholderTest.php
index fa82c67..e724d76 100644
--- a/tests/Http/PlaceholderTest.php
+++ b/tests/Http/PlaceholderTest.php
@@ -1,21 +1,15 @@
<?php
namespace Nasqueron\Notifications\Tests;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-use Illuminate\Foundation\Testing\DatabaseMigrations;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-
-class PlaceholderTest extends TestCase
-{
+class PlaceholderTest extends TestCase {
/**
* Placeholder homepage works.
*
* @return void
*/
- public function testPlaceholder()
- {
+ public function testPlaceholder() {
$this->visit('/')
->see('Notifications center');
}
}
diff --git a/tests/Http/StatusTest.php b/tests/Http/StatusTest.php
index 43d8a49..a8fca30 100644
--- a/tests/Http/StatusTest.php
+++ b/tests/Http/StatusTest.php
@@ -1,21 +1,15 @@
<?php
namespace Nasqueron\Notifications\Tests;
-use Illuminate\Foundation\Testing\WithoutMiddleware;
-use Illuminate\Foundation\Testing\DatabaseMigrations;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-
-class StatusTest extends TestCase
-{
+class StatusTest extends TestCase {
/**
* Status works.
*
* @return void
*/
- public function testStatus()
- {
+ public function testStatus() {
$this->visit('/status')
->see('ALIVE');
}
}
diff --git a/tests/Jobs/NotifyNewCommitsToDiffusionTest.php b/tests/Jobs/NotifyNewCommitsToDiffusionTest.php
index 9051d5a..f7350fd 100644
--- a/tests/Jobs/NotifyNewCommitsToDiffusionTest.php
+++ b/tests/Jobs/NotifyNewCommitsToDiffusionTest.php
@@ -1,70 +1,72 @@
<?php
namespace Nasqueron\Notifications\Tests\Jobs;
use Nasqueron\Notifications\Jobs\Job;
use Nasqueron\Notifications\Jobs\NotifyNewCommitsToDiffusion;
use Nasqueron\Notifications\Tests\TestCase;
class NotifyNewCommitsToDiffusionTest extends TestCase {
///
/// Tests
///
/**
* @dataProvider apiRepositoryReplyProvider
*/
- public function testHandle ($apiRepositoryReply, int $apiCallCounts) {
+ public function testHandle(?array $apiRepositoryReply, int $apiCallCounts) {
$this->mockPhabricatorAPI()
->shouldReceive('getForProject->call')
->andReturn(
// First API call: repository.query
$apiRepositoryReply,
// Second API call: diffusion.looksoon
null
)
->times($apiCallCounts); // 2 when repository.query is valid
// 1 otherwise
$job = $this->mockJob();
$job->handle();
}
- public function testJobWhenThereIsNoPhabricatorInstanceForTheProject () {
+ public function testJobWhenThereIsNoPhabricatorInstanceForTheProject () : void {
$job = $this->mockJob("not-existing-project");
$job->handle();
+
+ $this->markTestIncomplete();
}
///
/// Helper methods
///
/**
* Mocks a job
*/
protected function mockJob(string $project = "acme") : Job {
return new NotifyNewCommitsToDiffusion(
$project,
"ssh://acme/k2.git"
);
}
/**
* Provides API repository reply and associated API calls count
*/
public function apiRepositoryReplyProvider () : array {
return [
// Regular behavior
[[new class { public $callsign = "K2"; }], 2],
// Phabricator doesn't know this repo
[[], 1],
// Some error occurs and the API reply is null
[null, 1],
];
}
}
diff --git a/tests/Phabricator/PhabricatorAPIExceptionTest.php b/tests/Phabricator/PhabricatorAPIExceptionTest.php
index ec42555..abffc68 100644
--- a/tests/Phabricator/PhabricatorAPIExceptionTest.php
+++ b/tests/Phabricator/PhabricatorAPIExceptionTest.php
@@ -1,29 +1,29 @@
<?php
namespace Nasqueron\Notifications\Tests\Phabricator;
use Nasqueron\Notifications\Phabricator\PhabricatorAPIException;
use Nasqueron\Notifications\Tests\TestCase;
class PhabricatorAPIExceptionTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Phabricator\PhabricatorAPIException
*/
private $exception;
- public function setUp () {
+ public function setUp (): void {
$this->exception = new PhabricatorAPIException(
100,
"Lorem ipsum dolor"
);
}
public function testGetCode () {
$this->assertSame(100, $this->exception->getCode());
}
public function testGetMessage () {
$this->assertSame("Lorem ipsum dolor", $this->exception->getMessage());
}
}
diff --git a/tests/Phabricator/PhabricatorAPIFactoryTest.php b/tests/Phabricator/PhabricatorAPIFactoryTest.php
index 634c2ec..f451ec8 100644
--- a/tests/Phabricator/PhabricatorAPIFactoryTest.php
+++ b/tests/Phabricator/PhabricatorAPIFactoryTest.php
@@ -1,32 +1,32 @@
<?php
namespace Nasqueron\Notifications\Tests\Phabricator;
use Nasqueron\Notifications\Tests\TestCase;
class PhabricatorAPIFactoryTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Phabricator\ProjectsMapFactory
*/
private $factory;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->factory = $this->app->make('phabricator-api');
}
public function testGetAPI () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\PhabricatorAPI',
$this->factory->get("https://phabricator.acme.tld")
);
}
public function testGetAPIForProject () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\PhabricatorAPI',
$this->factory->getForProject("Acme")
);
}
}
diff --git a/tests/Phabricator/PhabricatorAPITest.php b/tests/Phabricator/PhabricatorAPITest.php
index 282e0b3..b6925fe 100644
--- a/tests/Phabricator/PhabricatorAPITest.php
+++ b/tests/Phabricator/PhabricatorAPITest.php
@@ -1,36 +1,32 @@
<?php
namespace Nasqueron\Notifications\Tests\Phabricator;
use Nasqueron\Notifications\Phabricator\PhabricatorAPI;
use Nasqueron\Notifications\Tests\TestCase;
class PhabricatorAPITest extends TestCase {
public function testForInstance () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\PhabricatorAPI',
PhabricatorAPI::forInstance("https://phabricator.acme.tld")
);
}
public function testForProject () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\PhabricatorAPI',
PhabricatorAPI::forInstance("https://phabricator.acme.tld")
);
}
- /**
- * @expectedException \RuntimeException
- */
public function testForInstanceWhere () {
+ $this->expectException(\RuntimeException::class);
PhabricatorAPI::forInstance("https://notfound.acme.tld");
}
- /**
- * @expectedException \RuntimeException
- */
public function testForProjectWhenProjectDoesNotExist () {
+ $this->expectException(\RuntimeException::class);
PhabricatorAPI::forProject("NotFound");
}
}
diff --git a/tests/Phabricator/ProjectsMapFactoryTest.php b/tests/Phabricator/ProjectsMapFactoryTest.php
index ddefc70..d6cb907 100644
--- a/tests/Phabricator/ProjectsMapFactoryTest.php
+++ b/tests/Phabricator/ProjectsMapFactoryTest.php
@@ -1,35 +1,35 @@
<?php
namespace Nasqueron\Notifications\Tests\Phabricator;
use Nasqueron\Notifications\Tests\TestCase;
class ProjectsMapFactoryTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Phabricator\ProjectsMapFactory
*/
private $factory;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->factory = $this->app->make('phabricator-projectsmap');
$this->mockPhabricatorAPIForProjectsMap();
}
public function testLoadProjectsMap () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\ProjectsMap',
$this->factory->load("Acme")
);
}
public function testFetchProjectsMap () {
$this->assertInstanceOf(
'\Nasqueron\Notifications\Phabricator\ProjectsMap',
$this->factory->fetch("Acme")
);
}
}
diff --git a/tests/Phabricator/ProjectsMapTest.php b/tests/Phabricator/ProjectsMapTest.php
index e4dac8e..6cdb170 100644
--- a/tests/Phabricator/ProjectsMapTest.php
+++ b/tests/Phabricator/ProjectsMapTest.php
@@ -1,203 +1,198 @@
<?php
namespace Nasqueron\Notifications\Tests\Phabricator;
use Nasqueron\Notifications\Contracts\APIClient;
use Nasqueron\Notifications\Phabricator\ProjectsMap;
use Nasqueron\Notifications\Tests\TestCase;
-use Mockery;
+use ErrorException;
+use Exception;
class ProjectsMapTest extends TestCase {
/**
* @var \Nasqueron\Notifications\Phabricator\ProjectsMap
*/
private $map;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
//
// We mock the API, so an imaginary instance of Phabricator
// will return 3 results: Accounts, Agora & architecture.
//
// Agora has the key "PHID-PROJ-cztcgpvqr6smnnekotq7".
//
$this->mockPhabricatorAPIForProjectsMap();
$this->map = ProjectsMap::fetch("http://phabricator.acme.tld");
}
public function testIteratorIsTraversable () {
$this->assertInstanceOf(
"Traversable",
$this->map->getIterator()
);
}
///
/// Tests for ArrayAccess
///
public function testOffsetExistsWhenItDoes () {
$this->assertTrue(
$this->map->offsetExists("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
public function testOffsetExistsWhenItDoesNot () {
$this->assertFalse(
$this->map->offsetExists("non-existing-key")
);
}
public function testOffsetGetWhenItDoesExist () {
$this->assertSame(
"Agora",
$this->map->offsetGet("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
- /**
- * @expectedException ErrorException
- */
public function testOffsetGetWhenItDoesNotExist () {
+ $this->expectException(ErrorException::class);
$this->map->offsetGet("non-existing-key");
}
/**
* @covers Nasqueron\Notifications\Phabricator\ProjectsMap::offsetSet
*/
public function testOffsetSet () {
$this->map->offsetSet("newkey", "quux");
$this->assertSame("quux", $this->map->offsetGet("newkey"));
}
/**
* @covers Nasqueron\Notifications\Phabricator\ProjectsMap::offsetUnset
*/
public function testOffsetUnset () {
unset($this->map["PHID-PROJ-cztcgpvqr6smnnekotq7"]);
$this->assertFalse(
$this->map->offsetExists("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
///
/// Tests for cache
///
public function testCache () {
$this->assertFalse($this->map->isCached());
$this->map->saveToCache();
$this->assertTrue($this->map->isCached());
}
public function testLoadFromCache () {
$this->map->saveToCache();
$map = new ProjectsMap("http://phabricator.acme.tld");
$map->loadFromCache();
$this->assertTrue(
$map->offsetExists("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
public function testLoadWhenInCache () {
$this->map->saveToCache();
$map = ProjectsMap::load("http://phabricator.acme.tld");
$this->assertTrue(
$map->offsetExists("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
///
/// Tests for helper methods
///
public function testGetProjectName () {
$this->assertSame(
"Agora",
$this->map->getProjectName("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
public function testGetProjectNameForNewInstance () {
$map = new ProjectsMap("http://phabricator.acme.tld");
$this->assertSame(
"Agora",
$map->getProjectName("PHID-PROJ-cztcgpvqr6smnnekotq7")
);
}
public function testGetProjectNameWhenItDoesNotExist () {
$this->assertSame(
"",
$this->map->getProjectName("non-existing-key")
);
}
public function testToArrayProducesArray () {
$array = $this->map->toArray();
$this->assertTrue(
is_array($array),
"Test if toArray return an array"
);
}
public function testThatArrayCount () {
$array = $this->map->toArray();
$this->assertSame(3, count($array));
}
public function testThatArrayContainsExpectedData () {
$this->assertSame(
[
["PHID-PROJ-6dg6ogx5pjmk24ur4tp4", "Accounts"],
["PHID-PROJ-cztcgpvqr6smnnekotq7", "Agora"],
["PHID-PROJ-3iew3cqf3htpazfyzb5a", "architecture"]
],
$this->map->toArray()
);
}
///
/// Tests API
///
private function mockPhabricatorAPIWithReply ($reply) : APIClient {
return (new class($reply) implements APIClient {
private $reply;
public function __construct ($reply) {
$this->reply = $reply;
}
public function setEndPoint ($url) : void { }
public function call ($method, $arguments = []) {
return $this->reply;
}
});
}
- /**
- * @expectedException Exception
- */
public function testFetchFromAPIWithoutReply () {
+ $this->expectException(Exception::class);
$mock = $this->mockPhabricatorAPIWithReply(false);
ProjectsMap::fetch("http://phabricator.acme.tld", $mock);
}
- /**
- * @expectedException Exception
- */
public function testFetchFromAPIInvalidReply () {
+ $this->expectException(Exception::class);
$mock = $this->mockPhabricatorAPIWithReply(new \stdClass);
ProjectsMap::fetch("http://phabricator.acme.tld", $mock);
}
}
diff --git a/tests/Providers/ConfigTest.php b/tests/Providers/ConfigTest.php
index 13461f2..21551ce 100644
--- a/tests/Providers/ConfigTest.php
+++ b/tests/Providers/ConfigTest.php
@@ -1,43 +1,43 @@
<?php
namespace Nasqueron\Notifications\Tests\Providers;
-use Config;
-use File;
+use Illuminate\Support\Facades\Config;
+use Illuminate\Support\Facades\File;
class ConfigTest extends TestCase {
/**
* The actual list of services providers
*
* @var string[]
*/
private $providers;
/**
* The service providers' namespace
*
* @var string
*/
private $namespace;
- public function setUp () {
+ public function setUp (): void {
parent::setUp();
$this->providers = Config::get('app.providers');
$this->namespace = $this->app->getInstance()->getNamespace()
. 'Providers\\';
}
public function testOmittedFiles () {
$files = File::allFiles(app_path('Providers'));
foreach ($files as $file) {
$class = $this->namespace . $file->getBasename('.php');
$this->assertContains(
$class, $this->providers,
"The class $class should be added to config/app.php in the " .
"providers array."
);
}
}
}
diff --git a/tests/Providers/DockerHubServiceProviderTest.php b/tests/Providers/DockerHubServiceProviderTest.php
index 1da526c..791bcbc 100644
--- a/tests/Providers/DockerHubServiceProviderTest.php
+++ b/tests/Providers/DockerHubServiceProviderTest.php
@@ -1,36 +1,36 @@
<?php
namespace Nasqueron\Notifications\Tests\Providers;
use Nasqueron\Notifications\Providers\DockerHubServiceProvider;
-use Config;
+use Illuminate\Support\Facades\Config;
class DockerHubServiceProviderTest extends TestCase {
public function testType () {
$this->assertServiceInstanceOf(
'Keruald\DockerHub\Build\TriggerBuildFactory',
'dockerhub'
);
}
public function testGetTokens () {
$this->assertSame(
['acme/foo' => '0000'],
DockerHubServiceProvider::getTokens($this->app),
"The service provider should deserialize DockerHubTokens.json."
);
}
public function testGetTokensWhenFileDoesNotExist () {
Config::set('services.dockerhub.tokens', 'notexisting.json');
$this->assertSame(
[],
DockerHubServiceProvider::getTokens($this->app),
"When no tokens file exists, an empty array is used instead."
);
}
}
diff --git a/tests/Providers/EventServiceProviderTest.php b/tests/Providers/EventServiceProviderTest.php
index f2bcad5..3fb7008 100644
--- a/tests/Providers/EventServiceProviderTest.php
+++ b/tests/Providers/EventServiceProviderTest.php
@@ -1,39 +1,51 @@
<?php
namespace Nasqueron\Notifications\Tests\Providers;
-use Config;
-use File;
+use Nasqueron\Notifications\Providers\EventServiceProvider;
+
+use Illuminate\Support\Facades\File;
class EventServiceProviderTest extends TestCase {
public function testType () {
$this->assertServiceInstanceOf(
'Illuminate\Contracts\Events\Dispatcher',
'events'
);
}
///
/// Tests specific to this service provider
///
public function testOmittedFiles () {
$subscribe = [];
$namespace = $this->app->getInstance()->getNamespace() . 'Listeners\\';
$files = File::allFiles(app_path('Listeners'));
foreach ($files as $file) {
$class = $namespace . $file->getBasename('.php');
$subscribe[] = $class;
}
- $this->assertEquals(
- $subscribe, Config::get('app.listeners'),
+ $this->assertEqualsCanonicalizing(
+ $subscribe, $this->getRegisteredListeners(),
'The files in the app/Listeners folder and the array of classes ' .
- 'defined in config/app.php at listeners key diverge.',
- 0.0, 10, true // delta, maxDepth, canonicalize
+ 'defined in config/app.php at listeners key diverge.'
);
}
+ private function getRegisteredListeners () : array {
+ $provider = $this->app->getProvider(EventServiceProvider::class);
+ $eventsMap = $provider->listens();
+ $listeners = [];
+
+ foreach ($eventsMap as $foundListeners) {
+ foreach ($foundListeners as $listener){
+ $listeners[] = $listener;
+ }
+ }
+ return array_unique($listeners);
+ }
}
diff --git a/tests/Providers/ServicesServiceProviderTest.php b/tests/Providers/ServicesServiceProviderTest.php
index fc93b9b..9a120d2 100644
--- a/tests/Providers/ServicesServiceProviderTest.php
+++ b/tests/Providers/ServicesServiceProviderTest.php
@@ -1,41 +1,41 @@
<?php
namespace Nasqueron\Notifications\Tests\Providers;
use Nasqueron\Notifications\Providers\ServicesServiceProvider;
-use Config;
+use Illuminate\Support\Facades\Config;
class ServicesServiceProviderTest extends TestCase {
public function testType () {
$this->assertServiceInstanceOf(
"Nasqueron\Notifications\Config\Services\Services",
'services'
);
}
///
/// Tests specific to this service provider
///
public function testWithCredentialsFile () {
$services = $this->app->make('services');
$this->assertGreaterThan(0, count($services->services));
}
public function testWithoutCredentialsFile () {
Config::set('services.gate.credentials', null);
$services = $this->app->make('services');
$this->assertSame(0, count($services->services));
}
public function testWithNontFoundCredentialsFile () {
Config::set('services.gate.credentials', 'notfound.json');
$services = $this->app->make('services');
$this->assertSame(0, count($services->services));
}
}
diff --git a/tests/TestCase.php b/tests/TestCase.php
index 0dd2c1d..97707f0 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -1,166 +1,164 @@
<?php
namespace Nasqueron\Notifications\Tests;
use Nasqueron\Notifications\Config\Services\Service;
use Illuminate\Contracts\Console\Kernel;
use Keruald\Broker\BlackholeBroker;
-use Keruald\Broker\Broker;
-
+use Laravel\BrowserKitTesting\TestCase as BaseTestCase;
use Mockery;
-class TestCase extends \Illuminate\Foundation\Testing\TestCase
-{
+
+class TestCase extends BaseTestCase {
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
- public function createApplication()
- {
+ public function createApplication() {
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
///
/// Helpers to mock application services
///
/**
* Mocks the events dispatcher
*/
public function disableEvents () {
// Disables events
// This allows to test a single component and not all the application
$mock = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
- $mock->shouldReceive('fire');
+ $mock->shouldReceive('dispatch');
$mock->shouldReceive('listen');
$this->app->instance('events', $mock);
}
/**
* Mocks the broker
*/
public function disableBroker () {
$broker = new BlackholeBroker();
$broker->acceptAllMethodCalls(); // allows to be used as a mock
$this->app->instance('broker', $broker);
}
/**
* Mocks the broker, throwing an exception when sendMessage is called.
*/
public function mockNotOperationalBroker () {
$mock = Mockery::mock('Keruald\Broker\Broker');
$mock->shouldReceive('connect');
$mock->shouldReceive('setExchangeTarget->routeTo->sendMessage')
->andThrow(new \RuntimeException);
$this->app->instance('broker', $mock);
}
/**
* Mocks the Phabricator API
*
* @return \Nasqueron\Notifications\Phabricator\PhabricatorAPIFactory The mock
*/
protected function mockPhabricatorAPI () {
// Inject into our container a mock of PhabricatorAPI
$mock = Mockery::mock('Nasqueron\Notifications\Phabricator\PhabricatorAPIFactory');
$this->app->instance('phabricator-api', $mock);
return $mock;
}
private function mockPhabricatorAPIProjectsQueryReply () {
$json = file_get_contents('tests/data/PhabricatorProjetsQueryReply.json');
return json_decode($json);
}
/**
* Mocks the Phabricator API
*/
protected function mockPhabricatorAPIForProjectsMap () {
$mock = $this->mockPhabricatorAPI();
$reply = $this->mockPhabricatorAPIProjectsQueryReply();
$mock->shouldReceive('getForProject->call')->andReturn($reply);
}
///
/// Helper methods to mock services
///
protected function mockServices () {
// Inject into our container a mock of Services
$mock = Mockery::mock('Nasqueron\Notifications\Config\Services\Services');
$this->app->instance('services', $mock);
return $mock;
}
protected function mockService ($gate = 'Storm') {
$service = new Service;
$service->gate = $gate;
$service->door = 'Acme';
$service->instance = "http://www.perdu.com";
return $service;
}
///
/// Helpers to post data to gates
///
/**
* Visits the given URI with a JSON request.
*
* @param string $uri
* @param mixed $data
* @param string $method
* @param array $headers
* @return $this
*/
public function sendJsonPayload ($uri, $data, $method = 'POST', array $headers = []) {
$content = json_encode($data);
$headers = array_merge([
'CONTENT_TYPE' => 'application/json',
'Accept' => 'application/json',
], $headers);
return $this->sendPayload($uri, $content, $method, $headers);
}
/**
* Visits the given URI with a raw request.
*
* @param string $uri
* @param string $content
* @param string $method
* @param array $headers
* @return $this
*/
public function sendPayload ($uri, $content, $method = 'POST', array $headers = []) {
$headers = array_merge([
'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
], $headers);
$this->call(
$method, $uri, [], [], [], $this->transformHeadersToServerVars($headers), $content
);
return $this;
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sun, Nov 24, 19:42 (3 h, 42 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2256175
Default Alt Text
(253 KB)

Event Timeline