code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function notifyAction(Request $request) { /** @var Event $content */ $content = json_decode($request->getContent(), true); // Get the Event again from Stripe for security reasons $stripeWebhookEvent = $this->get('stripe_bundle.manager.stripe_api')->retrieveEvent($content['id']); // Now check the event doesn't already exist in the database $localWebhookEvent = $this->get('stripe_bundle.entity_manager')->getRepository('SHQStripeBundle:StripeLocalWebhookEvent')->findOneByStripeId($stripeWebhookEvent->id); if (false !== strpos($content['type'], 'deleted')) { $objectType = ucfirst($content['data']['object']['object']); if (null === $localWebhookEvent) { $localResource = $this->get('stripe_bundle.entity_manager') ->getRepository('SHQStripeBundle:StripeLocal' . $objectType) ->findOneBy(['id' => $content['data']['object']['id']]); } $syncer = $this->get('stripe_bundle.syncer.' . $objectType); if (method_exists($syncer, 'removeLocal')) { $this->get('stripe_bundle.syncer.' . $objectType)->removeLocal($localResource, $stripeWebhookEvent); } return new Response('ok', 200); } if (null === $localWebhookEvent) { // Create the entity object (this will be persisted) $localWebhookEvent = new StripeLocalWebhookEvent(); // Now sync the entity LocalWebhookEvent with the remote Stripe\Event (persisting is automatically handled) $this->get('stripe_bundle.syncer.webhook_event')->syncLocalFromStripe($localWebhookEvent, $stripeWebhookEvent); } // Guess the event to dispatch to the application $guessedDispatchingEvent = $this->get('stripe_bundle.guesser.event_guesser')->guess($stripeWebhookEvent, $localWebhookEvent); $this->container->get('event_dispatcher')->dispatch($guessedDispatchingEvent['type'], $guessedDispatchingEvent['object']); return new Response('ok', 200); }
@param Request $request @return Response
public function run() { if (is_callable($this->closure)) { // Set the error handler for the spec set_error_handler([$this, 'handleError'], E_ALL); // Invoke the closure while catching exceptions try { $this->closure->__invoke(); } catch (ExpectationException $exception) { $this->exception = $exception; } catch (\Exception $exception) { $this->handleException($exception); } restore_error_handler(); } }
Invokes a Runnable object's $closure, setting an error handler and catching all uncaught exceptions.
public function handleError($level, $string, $file = null, $line = null) { $this->exception = new ErrorException($level, $string, $file, $line); }
An error handler to be used by set_error_handler(). Creates a custom ErrorException, and sets the objects $exception property. @param int $level The error level corresponding to the PHP error @param string $string Error message itself @param string $file The name of the file from which the error was raised @param int $line The line number from which the error was raised
public function metadataTransformer() { if (is_string($this->getMetadata())) { $this->setMetadata(json_decode($this->getMetadata(), true)); } }
Transforms metadata from string to array. As metadata can be set by the developer or by reflection during syncronization of the StripeCustomer object with this local one, may happen the value is a string. This lifecycle callback ensures the value ever is an array.
public function getEventTypes() { $this->endpoint = 'eventtypes'; $this->url = sprintf('%s%s', $this->url, $this->endpoint); $response = $this->get($this->url); return new AuthnetWebhooksResponse($response); }
Gets all of the available event types @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
public function createWebhooks(Array $webhooks, $webhookUrl, $status = 'active') { $this->endpoint = 'webhooks'; $this->url = sprintf('%s%s', $this->url, $this->endpoint); $request = [ 'url' => $webhookUrl, 'eventTypes' => $webhooks, 'status' => $status ]; $this->requestJson = json_encode($request); $response = $this->post($this->url, $this->requestJson); return new AuthnetWebhooksResponse($response); }
Creates a new webhook @param array $webhooks Array of webhooks to be created or modified @param string $webhookUrl URL of where webhook notifications will be sent @param string $status Status of webhooks to be created or modified [active/inactive] @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
public function getWebhooks() { $this->endpoint = 'webhooks'; $this->url = sprintf('%s%s', $this->url, $this->endpoint); $response = $this->get($this->url); return new AuthnetWebhooksResponse($response); }
List all of your webhooks @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
public function getWebhook($webhookId) { $this->endpoint = 'webhooks'; $this->url = sprintf('%s%s/%s', $this->url, $this->endpoint, $webhookId); $response = $this->get($this->url); return new AuthnetWebhooksResponse($response); }
Get a webhook @param string $webhookId Webhook ID to be retrieved @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
public function updateWebhook($webhookId, $webhookUrl, Array $eventTypes, $status = 'active') { $this->endpoint = 'webhooks'; $this->url = sprintf('%s%s/%s', $this->url, $this->endpoint, $webhookId); $request = [ 'url' => $webhookUrl, 'eventTypes' => $eventTypes, 'status' => $status ]; $this->requestJson = json_encode($request); $response = $this->put($this->url, $this->requestJson); return new AuthnetWebhooksResponse($response); }
Updates webhook event types @param array $webhookId Webhook ID to be modified @param string $webhookUrl URL of where webhook notifications will be sent @param array $eventTypes Array of event types to be added/removed @param string $status Status of webhooks to be modified [active/inactive] @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
public function deleteWebhook($webhookId) { $this->endpoint = 'webhooks'; $this->url = sprintf('%s%s/%s', $this->url, $this->endpoint, $webhookId); $this->delete($this->url); }
Delete a webhook @param string $webhookId Webhook ID to be deleted @throws \JohnConde\Authnet\AuthnetCurlException
public function getNotificationHistory($limit = 1000, $offset = 0) { $this->endpoint = 'notifications'; $this->url = sprintf('%s%s', $this->url, $this->endpoint); $response = $this->get($this->url, [ 'offset' => $offset, 'limit' => $limit ]); return new AuthnetWebhooksResponse($response); }
Retrieve Notification History @param integer $limit Default: 1000 @param integer $offset Default: 0 @return \JohnConde\Authnet\AuthnetWebhooksResponse @throws \JohnConde\Authnet\AuthnetInvalidJsonException @throws \JohnConde\Authnet\AuthnetCurlException
private function handleResponse() { if (!$this->processor->error) { return $this->processor->response; } $error_message = null; $error_code = null; if ($this->processor->error_code) { $error_message = $this->processor->error_message; $error_code = $this->processor->error_code; if (empty($error_message)) { $response = json_decode($this->processor->response); $error_message = sprintf('(%u) %s: %s', $response->status, $response->reason, $response->message); } } throw new AuthnetCurlException(sprintf('Connection error: %s (%s)', $error_message, $error_code)); }
Tells the handler to make the API call to Authorize.Net @return string @throws \JohnConde\Authnet\AuthnetCurlException
private function get($url, Array $params = []) { $this->processor->get($url, $params); return $this->handleResponse(); }
Make GET request via Curl @param string $url @param array $params @return string @throws \JohnConde\Authnet\AuthnetCurlException @codeCoverageIgnore
private function post($url, $request) { $this->processor->post($url, $request); return $this->handleResponse(); }
Make POST request via Curl @param string $url API endpoint @param string $request JSON request payload @return string @throws \JohnConde\Authnet\AuthnetCurlException @codeCoverageIgnore
private function put($url, $request) { $this->processor->put($url, $request, true); return $this->handleResponse(); }
Make PUT request via Curl @param string $url API endpoint @param string $request JSON request payload @return string @throws \JohnConde\Authnet\AuthnetCurlException @codeCoverageIgnore
private function process() { $this->processor->post($this->url, $this->requestJson); if (!$this->processor->error) { return $this->processor->response; } $error_message = null; $error_code = null; if ($this->processor->error_code) { $error_message = $this->processor->error_message; $error_code = $this->processor->error_code; } throw new AuthnetCurlException(sprintf('Connection error: %s (%s)', $error_message, $error_code)); }
Tells the handler to make the API call to Authorize.Net @throws \JohnConde\Authnet\AuthnetCurlException
public function guessEventPieces($type) { /* * Guess the event kind. * * In an event like charge.dispute.closed, the kind is "charge". */ $dotPosition = strpos($type, '.'); $eventKind = substr($type, 0, $dotPosition); /* * Guess the constant of the type. * * In an event like charge.dispute.closed, the type is "DISPUTE_CLOSED". */ $string = str_replace($eventKind . '.', '', $type); $string = str_replace('.', '_', $string); $eventType = strtoupper($string); return [ 'kind' => $eventKind, 'type' => $eventType, ]; }
@param $type @return array
public function setValue($value) { if ($this->acceptsArguments()) { $this->value = $value; } else { $this->value = (boolean) $value; } }
Sets the value of the option. If the option accepts arguments, the supplied value can be of any type. Otherwise, the value is cast as a boolean. @param mixed $value The value to assign to the option
public function describe($title, \Closure $closure) { $previous = $this->current; $suite = new Suite($title, $closure, $previous); if ($this->current === $this->root) { $this->suites[] = $suite; } else { $this->current->addSuite($suite); } $this->current = $suite; $suite->getClosure()->__invoke(); $this->current = $previous; }
Constructs a test Suite, assigning it the given title and anonymous function. If it's a child of another suite, a reference to the parent suite is stored. This is done by tracking the current and previously defined suites. @param string $title A title to be associated with the suite @param \Closure $closure The closure to invoke when the suite is ran
public function xdescribe($title, \Closure $closure) { $previous = $this->current; $suite = new Suite($title, $closure, $previous); $suite->setPending(); // If current is null, this is the root suite for the file if ($this->current === null) { $this->suites[] = $suite; } else { $this->current->addSuite($suite); } $this->current = $suite; $suite->getClosure()->__invoke(); $this->current = $previous; }
Creates a suite and marks it as pending. @param string $title A title to be associated with the suite @param \Closure $closure The closure to invoke when the suite is ran
public function it($title, \Closure $closure = null) { $spec = new Spec($title, $closure, $this->current); $this->current->addSpec($spec); }
Constructs a new Spec, adding it to the list of specs in the current suite. @param string $title A title to be associated with the spec @param \Closure $closure The closure to invoke when the spec is ran
public function xit($title, \Closure $closure = null) { $spec = new Spec($title, $closure, $this->current); $spec->setPending(); $this->current->addSpec($spec); }
Constructs a new Spec, adding it to the list of specs in the current suite and mark it as pending. @param string $title A title to be associated with the spec @param \Closure $closure The closure to invoke when the spec is ran
public function before(\Closure $closure) { $key = 'before'; $before = new Hook($key, $closure, $this->current); $this->current->setHook($key, $before); }
Constructs a new Hook, defining a closure to be ran prior to the parent suite's closure. @param \Closure $closure The closure to be ran before the suite
public function after(\Closure $closure) { $key = 'after'; $after = new Hook($key, $closure, $this->current); $this->current->setHook($key, $after); }
Constructs a new Hook, defining a closure to be ran after the parent suite's closure. @param \Closure $closure The closure to be ran after the suite
public function beforeEach(\Closure $closure) { $key = 'beforeEach'; $beforeEach = new Hook($key, $closure, $this->current); $this->current->setHook($key, $beforeEach); }
Constructs a new Hook, defining a closure to be ran prior to each of the parent suite's nested suites and specs. @param \Closure $closure The closure to be ran before each spec
public function afterEach(\Closure $closure) { $key = 'afterEach'; $afterEach = new Hook($key, $closure, $this->current); $this->current->setHook($key, $afterEach); }
Constructs a new Hook, defining a closure to be ran prior to each of the parent suite's nested suites and specs. @param \Closure $closure The closure to be ran after each spec
public function run() { // Get and instantiate the reporter class, load files $reporterClass = self::$console->getReporterClass(); $this->reporter = new $reporterClass(self::$console); $this->reporter->beforeRun(); foreach ($this->suites as $suite) { $this->runSuite($suite); } $this->reporter->afterRun(); if (self::$console->options['watch']) { $this->watch(); } }
Starts the test runner by first invoking the associated reporter's beforeRun() method, then iterating over all defined suites and running their specs, and calling the reporter's afterRun() when complete.
public function watch() { $watcher = new Watcher(); $watcher->watchPath(getcwd()); $watcher->addListener(function() { $paths = implode(' ', self::$console->getPaths()); $descriptor = [ 0 => ['pipe', 'r'], 1 => ['pipe', 'w'] ]; // Rebuild option string, without watch $optionString = ''; foreach (self::$console->options as $key => $val) { if ($key == 'watch') { continue; } elseif ($val === true) { // test $optionString .= "--$key "; } elseif ($val) { $optionString .= "--$key $val "; } } // Run pho in another process and echo its stdout $procStr = "{$_SERVER['SCRIPT_FILENAME']} {$optionString} {$paths}"; $process = proc_open($procStr, $descriptor, $pipes); if (is_resource($process)) { while ($buffer = fread($pipes[1], 16)) { self::$console->write($buffer); } fclose($pipes[0]); fclose($pipes[1]); proc_close($process); } }); // Ever vigilant $watcher->watch(); }
Monitors the the current working directory for modifications, and reruns the specs in another process on change.
private function runSuite(Suite $suite) { $this->runRunnable($suite->getHook('before')); $this->reporter->beforeSuite($suite); // Run the specs $this->runSpecs($suite); // Run nested suites foreach ($suite->getSuites() as $nestedSuite) { $this->runSuite($nestedSuite); } $this->reporter->afterSuite($suite); $this->runRunnable($suite->getHook('after')); }
Runs a particular suite by running the associated hooks and reporter, methods, iterating over its child suites and recursively calling itself, followed by running its specs. @param Suite $suite The suite to run
private function runSpecs(Suite $suite) { foreach ($suite->getSpecs() as $spec) { // If using the filter option, only run matching specs $pattern = self::$console->options['filter']; if ($pattern && !preg_match($pattern, $spec)) { continue; } $this->reporter->beforeSpec($spec); $this->runBeforeEachHooks($suite, $spec); $this->runRunnable($spec); $this->runAfterEachHooks($suite, $spec); $this->reporter->afterSpec($spec); } }
Runs the specs associated with the provided test suite. It iterates over and runs each spec, calling the reporter's beforeSpec and afterSpec methods, as well as the suite's beforeEach and aferEach hooks. If the filter option is used, only specs containing a pattern are ran. And if the stop flag is used, it quits when an exception or error is thrown. @param Suite $suite The suite containing the specs to run
private function runBeforeEachHooks(Suite $suite, Spec $spec) { if ($suite->getParent()) { $this->runBeforeEachHooks($suite->getParent(), $spec); } $hook = $suite->getHook('beforeEach'); $this->runRunnable($hook); if (!$spec->getException() && $hook) { $spec->setException($hook->getException()); } }
Runs the beforeEach hooks of the given suite and its parent suites recursively. They are ran in the order in which they were defined, from outer suite to inner suites. @param Suite $suite The suite with the hooks to run @param Spec $spec The spec to assign any hook failures
private function runRunnable($runnable) { if (!$runnable) return; $runnable->run(); if ($runnable->getException()) { self::$console->setExitStatus(1); if (self::$console->options['stop']) { $this->reporter->afterRun(); exit(1); } } }
A short helper method that calls an object's run() method only if it's an instance of Runnable.
public function syncStripeFromLocal(ApiResource $stripeResource, StripeLocalResourceInterface $localResource) { /** @var Plan $stripeResource */ if ( ! $stripeResource instanceof Plan) { throw new \InvalidArgumentException('PlanSyncer::hydrateStripe() accepts only Stripe\Plan objects as first parameter.'); } /** @var StripeLocalPlan $localResource */ if ( ! $localResource instanceof StripeLocalPlan) { throw new \InvalidArgumentException('PlanSyncer::hydrateStripe() accepts only StripeLocalPlan objects as second parameter.'); } $this->getEntityManager()->persist($localResource); $this->getEntityManager()->flush(); }
{@inheritdoc}
public function syncStripeFromLocal(ApiResource $stripeResource, StripeLocalResourceInterface $localResource) { /** @var Card $stripeResource */ if ( ! $stripeResource instanceof Card) { throw new \InvalidArgumentException('CardSyncer::hydrateLocal() accepts only Stripe\Card objects as first parameter.'); } /** @var StripeLocalCard $localResource */ if ( ! $localResource instanceof StripeLocalCard) { throw new \InvalidArgumentException('CardSyncer::hydrateLocal() accepts only StripeLocalCard objects as second parameter.'); } throw new \RuntimeException('Method not yet implemented'); }
{@inheritdoc}
public function match($actual) { $this->actual = gettype($actual); return ($this->actual === $this->expected); }
Compares the type of the passed argument to the expected type. Returns true if the two values are of the same type, false otherwise. @param mixed $actual The value to test @return boolean Whether or not the value has the expected type
public function match($callable) { ob_start(); $callable(); $this->actual = ob_get_contents(); ob_end_clean(); return ($this->actual == $this->expected); }
Compares the output printed by the callable to the expected output. Returns true if the two strings are equal, false otherwise. @param callable $callable The function to invoke @return boolean Whether or not the printed and expected output are equal
public function onChargeCreate(StripeChargeCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $localCharge = $event->getLocalCharge(); $result = $this->getStripeManager()->createCharge($localCharge); // Check if something went wrong if (false === $result) { // Stop progation $event->setStopReason($this->getStripeManager()->getError())->stopPropagation(); // Dispatch a failed event $dispatcher->dispatch(StripeChargeCreateEvent::FAILED, $event); // exit return; } $dispatcher->dispatch(StripeChargeCreateEvent::CREATED, $event); }
{@inheritdoc} @param StripeChargeCreateEvent $event @param $eventName @param ContainerAwareEventDispatcher|EventDispatcherInterface $dispatcher
public function match($haystack) { $this->found = []; $this->missing = []; if (!is_string($haystack) && !is_array($haystack)) { throw new \InvalidArgumentException('Argument must be an array or string'); } if (is_string($haystack)) { $this->type = 'string'; foreach ($this->needles as $needle) { if (strpos($haystack, $needle) !== false) { $this->found[] = $needle; } else { $this->missing[] = $needle; } } } elseif (is_array($haystack)) { $this->type = 'array'; foreach ($this->needles as $needle) { if (in_array($needle, $haystack)) { $this->found[] = $needle; } else { $this->missing[] = $needle; } } } if ($this->matchAll) { return (count($this->missing) === 0); } return (count($this->found) > 0); }
Checks whether or not the needles are found in the supplied $haystack. Returns true if the needles are found, false otherwise. @param mixed $haystack An array or string through which to search @return boolean Whether or not the needles were found @throws \InvalidArgumentException If $haystack isn't an array or string
public function getFailureMessage($negated = false) { if (!$negated) { $missing = implode(', ', $this->missing); return "Expected {$this->type} to contain {$missing}"; } else { $found = implode(', ', $this->found); return "Expected {$this->type} not to contain {$found}"; } }
Returns an error message indicating why the match failed, and the negation of the message if $negated is true. @param boolean $negated Whether or not to print the negated message @return string The error message
public function isValid() { $hashedBody = strtoupper(hash_hmac('sha512', $this->webhookJson, $this->signature)); return (isset($this->headers['X-ANET-SIGNATURE']) && strtoupper(explode('=', $this->headers['X-ANET-SIGNATURE'])[1]) === $hashedBody); }
Validates a webhook signature to determine if the webhook is valid @return bool
protected function getAllHeaders() { if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); } else { $headers = array_filter($_SERVER, function($key) { return strpos($key, 'HTTP_') === 0; }, ARRAY_FILTER_USE_KEY); } return $headers; }
Retrieves all HTTP headers of a given request @return array
public function createCharge(StripeLocalCharge $localCharge) { // Get the object as an array $params = $localCharge->toStripe('create'); // If the statement descriptor is not set and the default one is not null... if (false === isset($params['statement_descriptor']) && false === is_null($this->statementDescriptor)) { // Set it $params['statement_descriptor'] = $this->statementDescriptor; } $arguments = [ 'params' => $params, 'options' => [], ]; $stripeCharge = $this->callStripeApi(Charge::class, 'create', $arguments); // If the creation failed... if (false === $stripeCharge) { // ... Check if it was due to a fraudulent detection if (isset($this->error['error']['type'])) { $this->chargeSyncer->handleFraudDetection($localCharge, $this->error); } // ... return false as the payment anyway failed return false; } // Set the data returned by Stripe in the LocalCustomer object $this->chargeSyncer->syncLocalFromStripe($localCharge, $stripeCharge); // The creation was successful: return true return true; }
@param StripeLocalCharge $localCharge @return bool
public function createSubscription(StripeLocalSubscription $localSubscription) { // Get the object as an array $params = $localSubscription->toStripe('create'); $arguments = [ 'params' => $params, 'options' => [], ]; $stripeSubscription = $this->callStripeApi(Subscription::class, 'create', $arguments); // If the creation failed, return false if (false === $stripeSubscription) { return false; } // Set the data returned by Stripe in the LocalSubscription object $this->subscriptionSyncer->syncLocalFromStripe($localSubscription, $stripeSubscription); // The creation was successful: return true return true; }
@param StripeLocalSubscription $localSubscription @return bool
public function cancelSubscription(StripeLocalSubscription $localSubscription) { // Get the stripe object $stripeSubscription = $this->retrieveSubscription($localSubscription); // The retrieving failed: return false if (false === $stripeSubscription) { return false; } // Save the subscription object $stripeSubscription = $this->callStripeObject($stripeSubscription, 'cancel'); // If the update failed, return false if (false === $stripeSubscription) { return false; } return true; }
@param StripeLocalSubscription $localSubscription @return bool
public function createCustomer(StripeLocalCustomer $localCustomer) { // Get the object as an array $params = $localCustomer->toStripe('create'); $arguments = [ 'params' => $params, 'options' => [], ]; /** @var Customer $stripeCustomer */ $stripeCustomer = $this->callStripeApi(Customer::class, 'create', $arguments); // If the creation failed, return false if (false === $stripeCustomer) { return false; } // Set the data returned by Stripe in the LocalCustomer object $this->customerSyncer->syncLocalFromStripe($localCustomer, $stripeCustomer); // The creation was successful: return true return true; }
@param StripeLocalCustomer $localCustomer @return bool
public function retrieveCustomer(StripeLocalCustomer $localCustomer) { // If no ID is set, return false if (null === $localCustomer->getId()) { return false; } $arguments = [ 'id' => $localCustomer->getId(), 'options' => [], ]; // Return the stripe object that can be "false" or "Customer" return $this->callStripeApi(Customer::class, 'retrieve', $arguments); }
@param StripeLocalCustomer $localCustomer @throws InvalidRequest @return ApiResource|bool|Customer
public function createPlan(StripeLocalPlan $localPlan) { // Get the object as an array $details = $localPlan->toStripe('create'); /** @var Plan $stripePlan */ $stripePlan = $this->callStripeApi(Plan::class, 'create', $details); // If the creation failed, return false if (false === $stripePlan) { return false; } // Set the data returned by Stripe in the LocalPlan object $this->planSyncer->syncLocalFromStripe($localPlan, $stripePlan); // The creation was successful: return true return true; }
@param StripeLocalPlan $localPlan @return bool
public function retrievePlan(StripeLocalPlan $localPlan) { // If no ID is set, return false if (null === $localPlan->getId()) { return false; } $arguments = [ 'id' => $localPlan->getId(), 'options' => [], ]; // Return the stripe object that can be "false" or "Plan" return $this->callStripeApi(Plan::class, 'retrieve', $arguments); }
@param StripeLocalPlan $localPlan @throws InvalidRequest @return ApiResource|bool|Plan
public function retrieveSubscription(StripeLocalSubscription $localSubscription) { // If no ID is set, return false if (null === $localSubscription->getId()) { return false; } $arguments = [ 'id' => $localSubscription->getId(), 'options' => [], ]; // Return the stripe object that can be "false" or "Subscription" return $this->callStripeApi(Subscription::class, 'retrieve', $arguments); }
@param StripeLocalSubscription $localSubscription @throws InvalidRequest @return ApiResource|bool|Subscription
public function updateCustomer(StripeLocalCustomer $localCustomer, $syncSources): bool { // Get the stripe object $stripeCustomer = $this->retrieveCustomer($localCustomer); // The retrieving failed: return false if (false === $stripeCustomer) { return false; } // Update the stripe object with info set in the local object $this->customerSyncer->syncStripeFromLocal($stripeCustomer, $localCustomer); // Save the customer object $stripeCustomer = $this->callStripeObject($stripeCustomer, 'save'); // If the update failed, return false if (false === $stripeCustomer) { return false; } // Set the data returned by Stripe in the LocalCustomer object $this->customerSyncer->syncLocalFromStripe($localCustomer, $stripeCustomer); if (true === $syncSources) { $this->customerSyncer->syncLocalSources($localCustomer, $stripeCustomer); } return true; }
@param StripeLocalCustomer $localCustomer @param bool $syncSources @return bool
public function updatePlan(StripeLocalPlan $localPlan, $syncSources) { // Get the stripe object $stripePlan = $this->retrievePlan($localPlan); // The retrieving failed: return false if (false === $stripePlan) { return false; } // Update the stripe object with info set in the local object $this->planSyncer->syncStripeFromLocal($stripePlan, $localPlan); // Save the plan object $stripePlan = $this->callStripeObject($stripePlan, 'save'); // If the update failed, return false if (false === $stripePlan) { return false; } // Set the data returned by Stripe in the LocalPlan object $this->planSyncer->syncLocalFromStripe($localPlan, $stripePlan); if (true === $syncSources) { $this->planSyncer->syncLocalSources($localPlan, $stripePlan); } return true; }
@param StripeLocalPlan $localPlan @param bool $syncSources @return bool
public function match($actual) { if (is_string($actual)) { $this->type = 'string'; $this->actual = strlen($actual); } elseif (is_array($actual)) { $this->type = 'array'; $this->actual = count($actual); } else { throw new \Exception('LengthMatcher::match() requires an array or string'); } return ($this->actual === $this->expected); }
Compares the length of the given array or string to the expected value. Returns true if the value is of the expected length, else false. @param mixed $actual An array or string for which to test the length @return boolean Whether or not the value is of the expected length @throws \Exception If $actual isn't of type array or string
protected function checkTransactionStatus($status) { if ($this->transactionInfo instanceof TransactionResponse) { $match = (int) $this->transactionInfo->getTransactionResponseField('ResponseCode') === (int) $status; } else { $match = (int) $this->transactionResponse->responseCode === $status; } return $match; }
Check to see if the ResponseCode matches the expected value @param integer $status @return bool Check to see if the ResponseCode matches the expected value
public function getTransactionResponseField($field) { if ($this->transactionInfo instanceof TransactionResponse) { return $this->transactionInfo->getTransactionResponseField($field); } throw new AuthnetTransactionResponseCallException('This API call does not have any transaction response data'); }
Gets the transaction response field for AIM and CIM transactions. @param mixed $field Name or key of the transaction field to be retrieved @return string Transaction field to be retrieved @throws \JohnConde\Authnet\AuthnetTransactionResponseCallException
public function getErrorText() { $message = ''; if ($this->isError()) { $message = $this->messages->message[0]->text; if (@$this->transactionResponse->errors[0]->errorText) { $message = $this->transactionResponse->errors[0]->errorText; } } return $message; }
If an error has occurred, returns the error message @return string Error response from Authorize.Net
public function getErrorCode() { $code = ''; if ($this->isError()) { $code = $this->messages->message[0]->code; if (@$this->transactionResponse->errors[0]->errorCode) { $code = $this->transactionResponse->errors[0]->errorCode; } } return $code; }
If an error has occurred, returns the error message @return string Error response from Authorize.Net
protected function getStringValue($value) { if ($value === true) { return 'true'; } elseif ($value === false) { return 'false'; } elseif ($value === null) { return 'null'; } elseif (is_string($value)) { return "\"$value\""; } return rtrim(print_r($value, true)); }
Returns a string representation of the given value, used for printing the failure message. @param mixed $value The value for which to get a string representation @returns string The string in question
function _dochecks() { // Check availability of %F if (sprintf('%.1F', 1.0) != '1.0') $this->Error('This version of PHP is not supported'); // Check availability of mbstring if (!function_exists('mb_strlen')) $this->Error('mbstring extension is not available'); // Check mbstring overloading if (ini_get('mbstring.func_overload') & 2) $this->Error('mbstring overloading must be disabled'); // Ensure runtime magic quotes are disabled if (get_magic_quotes_runtime()) @set_magic_quotes_runtime(0); }
***************************************************************************** * Protected methods * * *****************************************************************************
public static function error(string $errorMessage, string $errorCode = null, array $data = null): JSendResponse { return new static(static::ERROR, $data, $errorMessage, $errorCode); }
From the spec: Description: An error occurred in processing the request, i.e. an exception was thrown Required : errorMessage Optional : errorCode, data @param string $errorMessage @param string|null $errorCode @param array|null $data @return JSendResponse @throws InvalidJSendException if empty($errorMessage) is true
public function asArray(): array { $theArray = [static::KEY_STATUS => $this->status]; if ($this->data) { $theArray[static::KEY_DATA] = $this->data; } if (!$this->data && !$this->isError()) { // Data is optional for errors, so it should not be set // rather than be null. $theArray[static::KEY_DATA] = null; } if ($this->isError()) { $theArray[static::KEY_MESSAGE] = (string)$this->errorMessage; if (!empty($this->errorCode)) { $theArray[static::KEY_CODE] = (int)$this->errorCode; } } return $theArray; }
Serializes the class into an array @return array the serialized array
public static function decode($json, $depth = 512, $options = 0): JSendResponse { $rawDecode = json_decode($json, true, $depth, $options); if ($rawDecode === null) { throw new \UnexpectedValueException('JSON is invalid.'); } if ((!\is_array($rawDecode)) || (!array_key_exists(static::KEY_STATUS, $rawDecode))) { throw new InvalidJSendException('JSend must be an object with a valid status.'); } $status = $rawDecode[static::KEY_STATUS]; $data = $rawDecode[static::KEY_DATA] ?? null; $errorMessage = $rawDecode[static::KEY_MESSAGE] ?? null; $errorCode = $rawDecode[static::KEY_CODE] ?? null; if ($status === static::ERROR && $errorMessage === null) { throw new InvalidJSendException('JSend errors must contain a message.'); } if ($status !== static::ERROR && !array_key_exists(static::KEY_DATA, $rawDecode)) { throw new InvalidJSendException('JSend must contain data unless it is an error.'); } return new static($status, $data, $errorMessage, $errorCode); }
Takes raw JSON (JSend) and builds it into a new JSendResponse @param string $json the raw JSON (JSend) to decode @param int $depth User specified recursion depth, defaults to 512 @param int $options Bitmask of JSON decode options. @return JSendResponse if JSON is invalid @throws InvalidJSendException if JSend does not conform to spec @see json_decode()
public function run() { if (true === $this->pending) { $this->result = self::PENDING; } else { parent::run(); if ($this->closure && !$this->exception) { $this->result = self::PASSED; } elseif ($this->closure) { $this->result = self::FAILED; } else { $this->result = self::INCOMPLETE; } } }
Invokes Runnable::run(), storing any exception in the corresponding property, followed by setting the specs' result.
public function setException(\Exception $exception = null) { $this->exception = $exception; $this->result = self::FAILED; }
Sets the spec exception, also marking it as failed. @param \Exception The exception
public function getHook($key) { if (isset($this->hooks[$key])) { return $this->hooks[$key]; } return null; }
Returns the hook found at the specified key. Usually one of before, after, beforeEach, or afterEach. @param string $key The key for the hook @return Hook The given hook
public function addSuite($suite) { if (true === $this->pending) { $suite->setPending(); } $this->suites[] = $suite; }
Adds a suite to the list of nested suites. @param Suite $suite The suite to add
public function setAmount(MoneyInterface $amount): self { if (null === $this->amount) { $this->amount = $amount; } return $this; }
This sets the amount only if it is null. This is to prevent an accidental overwriting of it. @param Money|MoneyInterface $amount @throws \InvalidArgumentException If the amount is not an integer @return StripeLocalCharge
public function setSource($card): self { if ($card instanceof StripeLocalCard) { $card = $card->getId(); } $this->source = $card; return $this; }
@param string|StripeLocalCard $card @return StripeLocalCharge
public function getFingerprint($amount) { if (!filter_var($amount, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND)) { throw new AuthnetInvalidAmountException('You must enter a valid amount greater than zero.'); } return strtoupper(hash_hmac('sha512', sprintf('%s^%s^%s^%s^', $this->login, $this->sequence, $this->timestamp, $amount ), hex2bin($this->signature))); }
Returns the hash for the SIM transaction @param float $amount The amount of the transaction @return string Hash of five different unique transaction parameters @throws \JohnConde\Authnet\AuthnetInvalidAmountException
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('shq_stripe'); $rootNode ->children() ->booleanNode('debug')->end() ->scalarNode('db_driver') ->validate() ->ifNotInArray(self::getSupportedDrivers()) ->thenInvalid('The driver %s is not supported. Please choose one of ' . json_encode(self::getSupportedDrivers())) ->end() ->cannotBeOverwritten() ->defaultValue('orm') ->cannotBeEmpty() ->end() ->scalarNode('model_manager_name')->defaultNull()->end() ->arrayNode('stripe_config') ->isRequired() ->children() ->scalarNode('secret_key')->cannotBeEmpty()->end() ->scalarNode('publishable_key')->cannotBeEmpty()->end() ->scalarNode('statement_descriptor')->defaultNull()->end() ->end() ->end() ->arrayNode('endpoint') ->addDefaultsIfNotSet() ->children() ->scalarNode('route_name')->defaultValue('_stripe_bundle_endpoint')->cannotBeEmpty()->end() ->end() ->end(); return $treeBuilder; }
{@inheritdoc}
public function syncStripeFromLocal(ApiResource $stripeResource, StripeLocalResourceInterface $localResource) { /** @var Customer $stripeResource */ if ( ! $stripeResource instanceof Customer) { throw new \InvalidArgumentException('CustomerSyncer::syncStripeFromLocal() accepts only Stripe\Customer objects as first parameter.'); } /** @var StripeLocalCustomer $localResource */ if ( ! $localResource instanceof StripeLocalCustomer) { throw new \InvalidArgumentException('CustomerSyncer::syncStripeFromLocal() accepts only StripeLocalCustoer objects as second parameter.'); } if (null !== $localResource->getAccountBalance()) { $stripeResource->account_balance = $localResource->getAccountBalance(); } if (null !== $localResource->getBusinessVatId()) { $stripeResource->business_vat_id = $localResource->getBusinessVatId(); } if (null !== $localResource->getNewSource()) { $stripeResource->source = $localResource->getNewSource(); } if (null !== $localResource->getDescription()) { $stripeResource->description = $localResource->getDescription(); } if (null !== $localResource->getEmail()) { $stripeResource->email = $localResource->getEmail(); } if (null !== $localResource->getAccountBalance()) { $stripeResource->metadata = $localResource->getMetadata(); } }
{@inheritdoc}
private function sourceExists(StripeLocalCard $card, Collection $sources) { /** @var Card $source */ foreach ($sources->data as $source) { if ($card->getId() === $source->id) { return true; } } return false; }
Checks if the given card is set source in the StripeCustomer object. Perfrom this check guarantees that the local database is ever in sync with the Stripe Account. @param StripeLocalCard $card @param Collection $sources @return bool
public function getTransactionResponseField($field) { $value = null; if (is_int($field)) { $value = (isset($this->responseArray[$field])) ? $this->responseArray[$field] : $value; } else { if ($key = array_search($field, $this->fieldMap)) { $value = $this->responseArray[$key]; } } return $value; }
Gets the requested value out of the response array using the provided key. The location of that value can be accessed via it's numerical location in the array (starting at zero) or using the key for that field as defined by Authorize.Net and mapped in self::$fieldMap. @param mixed $field Name or key of the transaction field to be retrieved @return string Transaction field to be retrieved
public function build(ContainerBuilder $container) { parent::build($container); $modelDir = realpath(__DIR__ . '/Resources/config/doctrine/mappings'); $mappings = [ $modelDir => 'SerendipityHQ\Bundle\StripeBundle\Model', ]; $ormCompilerClass = 'Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass'; if (class_exists($ormCompilerClass)) { $container->addCompilerPass( $this->getXmlMappingDriver($mappings) ); } // Register Value Object custom types $container->loadFromExtension('doctrine', [ 'dbal' => [ 'types' => [ 'email' => EmailType::class, 'money' => MoneyType::class, ], ], ]); }
{@inheritdoc}
public function hasTrigger($trigger) { return count($this->connection->select( $this->grammar->compileTriggerExists(), [$trigger] )) > 0; }
Determine if the given trigger exists. @param string $trigger @return bool
public function dropIfExists($trigger) { $this->build(tap($this->createBlueprint($trigger), function ($blueprint) { $blueprint->dropIfExists(); })); }
Drop trigger. @return void
public function callBuild() { $eventObjectTable = $this->getEventObjectTable(); $callback = $this->getStatement(); $actionTiming = $this->getActionTiming(); $event = $this->getEvent(); $this->build(tap( $this->createBlueprint($this->trigger), function (Blueprint $blueprint) use ($eventObjectTable, $callback, $actionTiming, $event) { $blueprint->create(); $blueprint->on($eventObjectTable); $blueprint->statement($callback); $blueprint->$actionTiming(); $blueprint->$event(); } )); }
Call build to execute blueprint to build trigger. @return void
public function onSubscriptionCreate(StripeSubscriptionCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $localSubscription = $event->getLocalSubscription(); $result = $this->getStripeManager()->createSubscription($localSubscription); // Check if something went wrong if (false === $result) { // Stop progation $event->setStopReason($this->getStripeManager()->getError())->stopPropagation(); // Dispatch a failed event $dispatcher->dispatch(StripeSubscriptionCreateEvent::FAILED, $event); // exit return; } $dispatcher->dispatch(StripeSubscriptionCreateEvent::CREATED, $event); }
{@inheritdoc} @param StripeSubscriptionCreateEvent $event @param $eventName @param ContainerAwareEventDispatcher|EventDispatcherInterface $dispatcher
public function onSubscriptionCancel(StripeSubscriptionCancelEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $localSubscription = $event->getLocalSubscription(); $localSubscription->setCancelAtPeriodEnd(true); $result = $this->getStripeManager()->cancelSubscription($localSubscription, true); // Check if something went wrong if (false === $result) { // Stop progation $event->setStopReason($this->getStripeManager()->getError())->stopPropagation(); // Dispatch a failed event $dispatcher->dispatch(StripeSubscriptionCancelEvent::FAILED, $event); // exit return; } $dispatcher->dispatch(StripeSubscriptionCancelEvent::CANCELED, $event); }
{@inheritdoc} @param StripeSubscriptionCancelEvent $event @param $eventName @param ContainerAwareEventDispatcher|EventDispatcherInterface $dispatcher
public function beforeSuite(Suite $suite) { if ($this->depth == 0) { $this->console->writeLn(''); } $leftPad = str_repeat(' ', self::TAB_SIZE * $this->depth); $title = $suite->getTitle(); $this->console->writeLn($leftPad . $title); $this->depth += 1; parent::beforeSuite($suite); }
Ran before the containing test suite is invoked. @param Suite $suite The test suite before which to run this method
public function afterSpec(Spec $spec) { $leftPad = str_repeat(' ', self::TAB_SIZE * $this->depth); if ($spec->isFailed()) { $this->failures[] = $spec; $title = $this->formatter->red($spec->getTitle()); } elseif ($spec->isIncomplete()) { $this->incompleteSpecs[] = $spec; $title = $this->formatter->cyan($spec->getTitle()); } elseif ($spec->isPending()) { $this->pendingSpecs[] = $spec; $title = $this->formatter->yellow($spec->getTitle()); } else { $title = $this->formatter->grey($spec->getTitle()); } $this->console->writeLn($leftPad . $title); }
Ran after an individual spec. May be used to display the results of that particular spec. @param Spec $spec The spec after which to run this method
protected function handleHookFailure(Hook $hook) { $this->failures[] = $hook; $title = $this->formatter->red($hook->getTitle()); $leftPad = str_repeat(' ', self::TAB_SIZE * $this->depth); $this->console->writeLn($leftPad . $title); }
If a given hook failed, adds it to list of failures and prints the result. @param Hook $hook The failed hook
public function addCharge(StripeLocalCharge $charge) { // If the cards is already set if (false === $this->charges->contains($charge)) { // Add the card to the collection $this->charges->add($charge); } return $this; }
@param StripeLocalCharge $charge @return $this
public function addSubscription(StripeLocalSubscription $subscription) { // If the subscription is already set if (false === $this->subscriptions->contains($subscription)) { // Add the subscription to the collection $this->subscriptions->add($subscription); } return $this; }
@param StripeLocalSubscription $subscription @return $this
public function setNewSource($source) { if (0 < strpos($source, 'tok_')) { throw new \InvalidArgumentException(sprintf('The token you passed seems not to be a card token: %s', $source)); } $this->newSource = $source; return $this; }
@param string $source @return $this
public function toStripe($action) { if ('create' !== $action && 'update' !== $action) { throw new \InvalidArgumentException('StripeLocalCustomer::__toArray() accepts only "create" or "update" as parameter.'); } $return = []; if (null !== $this->getAccountBalance() && 'create' === $action) { $return['account_balance'] = $this->getAccountBalance(); } if (null !== $this->getBusinessVatId() && 'create' === $action) { $return['business_vat_id'] = $this->getBusinessVatId(); } if (null !== $this->getDescription() && 'create' === $action) { $return['description'] = $this->getDescription(); } if (null !== $this->getEmail() && 'create' === $action) { $return['email'] = $this->getEmail()->getEmail(); } if (null !== $this->getMetadata() && 'create' === $action) { $return['metadata'] = $this->getMetadata(); } if (null !== $this->getNewSource() && 'create' === $action) { $return['source'] = $this->getNewSource(); } return $return; }
{@inheritdoc}
public function getReporterClass() { $reporter = $this->options['reporter']; if ($reporter === false) { return self::DEFAULT_REPORTER; } $reporterClass = ucfirst($reporter) . 'Reporter'; $reporterClass = "pho\\Reporter\\$reporterClass"; try { $reflection = new ReflectionClass($reporterClass); } catch (ReflectionException $exception) { throw new ReporterNotFoundException($exception); } return $reflection->getName(); }
Returns the namespaced name of the reporter class requested via the command line arguments, defaulting to DotReporter if not specified. @return string The namespaced class name of the reporter @throws \pho\Exception\ReporterNotFoundException
public function parseArguments() { // Add the list of options to the OptionParser foreach ($this->availableOptions as $name => $desc) { $desc[3] = (isset($desc[3])) ? $desc[3] : null; list($longName, $shortName, $description, $argumentName) = $desc; $this->optionParser->addOption($name, $longName, $shortName, $description, $argumentName); } // Parse the arguments, assign the options $this->optionParser->parseArguments($this->arguments); $this->options = $this->optionParser->getOptions(); // Verify the paths, listing any invalid paths $paths = $this->optionParser->getPaths(); if ($paths) { $this->paths = $paths; foreach ($this->paths as $path) { if (!file_exists($path)) { $this->exitStatus = 1; $this->writeLn("The file or path \"{$path}\" doesn't exist"); } } } // Render help or version text if necessary, and display errors if ($this->options['help']) { $this->exitStatus = 0; $this->printHelp(); } elseif ($this->options['version']) { $this->exitStatus = 0; $this->printVersion(); } elseif ($this->optionParser->getInvalidArguments()) { $this->exitStatus = 1; foreach ($this->optionParser->getInvalidArguments() as $invalidArg) { $this->writeLn("$invalidArg is not a valid option"); } } }
Parses the arguments originally supplied via the constructor, assigning their values to the option keys in the $options array. If the arguments included the help or version option, the corresponding text is printed. Furthermore, if the arguments included a non-valid flag or option, or if any of the listed paths were invalid, error message is printed.
private function printHelp() { $this->writeLn("Usage: pho [options] [files]\n"); $this->writeLn("Options\n"); // Loop over availableOptions, building the necessary input for // ConsoleFormatter::alignText() $options = []; foreach ($this->availableOptions as $name => $optionInfo) { $row = [$optionInfo[1], $optionInfo[0]]; $row[] = (isset($optionInfo[3])) ? "<{$optionInfo[3]}>" : ''; $row[] = $optionInfo[2]; $options[] = $row; } $pad = str_repeat(' ', 3); foreach ($this->formatter->alignText($options, $pad) as $line) { $this->writeLn($pad . $line); } }
Outputs the help text, as required when the --help/-h flag is used. It's done by iterating over $this->availableOptions.
public function beforeSuite(Suite $suite) { $hook = $suite->getHook('before'); if ($hook && $hook->getException()) { $this->handleHookFailure($hook); } }
Ran before the containing test suite is invoked. @param Suite $suite The test suite before which to run this method
public function afterSuite(Suite $suite) { $hook = $suite->getHook('after'); if ($hook && $hook->getException()) { $this->handleHookFailure($hook); } }
Ran after the containing test suite is invoked. @param Suite $suite The test suite after which to run this method
public function afterRun() { if (count($this->failures)) { $this->console->writeLn("\nFailures:"); } foreach ($this->failures as $spec) { $failedText = $this->formatter->red("\n\"$spec\" FAILED"); $this->console->writeLn($failedText); $this->console->writeLn($spec->getException()); } if ($this->startTime) { $endTime = microtime(true); $runningTime = round($endTime - $this->startTime, 5); $this->console->writeLn("\nFinished in $runningTime seconds"); } $failedCount = count($this->failures); $incompleteCount = count($this->incompleteSpecs); $pendingCount = count($this->pendingSpecs); $specs = ($this->specCount == 1) ? 'spec' : 'specs'; $failures = ($failedCount == 1) ? 'failure' : 'failures'; $incomplete = ($incompleteCount) ? ", $incompleteCount incomplete" : ''; $pending = ($pendingCount) ? ", $pendingCount pending" : ''; // Print ASCII art if enabled if ($this->console->options['ascii']) { $this->console->writeLn(''); $this->drawAscii(); } $summaryText = "\n{$this->specCount} $specs, $failedCount $failures" . $incomplete . $pending; // Generate the summary based on whether or not it passed if ($failedCount) { $summary = $this->formatter->red($summaryText); } else { $summary = $this->formatter->green($summaryText); } $summary = $this->formatter->bold($summary); $this->console->writeLn($summary); }
Invoked after the test suite has ran, allowing for the display of test results and related statistics.
private function drawAscii() { $fail = [ '(╯°□°)╯︵ ┻━┻', '¯\_(ツ)_/¯', '┻━┻︵ \(°□°)/ ︵ ┻━┻', '(ಠ_ಠ)', '(ノಠ益ಠ)ノ彡', '(✖﹏✖)' ]; $pass = [ '☜(゚ヮ゚☜)', '♪ヽ( ⌒o⌒)人(⌒-⌒ )v ♪', '┗(^-^)┓', 'ヽ(^。^)ノ', 'ヽ(^▽^)v' ]; if (count($this->failures)) { $key = array_rand($fail, 1); $this->console->writeLn($fail[$key]); } else { $key = array_rand($pass, 1); $this->console->writeLn($pass[$key]); } }
Prints ASCII art based on whether or not any specs failed. If all specs passed, the randomly selected art is of a happier variety, otherwise there's a lot of anger and flipped tables.
public function alignText($array, $delimiter = '') { // Get max column widths $widths = []; foreach ($array as $row) { $lengths = array_map('strlen', $row); for ($i = 0; $i < count($lengths); $i++) { if (isset($widths[$i])) { $widths[$i] = max($widths[$i], $lengths[$i]); } else { $widths[$i] = $lengths[$i]; } } } // Pad lines columns and return an array $output = []; foreach($array as $row) { $entries = []; for ($i = 0; $i < count($row); $i++) { $entries[] = str_pad($row[$i], $widths[$i]); } $output[] = implode($entries, $delimiter); } return $output; }
Given a multidimensional array, formats the text such that each entry is left aligned with all other entries in the given column. The method also takes an optional delimiter for specifying a sequence of characters to separate each column. @param array $array The multidimensional array to format @param string $delimiter The delimiter to be used between columns @return array An array of strings containing the formatted entries
private function applyForeground($color, $text) { list($startCode, $endCode) = self::$foregroundColors[$color]; return $startCode . $text . $endCode; }
Sets the text color to one of those defined in $foregroundColors. @param string $color A color corresponding to one of the keys in the $foregroundColors array @param string $text The text to be modified @return string The original text surrounded by ANSI escape codes
private function applyStyle($style, $text) { list($startCode, $endCode) = self::$styles[$style]; return $startCode . $text . $endCode; }
Sets the text style to one of those defined in $styles. @param string $style A style corresponding to one of the keys in the $styles array @param string $text The text to be modified @return string The original text surrounded by ANSI escape codes
public function watchPath($path) { if (!$this->inotify) { $this->paths[] = $path; $this->addModifiedTimes($path); return; } $mask = IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF; $directoryIterator = new \RecursiveDirectoryIterator(realpath($path)); $subPaths = new \RecursiveIteratorIterator($directoryIterator); // Iterate over instances of \SplFileObject foreach ($subpaths as $subPath) { if ($subPath->isDir()) { $watchDescriptor = inotify_add_watch($this->inotify, $subPath->getRealPath(), $mask); $this->paths[$watchDescriptor] = $subPath->getRealPath(); } } }
Adds the path to the list of files and folders to monitor for changes. If the path is a file, its modification time is stored for comparison. If a directory, the modification times for each sub-directory and file are recursively stored. @param string $path A valid path to a file or directory
private function watchTimeBased() { clearstatcache(); $modified = false; // Loop over stored modified timestamps and compare them to their // current value foreach ($this->modifiedTimes as $path => $modifiedTime) { if ($modifiedTime != stat($path)['mtime']) { $modified = true; break; } } if ($modified) { $this->runListeners(); // Clear modified times and re-traverse paths $this->modifiedTimes = []; foreach ($this->paths as $path) { $this->addModifiedTimes($path); } } }
Monitor the paths for any changes based on the modify time information. When a change is detected, all listeners are invoked, and the list of paths is once again traversed to acquire updated modification timestamps.
private function watchInotify() { if (($eventList = inotify_read($this->inotify)) === false) { return; } foreach ($eventList as $event) { $mask = $event['mask']; if ($mask & IN_DELETE_SELF || $mask & IN_MOVE_SELF) { $watchDescriptor = $event['wd']; if (inotify_rm_watch($this->inotify, $watchDescriptor)) { unset($this->paths[$watchDescriptor]); } break; } } $this->runListeners(); }
Monitor the paths for any changes based on the modify time information. When a change is detected, all listeners are invoked, and the list of paths is once again traversed to acquire updated modification timestamps.
private function addModifiedTimes($path) { if (is_file($path)) { $stat = stat($path); $this->modifiedTimes[realpath($path)] = $stat['mtime']; return; } $directoryIterator = new \RecursiveDirectoryIterator(realpath($path)); $files = new \RecursiveIteratorIterator($directoryIterator); // Iterate over instances of \SplFileObject foreach ($files as $file) { $modifiedTime = $file->getMTime(); $this->modifiedTimes[$file->getRealPath()] = $modifiedTime; } }
Given the path to a file or directory, recursively adds the modified times of any nested folders to the modifiedTimes property. @param string $path A valid path to a file or directory
public function beforeSuite(Suite $suite) { if ($this->depth == 0) { $this->console->writeLn(''); } $this->depth += 1; parent::beforeSuite($suite); }
Ran before the containing test suite is invoked. @param Suite $suite The test suite before which to run this method