repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Models/DummyComment.php
tests/Models/DummyComment.php
<?php namespace Froiden\RestAPI\Tests\Models; use Froiden\RestAPI\ApiModel; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class DummyComment extends ApiModel { protected $table = 'dummy_comments'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'comments', 'user_id', 'post_id', ]; protected $filterable = [ 'comments', 'user_id', 'post_id', ]; protected $dates = [ 'created_at', 'updated_at' ]; /** * Get the post that owns the comment. */ public function post() { return $this->belongsTo('Froiden\RestAPI\Tests\Models\DummyPost'); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Models/DummyPhone.php
tests/Models/DummyPhone.php
<?php namespace Froiden\RestAPI\Tests\Models; use Froiden\RestAPI\ApiModel; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class DummyPhone extends ApiModel { protected $table = 'dummy_phones'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'modal_no','user_id', ]; protected $dates = [ 'created_at', 'updated_at' ]; }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Models/DummyPost.php
tests/Models/DummyPost.php
<?php namespace Froiden\RestAPI\Tests\Models; use Froiden\RestAPI\ApiModel; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class DummyPost extends ApiModel { protected $table = 'dummy_posts'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'post', 'user_id', ]; protected $filterable = [ 'post', 'user_id', ]; protected $dates = [ 'created_at', 'updated_at' ]; /** * Get the comments for the blog post. */ public function comments() { return $this->hasMany('Froiden\RestAPI\Tests\Models\DummyComment'); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Models/DummyUser.php
tests/Models/DummyUser.php
<?php namespace Froiden\RestAPI\Tests\Models; use Froiden\RestAPI\ApiModel; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class DummyUser extends ApiModel { protected $table = 'dummy_users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'age', ]; protected $filterable = [ 'name', 'email', 'age', ]; protected $dates = [ 'created_at', 'updated_at' ]; /** * Get the phone record associated with the user. */ public function phone() { return $this->hasOne('Froiden\RestAPI\Tests\Models\DummyPhone', 'user_id', 'id'); } /** * The posts that belong to the user. */ public function posts() { return $this->hasMany('Froiden\RestAPI\Tests\Models\DummyPost', 'user_id', 'id'); } /** * The comments that belong to the user. */ public function comments() { return $this->hasMany('Froiden\RestAPI\Tests\Models\DummyComment', 'user_id', 'id'); } }
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
Froiden/laravel-rest-api
https://github.com/Froiden/laravel-rest-api/blob/45e05076f8fc7918d70631369b02ed7168a6cb5d/tests/Factories/ModelFactory.php
tests/Factories/ModelFactory.php
<?php $factory->define( \Froiden\RestAPI\Tests\Models\DummyUser::class, function(Faker\Generator $faker){ return [ 'name' => $faker->name, 'email' => $faker->email, 'age' => $faker->randomDigitNotNull, ]; } ); $factory->define( \Froiden\RestAPI\Tests\Models\DummyPhone::class, function(Faker\Generator $faker){ return [ 'name' => $faker->name, 'modal_no' => $faker->swiftBicNumber, 'user_id' => \Froiden\RestAPI\Tests\Models\DummyUser::all()->random()->id, ]; } ); $factory->define(\Froiden\RestAPI\Tests\Models\DummyPost::class, function(Faker\Generator $faker) { $createFactory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); return [ 'post' => $faker->company, 'user_id' => \Froiden\RestAPI\Tests\Models\DummyUser::all()->random()->id, ]; } ); $factory->define(\Froiden\RestAPI\Tests\Models\DummyComment::class, function(Faker\Generator $faker) { $createFactory = \Illuminate\Database\Eloquent\Factory::construct(\Faker\Factory::create(), base_path() . '/laravel-rest-api/tests/Factories'); return [ 'comment' => $faker->text, 'user_id' => \Froiden\RestAPI\Tests\Models\DummyUser::all()->random()->id, 'post_id' => \Froiden\RestAPI\Tests\Models\DummyPost::all()->random()->id, ]; } );
php
MIT
45e05076f8fc7918d70631369b02ed7168a6cb5d
2026-01-05T04:52:55.517023Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/trello_integration/trello_integration.php
trello_integration/trello_integration.php
<?php // Get the environment; we will post a new comment to Trello each time // a commit appears on a new branch on Pantheon. $env = $_ENV['PANTHEON_ENVIRONMENT']; // Look up the secrets from the secrets file. $secrets = _get_secrets(array('trello_key', 'trello_token'), array()); // Get latest commit $current_commithash = shell_exec('git rev-parse HEAD'); $last_commithash = false; // Retrieve the last commit processed by this script $commit_file = $_SERVER['HOME'] . "/files/private/{$env}_trello_integration_commit.txt"; if (file_exists($commit_file)) { $last_processed_commithash = trim(file_get_contents($commit_file)); // We should (almost) always find our last commit still in the repository; // if the user has force-pushed a branch, though, then our last commit // may be overwritten. If this happens, only process the most recent commit. exec("git rev-parse $last_processed_commithash 2> /dev/null", $output, $status); if (!$status) { $last_commithash = $last_processed_commithash; } } // Update the last commit file with the latest commit file_put_contents($commit_file, $current_commithash, LOCK_EX); // Retrieve git log for commits after last processed, to current $commits = _get_commits($current_commithash, $last_commithash, $env); // Check each commit message for Trello card IDs foreach ($commits['trello'] as $card_id => $commit_ids) { foreach ($commit_ids as $commit_id) { send_commit($secrets, $card_id, $commits['history'][$commit_id]); } } /** * Do git operations to find all commits between the specified commit hashes, * and return an associative array containing all applicable commits that * contain references to Trello cards. */ function _get_commits($current_commithash, $last_commithash, $env) { $commits = array( // Raw output of git log since the last processed 'history_raw' => null, // Formatted array of commits being sent to Trello 'history' => array(), // An array keyed by Trello card id, each holding an // array of commit ids. 'trello' => array() ); $cmd = 'git log'; // add -p to include diff if (!$last_commithash) { $cmd .= ' -n 1'; } else { $cmd .= ' ' . $last_commithash . '...' . $current_commithash; } $commits['history_raw'] = shell_exec($cmd); // Parse raw history into an array of commits $history = preg_split('/^commit /m', $commits['history_raw'], -1, PREG_SPLIT_NO_EMPTY); foreach ($history as $str) { $commit = array( 'full' => 'Commit: ' . $str ); // Only interested in the lines before the diff now $lines = explode("\n", $str); $commit['id'] = $lines[0]; $commit['message'] = trim(implode("\n", array_slice($lines, 4))); $commit['formatted'] = 'Commit: ' . substr($commit['id'], 0, 10) . ' [' . $env . '] ' . $commit['message'] . ' ~' . $lines[1] . ' - ' . $lines[2]; // Look for matches on a Trello card ID format // = [8 characters] preg_match('/\[[a-zA-Z0-9]{8}\]/', $commit['message'], $matches); if (count($matches) > 0) { // Build the $commits['trello'] array so there is // only 1 item per ticket id foreach ($matches as $card_id_enc) { $card_id = substr($card_id_enc, 1, -1); if (!isset($commits['trello'][$card_id])) { $commits['trello'][$card_id] = array(); } // ... and only 1 item per commit id $commits['trello'][$card_id][$commit['id']] = $commit['id']; } // Add the commit to the history array since there was a match. $commits['history'][$commit['id']] = $commit; } } return $commits; } /** * Send commits to Trello */ function send_commit($secrets, $card_id, $commit) { $payload = array( 'text' => $commit['formatted'], 'key' => $secrets['trello_key'], 'token' => $secrets['trello_token'] ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.trello.com/1/cards/' . $card_id . '/actions/comments'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); print("\n==== Posting to Trello ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("\n===== Post Complete! =====\n"); curl_close($ch); } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file ['.$secretsFile.'] found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/slack_notification/slack_notification.php
slack_notification/slack_notification.php
<?php /** * Quicksilver Script: Slack Notification * Description: Send a notification to a Slack channel when code is deployed to Pantheon. */ /** * Configuration options. * * Make changes here to customize the behavior of your notification. * * $slack_channel The Slack channel to post to. * $type Determines the Slack API to use for the message. Expects 'attachments' or 'blocks'. Blocks is more modern (our attachment has blocks embedded in it), but Attachments allows the distinct sidebar color (below). * $secret_key The key for the Pantheon Secret containing the bot token. * $pantheon_yellow A color for the sidebar that appears to the left of the Slack message (if 'attachments' is the type used). */ $slack_channel = '#firehose'; $type = 'attachments'; $secret_key = 'slack_deploybot_token'; $pantheon_yellow = '#FFDC28'; /** * A basic { type, text } object to embed in a block * * @param string $text The text message to be sent to Slack. * @param string $type The type of notification to send. * @param string $block_type The type of block to be sent in the Slack message. * * @return array */ function _create_text_block( string $text = '', string $type = 'mrkdwn', string $block_type = 'section' ) { return [ 'type' => $block_type, 'text' => [ 'type' => $type, 'text' => $text, ], ]; } /** * A multi-column block of content (very likely 2 cols) * * @param array $fields The fields to send to the multi-column block. * @return array */ function _create_multi_block( array $fields ) { return [ 'type' => 'section', 'fields' => array_map( function( $field ) { return [ 'type' => 'mrkdwn', 'text' => $field, ]; }, $fields ) ]; } /** * Creates a context block for a Slack message. * * @param array $elements An array of text elements to be included in the context block. * @return array The context block formatted for a Slack message. */ function _create_context_block( array $elements ) { return [ 'type' => 'context', 'elements' => array_map( function( $element ) { return [ 'type' => 'mrkdwn', 'text' => $element, ]; }, $elements ), ]; } /** * A divider block * * @return array */ function _create_divider_block() { return ['type' => 'divider']; } /** * Some festive emoji for the Slack message based on the workflow we're running. * * @return array */ function _get_emoji() { // Edit these if you want to change or add to the emoji used in Slack messages. return [ 'deploy' => ':rocket:', 'sync_code' => ':computer:', 'sync_code_external_vcs' => ':computer:', 'clear_cache' => ':broom:', 'clone_database' => ':man-with-bunny-ears-partying:', 'deploy_product' => ':magic_wand:', 'create_cloud_development_environment' => ':lightning_cloud:', ]; } /** * Get the type of the current workflow from the $_POST superglobal. * * @return string */ function _get_workflow_type() { return $_POST['wf_type']; } /** * Extract a human-readable workflow name from the workflow type. * * @return string */ function _get_workflow_name() { return ucfirst(str_replace('_', ' ', _get_workflow_type())); } // Uncomment the following line to see the workflow type. // printf("Workflow type: %s\n", _get_workflow_type()); /** * Get Pantheon environment variables from the $_ENV superglobal. * * @return object */ function _get_pantheon_environment() { $pantheon_env = new stdClass; $pantheon_env->site_name = $_ENV['PANTHEON_SITE_NAME']; $pantheon_env->environment = $_ENV['PANTHEON_ENVIRONMENT']; return $pantheon_env; } /** * Create base blocks for all workflows. * * @return array */ function _create_base_blocks() { $icons = _get_emoji(); $workflow_type = _get_workflow_type(); $workflow_name = _get_workflow_name(); $environment = _get_pantheon_environment()->environment; $site_name = _get_pantheon_environment()->site_name; $blocks = [ _create_text_block( "{$icons[$workflow_type]} {$workflow_name}", 'plain_text', 'header' ), _create_multi_block([ "*Site:* <https://dashboard.pantheon.io/sites/" . PANTHEON_SITE . "#{$environment}/code|{$site_name}>", "*Environment:* <http://{$environment}-{$site_name}.pantheonsite.io|{$environment}>", "*Initiated by:* {$_POST['user_email']}", ]), ]; return $blocks; } /** * Add custom blocks based on the workflow type. * * Note that slack_notification.php must appear in your pantheon.yml for each workflow type you wish to send notifications on. * * @return array */ function _get_blocks_for_workflow() { $workflow_type = _get_workflow_type(); $blocks = _create_base_blocks(); $environment = _get_pantheon_environment()->environment; $site_name = _get_pantheon_environment()->site_name; switch ($workflow_type) { case 'deploy': $deploy_message = $_POST['deploy_message']; $blocks[] = _create_text_block("*Deploy Note:*\n{$deploy_message}"); break; case 'sync_code': case 'sync_code_external_vcs': // Get the time, committer, and message for the most recent commit $committer = trim(`git log -1 --pretty=%cn`); $hash = trim(`git log -1 --pretty=%h`); $message = trim(`git log -1 --pretty=%B`); $blocks[] = _create_multi_block([ "*Commit:* {$hash}", "*Committed by:* {$committer}", ]); $blocks[] = _create_text_block("*Commit Message:*\n{$message}"); break; case 'clear_cache': $blocks[] = _create_text_block("*Action:*\nCaches cleared on <http://{$environment}-{$site_name}.pantheonsite.io|{$environment}>."); break; case 'clone_database': $blocks[] = _create_multi_block([ "*Cloned from:* {$_POST['from_environment']}", "*Cloned to:* {$environment}", ]); break; default: $description = $_POST['qs_description'] ?? 'No additional details provided.'; $blocks[] = _create_text_block("*Description:*\n{$description}"); break; } // Add a divider block at the end of the message $blocks[] = _create_divider_block(); return $blocks; } // Uncomment to debug the blocks. // echo "Blocks:\n"; // print_r( _get_blocks_for_workflow() ); /** * Prepare Slack POST content as an attachment with yellow sidebar. * * @return array */ function _get_attachments() { global $pantheon_yellow; return [ [ 'color' => $pantheon_yellow, 'blocks' => _get_blocks_for_workflow(), ] ]; } // Uncomment the following line to debug the attachments array. // echo "Attachments:\n"; print_r( $attachments ); echo "\n"; /** * Send a notification to Slack */ function _post_to_slack() { global $slack_channel, $type, $secret_key; $attachments = _get_attachments(); $blocks = _get_blocks_for_workflow(); $slack_token = pantheon_get_secret($secret_key); $post['channel'] = $slack_channel; // Check the type and adjust the payload accordingly. if ( $type === 'attachments' ) { $post['attachments'] = $attachments; } elseif ( $type === 'blocks' ) { $post['blocks'] = $blocks; } else { throw new InvalidArgumentException("Unsupported type: $type"); } // Uncomment to debug the payload. // echo "Payload: " . json_encode($post, JSON_PRETTY_PRINT) . "\n"; $payload = json_encode($post); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/chat.postMessage'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $slack_token, 'Content-Type: application/json; charset=utf-8', ]); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); print("\n==== Posting to Slack ====\n"); $result = curl_exec($ch); $response = json_decode($result, true); if (!$response['ok']) { print("Error: " . $response['error'] . "\n"); error_log("Slack API error: " . $response['error']); } else { print("Message sent successfully!\n"); } curl_close($ch); } // Send the Slack notification _post_to_slack();
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/generate_dev_content/generate_dev_content.php
generate_dev_content/generate_dev_content.php
<?php // Generating Developer Content for "Article" Content Type // Only run this operation for development or multidev environments if (isset($_POST['environment']) && !in_array($_POST['environment'], array('test', 'live'))) { // Only run this operation if Devel and Devel Generate modules are available. // Enable the modules if they are not already enabled $modules = json_decode(shell_exec('drush pm-list --format=json')); if (isset($modules->devel) && isset($modules->devel_generate)) { if (isset($modules->devel) && $modules->devel->status !== 'Enabled') { passthru('drush pm-enable -y devel'); } if (isset($modules->devel_generate) && $modules->devel_generate->status !== 'Enabled') { passthru('drush pm-enable -y devel_generate'); } // Remove the existing production article content echo "Removing production article content...\n"; passthru('drush genc --kill --types=article 0 0'); echo "Removal complete.\n"; // Generate new development article content echo "Generating development article content...\n"; passthru('drush generate-content 20 --types=article'); echo "Generation complete.\n"; // Disable the Devel and Devel Generate modules as appropriate if (isset($modules->devel) && $modules->devel->status !== 'Enabled') { passthru('drush pm-disable -y devel'); } if (isset($modules->devel_generate) && $modules->devel_generate->status !== 'Enabled') { passthru('drush pm-disable -y devel_generate'); } } else { echo "The Devel and Devel Generate modules must be present for this operation to work"; } }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/debugging_example/debug.php
debugging_example/debug.php
<?php echo "Quicksilver Debugging Output"; echo "\n\n"; echo "\n========= START PAYLOAD ===========\n"; print_r($_POST); echo "\n========== END PAYLOAD ============\n"; echo "\n------- START ENVIRONMENT ---------\n"; $env = $_ENV; foreach ($env as $key => $value) { if (preg_match('#(PASSWORD|SALT|AUTH|SECURE|NONCE|LOGGED_IN)#', $key)) { $env[$key] = '[REDACTED]'; } } print_r($env); echo "\n-------- END ENVIRONMENT ----------\n";
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/wp_solr_index/wp_solr_power_index.php
wp_solr_index/wp_solr_power_index.php
<?php // Post Solr schema echo "Posting Solr Schema File...\n"; passthru('wp solr repost-schema'); // Get Solr Server Info echo "Getting Solr Server Info...\n"; passthru('wp solr info'); // Index Solr Power items echo "Indexing Solr Power Items...\n"; passthru('wp solr index'); echo "Indexing complete.\n";
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/autopilot/autopilot.php
autopilot/autopilot.php
<?php /** * @file * Sends Autopilot VRT Quicksilver hook data to Slack. */ // Retrieve Slack webhook config data $config_file = $_SERVER['HOME'] . '/files/private/autopilot.json'; $config = json_decode(file_get_contents($config_file), 1); if ($config == false) { die('files/private/autopilot.json found. Aborting!'); } // The Webhook URL for Slack. $webook_url = $config['webhook_url']; // Sample data used if no actual update info in $_POST, e.g. invoking script directly while testing/developing this script. $updates_info_raw = $_POST['updates_info'] ?? "{\"upstream_ids\": null, \"extension_list\": [{\"update_version\": \"8.x-2.8\", \"version\": \"8.x-2.7\", \"type\": \"module\", \"name\": \"layout_builder_restrictions\", \"title\": \"Layout Builder Restrictions (layout_builder_restrictions)\"}], \"ids\": [25684], \"extensions_commit_message\": \"Updated Modules (layout_builder_restrictions)\", \"current_core_version\": \"\", \"cms_ids\": [], \"new_core_version\": \"\"}"; // The update data has to be massaged a bit as it contains escaped characters. $escaped_data = str_replace("\u0022", "\\\"", $updates_info_raw ); $escaped_data = str_replace("\u0027", "\\'", $escaped_data ); // The data can now be decoded and analyzed. $updates_info = json_decode($updates_info_raw, TRUE); $extension_list = $updates_info['extension_list']; $number_of_extensions_updated = count($extension_list); // Loop through and build update data as a Slack markdown list. $update_list_markdown = "*Updates performed*\n"; foreach ($extension_list as $key => $val) { $update_list_markdown .= "- " . $val['title'] . ' updated from ' . $val['version'] . ' to ' . $val['update_version'] . " \n"; } // Get other info for the message. $wf_type = $_POST['wf_type']; $user_email = $_POST['user_email']; $site_id = $_POST['site_id']; $vrt_result_url = $_POST['vrt_result_url']; $status = $_POST['vrt_status']; $full_vrt_url_path = "https://dashboard.pantheon.io/" . $vrt_result_url; $site_name = $_ENV['PANTHEON_SITE_NAME']; $site_url_and_label = 'http://' . $_ENV['PANTHEON_ENVIRONMENT'] . '-' . $_ENV['PANTHEON_SITE_NAME'] . '.pantheonsite.io|' . $_ENV['PANTHEON_ENVIRONMENT']; $qs_description = $_POST['qs_description']; // Set an emoji based on pass state - star for pass, red flag for fail $emoji = $status == "pass" ? ":star:" : ":red-flag:"; // Construct the data for Slack message API. $message_data = [ "text" => "Autopilot VRT for " . $site_name, "blocks" => [ [ "type" => "section", "text" => [ "type" => "mrkdwn", "text" => "$emoji VRT Results $status for $site_name - $full_vrt_url_path", ] ], [ "type" => "section", "block_id" => "section2", "text" => [ "type" => "mrkdwn", "text" => "<$full_vrt_url_path|Review VRT Results for $site_name> \n The test state was: $emoji $status $emoji." ], "accessory" => [ "type" => "image", "image_url" => "https://pantheon.io/sites/all/themes/zeus/images/new-design/homepage/home-hero-webops-large.jpg", "alt_text" => "Pantheon image" ] ], [ "type" => "section", "block_id" => "section3", "fields" => [ [ "type" => "mrkdwn", "text" => $update_list_markdown, ] ] ] ] ]; // Encode the data into JSON to send to Slack. $message_data = json_encode($message_data); // Define the command that will send the curl to the Slack webhook with the constructed data. $command = "curl -s -X POST -H 'Content-type: application/json' --data '" . $message_data . "' $webook_url"; // Execute the command with var_dump, so we can see output if running terminus workflow:watch, which can help for debugging. var_dump(shell_exec("$command 2>&1"));
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/new_relic_monitor/new_relic_monitor.php
new_relic_monitor/new_relic_monitor.php
<?php // No need to log this script operation in New Relic's stats. // PROTIP: you might also want to use this snippet if you have PHP code handling // very fast things like redirects or the like. if (extension_loaded('newrelic')) { newrelic_ignore_transaction(); } define("API_KEY_SECRET_NAME", "new_relic_api_key"); // Initialize New Relic $nr = new NewRelic(); // Check for Live Deployments only. if ($_POST['wf_type'] == 'deploy' && $_ENV['PANTHEON_ENVIRONMENT'] == 'live') { // Create New Relic monitor. echo "Creating Synthethics Monitor in New Relic...\n"; $nr->createMonitor(); } else { die("\n\nAborting: Only run on live deployments."); } echo "Done!"; /** * Basic class for New Relic calls. */ class NewRelic { private $nr_app_name; // New Relic account info. private $api_key; // New Relic Admin Key public $site_uri; // Pantheon Site URI /** * Initialize class * * @param [string] $api_key New Relic Admin API key. */ function __construct() { $this->site_uri = 'https://' . $_ENV['PANTHEON_ENVIRONMENT'] . '-' . $_ENV['PANTHEON_SITE_NAME'] . '.pantheonsite.io'; if (function_exists('pantheon_get_secret')) { $this->api_key = pantheon_get_secret(API_KEY_SECRET_NAME); } $this->nr_app_name = ini_get('newrelic.appname'); // Fail fast if we're not going to be able to call New Relic. if ($this->api_key == false) { die("\n\nALERT! No New Relic API key could be found.\n\n"); } } /** * Get a list of monitors. * * @return [array] $data */ public function getMonitors() { $data = $this->curl('https://synthetics.newrelic.com/synthetics/api/v3/monitors?limit=50'); return $data; } /** * Get a list of ping locations. * * @return [array] $data */ public function getLocations() { $data = $this->curl('https://synthetics.newrelic.com/synthetics/api/v1/locations'); return $data; } /** * Validate if monitor for current environment already exists. * * @param [string] $id * @return boolean * * @todo Finish validating after getting Pro API key. */ public function validateMonitor($id) { $monitors = $this->getMonitors(); return in_array($id, $monitors['name']); } /** * Create a new ping monitor. * * @param integer $freq The frequency of pings in seconds. * @return void */ public function createMonitor($freq = 60) { // List of locations. $locations = $this->getLocations(); $body = [ 'name' => $this->nr_app_name, 'type' => 'SIMPLE', 'frequency' => $freq, 'uri' => $this->site_uri, 'locations' => [], 'status' => 'ENABLED', ]; $req = $this->curl('https://synthetics.newrelic.com/synthetics/api/v3/monitors', [], $body, 'POST'); print_r($req); } /** * Custom curl function for reusability. */ public function curl($url, $headers = [], $body = [], $method = 'GET') { // Initialize Curl. $ch = curl_init(); // Include NR API key $headers[] = 'X-Api-Key: ' . $this->api_key; // Add POST body if method requires. if ($method == 'POST') { $payload = json_encode($body); $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); curl_close($ch); // print("JSON: " . json_encode($post,JSON_PRETTY_PRINT)); // Uncomment to debug JSON return $result; } }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/pivotal-tracker/pivotal_integration.php
pivotal-tracker/pivotal_integration.php
<?php // Get the environment; we will post a new comment to Tracker each time a commit appears on Pantheon. $env = $_ENV['PANTHEON_ENVIRONMENT']; // Do not watch test or live, though. if (($env == 'live') || ($env == 'test')) { exit(0); } // Look up the secrets from the secrets file. $secrets = _get_secrets(array('tracker_token'), array()); // Get latest commit $current_commithash = shell_exec('git rev-parse HEAD'); $last_commithash = false; // Retrieve the last commit processed by this script $commit_file = $_SERVER['HOME'] . "/files/private/{$env}_pivotal_integration_commit.txt"; if (file_exists($commit_file)) { $last_processed_commithash = trim(file_get_contents($commit_file)); // We should (almost) always find our last commit still in the repository; // if the user has force-pushed a branch, though, then our last commit // may be overwritten. If this happens, only process the most recent commit. exec("git rev-parse $last_processed_commithash 2> /dev/null", $output, $status); if (!$status) { $last_commithash = $last_processed_commithash; } } // Update the last commit file with the latest commit file_put_contents($commit_file, $current_commithash, LOCK_EX); // Retrieve git log for commits after last processed, to current $commits = _get_commits($current_commithash, $last_commithash, $env); // Check each commit message for Pivotal ticket numbers foreach ($commits['pivotal'] as $ticket_id => $commit_ids) { foreach ($commit_ids as $commit_id) { send_commit($secrets, $commits['history'][$commit_id]); } } /** * Do git operations to find all commits between the specified commit hashes, * and return an associative array containing all applicable commits that * contain references to Pivotal Tracker issues. */ function _get_commits($current_commithash, $last_commithash, $env) { $commits = array( // Raw output of git log since the last processed 'history_raw' => null, // Formatted array of commits being sent to pivotal 'history' => array(), // An array keyed by pivotal ticket id, each holding an // array of commit ids. 'pivotal' => array() ); //builds command $cmd = 'git log'; // add -p to include diff if (!$last_commithash) { $cmd .= ' -n 1'; } else { $cmd .= ' ' . $last_commithash . '...' . $current_commithash; } $commits['history_raw'] = shell_exec($cmd); // Parse raw history into an array of commits $history = preg_split('/^commit /m', $commits['history_raw'], -1, PREG_SPLIT_NO_EMPTY); foreach ($history as $str) { $commit = array( 'full' => 'Commit: ' . $str ); // Only interested in the lines before the diff now $lines = explode("\n", $str); $commit['id'] = $lines[0]; $commit['message'] = trim(implode("\n", array_slice($lines, 4))); $commit['formatted'] = $commit['message'] . " " . $lines[1] . ' - ' . $lines[2]; // Look for matches in commit based on Pivotal Tracker issue ID format // Expected pattern: "[#12345678] commit message" or "[fixed|completed|finished #12345678 message]" preg_match('/\[[^#]*#\K\d{1,16}/', $commit['message'], $matches); if (count($matches) > 0) { // Build the $commits['pivotal'] array so there is // only 1 item per ticket id foreach ($matches as $ticket_id) { if (!isset($commits['pivotal'][$ticket_id])) { $commits['pivotal'][$ticket_id] = array(); } // ... and only 1 item per commit id $commits['pivotal'][$ticket_id][$commit['id']] = $commit['id']; } // Add the commit to the history array since there was a match. $commits['history'][$commit['id']] = $commit; } } return $commits; } /** * Send commits to Pivotal */ function send_commit($secrets, $commit) { print("\n==== Posting to Pivotal Tracker ====\n"); // Sends commit to pivotal. $ch = 'curl -X POST -H "X-TrackerToken: '. $secrets['tracker_token'] . '" -H "Content-Type: application/json" -d \'{"source_commit":{"commit_id":"' . substr($commit['id'], 0, 10) . '","message":"' . $commit['formatted'] . '"}\' "https://www.pivotaltracker.com/services/v5/source_commits?fields=%3Adefault%2Ccomments"'; $result = shell_exec($ch); print("RESULT: $result"); print("\n===== Post Complete! =====\n"); } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/drush_config_import/drush_config_import.php
drush_config_import/drush_config_import.php
<?php // Import all config changes. echo "Importing configuration from yml files...\n"; passthru('drush config-import -y'); echo "Import of configuration complete.\n"; //Clear all cache echo "Rebuilding cache.\n"; passthru('drush cr'); echo "Rebuilding cache complete.\n";
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/google_chat_notification/google_chat_notification.php
google_chat_notification/google_chat_notification.php
<?php // Run Google Chat notification. new GoogleChatNotification(); class GoogleChatNotification { // Build a set of fields to be rendered with Google Chat. // https://developers.google.com/chat/api/reference/rest/v1/spaces.messages public $webhook_url; public $secrets; public $site_name; public $site_env; public $site_id; public $user_email; public $user_fullname; public $workflow_type; public $workflow_description; public $workflow_id; public $workflow_stage; public $quicksilver_description; public $workflow_label; public $workflow; public $environment_link; public $dashboard_link; public function __construct() { // Ensure we're in Pantheon context. if ($this->isPantheon() && $this->isQuicksilver()) { $this->webhook_url = $this->getSecret('google_chat_webhook'); $this->setQuicksilverVariables(); // Get Workflow message $data = $this->prepareOutputByWorkflow($this->workflow_type); $this->send($data); } } /** * Get the Pantheon site name. * @return string|null */ public function getPantheonSiteName(): ?string { return !empty($_ENV['PANTHEON_SITE_NAME']) ? $_ENV['PANTHEON_SITE_NAME'] : NULL; } /** * Get the Pantheon site id. * @return string|null */ public function getPantheonSiteId(): ?string { return !empty($_ENV['PANTHEON_SITE']) ? $_ENV['PANTHEON_SITE'] : NULL; } /** * Get the Pantheon environment. * @return string|null */ public function getPantheonEnvironment(): ?string { return !empty($_ENV['PANTHEON_ENVIRONMENT']) ? $_ENV['PANTHEON_ENVIRONMENT'] : NULL; } /** * Check if in the Pantheon site context. * @return bool|void */ public function isPantheon() { if ($this->getPantheonSiteName() !== NULL && $this->getPantheonEnvironment() !== NULL) { return TRUE; } die('No Pantheon environment detected.'); } /** * Check if in the Quicksilver context. * @return bool|void */ public function isQuicksilver() { if ($this->isPantheon() && !empty($_POST['wf_type'])) { return TRUE; } die('No Pantheon Quicksilver environment detected.'); } /** * Set Quicksilver variables from POST data. * @return void */ public function setQuicksilverVariables() { $this->site_name = $this->getPantheonSiteName(); $this->site_id = $this->getPantheonSiteId(); $this->site_env = $this->getPantheonEnvironment(); $this->user_fullname = $_POST['user_fullname']; $this->user_email = $_POST['user_email']; $this->workflow_id = $_POST['trace_id']; $this->workflow_description = $_POST['wf_description']; $this->workflow_type = $_POST['wf_type']; $this->workflow_stage = $_POST['stage']; $this->workflow = ucfirst($this->workflow_stage) . ' ' . str_replace('_', ' ', $this->workflow_type); $this->workflow_label = "Quicksilver workflow"; $this->quicksilver_description = $_POST['qs_description']; $this->environment_link = "https://$this->site_env-$this->site_name.pantheonsite.io"; $this->dashboard_link = "https://dashboard.pantheon.io/sites/$this->site_id#$this->site_env"; } /** * Load secrets from secrets file. */ public function getSecrets() { if (empty($this->secrets)) { $secretsFile = $_ENV['HOME'] . 'files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, TRUE); if (!$secrets) { die('Could not parse json in secrets file. Aborting!'); } $this->secrets = $secrets; } return $this->secrets; } /** * @param string $key Key in secrets that must exist. * @return mixed|void */ public function getSecret(string $key) { $secrets = $this->getSecrets(); $missing = array_diff([$key], array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets[$key]; } /** * @param string $workflow * @return array|null|string */ public function prepareOutputByWorkflow(string $workflow): ?array { switch ($workflow) { case 'sync_code': $this->workflow_label = "Sync code"; $output = $this->syncCodeOutput(); break; case 'deploy_product': $this->workflow_label = "Create new site"; $output = $this->deployProductOutput(); break; case 'deploy': $this->workflow_label = "Code or data deploys targeting an environment"; $output = $this->deployOutput(); break; case 'create_cloud_development_environment': $this->workflow_label = "Create multidev environment"; $output = $this->createMultidevOutput(); break; case 'clone_database': $this->workflow_label = "Clone database and files"; $output = $this->cloneDatabaseOutput(); break; case 'clear_cache': $this->workflow_label = "Clear site cache"; $output = $this->clearCacheOutput(); break; case 'autopilot_vrt': $this->workflow_label = "Autopilot visual regression test"; $output = $this->autopilotVrtOutput(); break; default: $output = $this->defaultOutput(); break; } return $output; } /** * @param array $cards * @return array[] */ public function createCardPayload(array $cards): array { return ['cards_v2' => [(object) $cards]]; } /** * @param string $id * @return array */ public function createCardTemplate(string $id): array { return [ 'card_id' => $id, 'card' => [], ]; } /** * @param array $buttons * @return array[][] */ public function createCardButtonList(array $buttons): array { return [ 'buttonList' => [ 'buttons' => $buttons, ], ]; } /** * @param $text * @param $url * @return array */ public function createCardButton($text, $url): array { return [ 'text' => $text, 'onClick' => [ 'openLink' => [ 'url' => $url, ], ], ]; } /** * Create common buttons for different workflows. * @return array */ public function createCommonButtons(): array { $dashboard_button = $this->createCardButton('View Dashboard', $this->dashboard_link); $environment_button = $this->createCardButton('View Site Environment', $this->environment_link); return [$dashboard_button, $environment_button]; } /** * @return array[] Divider element. */ public function createDivider(): array { return [ 'divider' => (object) array() ]; } /** * @param string $text * @return string[][] */ public function createDecoratedText(string $text): array { return [ 'decoratedText' => [ 'text' => $text, ] ]; } /** * @param $title * @param $subtitle * @param string $image_url * @param string $image_type * @return array */ public function createCardHeader($title, $subtitle = null, string $image_url = "https://avatars.githubusercontent.com/u/88005016", string $image_type = "CIRCLE" ): array { return [ 'title' => $title, 'subtitle' => $subtitle, 'imageUrl' => $image_url, 'imageType' => $image_type, ]; } /** * @param string $messageText * @param array $buttons * @return array */ public function prepareCardOutput(string $messageText, array $buttons = []): array { $cardTemplate = $this->createCardTemplate($this->workflow_id); $cardTemplate['card']['header'] = $this->createCardHeader($this->quicksilver_description, $this->workflow_label); // Create card widgets. $widgets = []; $widgets[] = $this->createDecoratedText(trim($messageText)); if (!empty($buttons)) { $widgets[] = $this->createDivider(); $widgets[] = $this->createCardButtonList($buttons); } $cardTemplate['card']['sections'] = ['widgets' => $widgets]; return $cardTemplate; } /** * @param array $post * @return void */ public function send(array $post) { $payload = json_encode($post, JSON_PRETTY_PRINT); print_r($payload); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->webhook_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // Watch for messages with `terminus workflows watch --site=SITENAME` print("\n==== Posting to Google Chat ====\n"); $result = curl_exec($ch); print("RESULT: $result"); // $payload_pretty = json_encode($post,JSON_PRETTY_PRINT); // Uncomment to debug JSON // print("JSON: $payload_pretty"); // Uncomment to Debug JSON print("\n===== Post Complete! =====\n"); curl_close($ch); } /** * Get output from shell commands. * @param $cmd * @return string */ public function getCommandOutput($cmd): string { $command = escapeshellcmd($cmd); return trim(shell_exec($command)); } /** * Generate message for sync_code workflow. * @return array[] */ public function syncCodeOutput(): array { // Get the committer, hash, and message for the most recent commit. $committer = $this->getCommandOutput('git log -1 --pretty=%cn'); $email = $this->getCommandOutput('git log -1 --pretty=%ce'); $message = $this->getCommandOutput('git log -1 --pretty=%B'); $hash = $this->getCommandOutput('git log -1 --pretty=%h'); $text = <<<MSG <b>Committer:</b> $committer ($email) <b>Commit:</b> $hash <b>Commit Message:</b> $message MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate message for deploy_product workflow. * @return array[]|object[][] */ public function deployProductOutput(): array { $text = <<<MSG New site created! <b>Site name:</b> $this->site_name <b>Created by:</b> $this->user_email MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate message for deploy workflow. * @return array[]|object[][] */ public function deployOutput(): array { // Find out what tag we are on and get the annotation. $deploy_tag = $this->getCommandOutput('git describe --tags'); $deploy_message = $_POST['deploy_message']; $text = <<<MSG Deploy to the $this->site_env environment of $this->site_name by $this->user_email is complete! <b>Deploy Tag:</b> $deploy_tag <b>Deploy Note:</b> $deploy_message MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate message for create_cloud_development_environment workflow. * @return array[]|object[][] */ public function createMultidevOutput(): array { $text = <<<MSG New multidev environment created! <b>Environment name:</b> $this->site_env <b>Created by:</b> $this->user_email MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate message for clone_database workflow. * @return array[]|object[][] */ public function cloneDatabaseOutput(): array { $to = $_POST['to_environment']; $from = $_POST['from_environment']; $text = <<<MSG <b>From environment:</b> $from <b>To environment:</b> $to <b>Started by:</b> $this->user_email MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate message for clear_cache workflow. * @return array[]|object[][] */ public function clearCacheOutput(): array { $text = "Cleared caches on the $this->site_env environment of $this->site_name!"; $card = $this->prepareCardOutput($text); return $this->createCardPayload($card); } /** * Generate message for autopilot_vrt workflow. * @return array[]|object[][] */ public function autopilotVrtOutput(): array { $status = $_POST['vrt_status']; $result_url = $_POST['vrt_result_url']; $updates_info = $_POST['updates_info']; $text = <<<MSG <b>Status:</b> $status <b>Report:</b> <a href="$result_url">View VRT Report</a> <b>Started by:</b> $this->user_email MSG; $card = $this->prepareCardOutput($text, $this->createCommonButtons()); return $this->createCardPayload($card); } /** * Generate default output for undefined workflows. * @return array */ public function defaultOutput(): array { return ['text' => $this->quicksilver_description ]; } }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/url_checker/url_checker.php
url_checker/url_checker.php
<?php // Make note of the site and environment we are running on. $env = $_ENV['PANTHEON_ENVIRONMENT']; $site = $_ENV['PANTHEON_SITE_NAME']; // Read our configuration file (or die) $config = url_checker_get_config(); // If we are not running in the live environment, or if there // is no 'base_url' defined in config.json, then generate an // appropriate URL for this current environment. if (($_ENV['PANTHEON_ENVIRONMENT'] != 'live') || !isset($config['base_url'])) { $config['base_url'] = 'http://' . $env . '-' . $site . '.pantheonsite.io'; } // If the base url does not end in a '/', then add one to the end. if ($config['base_url'][strlen($config['base_url']) - 1] != '/') { $config['base_url'] .= '/'; } if (!isset($config['check_paths']) || empty($config['check_paths'])) { die('Must define configuration paths to test in "check_paths" element of config.json.'); } $failed = 0; $results = array(); foreach ($config['check_paths'] as $path) { $status = url_checker_test_url($config['base_url'] . $path); $results[] = array( 'url' => $config['base_url'] . $path, 'status' => $status ); if ($status != 200) { $failed++; } } $output = url_checker_build_output($results, $failed); print $output; // If there were any URLs that could not be accessed, and if an email // address is configured in config.json, then send a notification email. if (($failed > 0) && (isset($config['email']))) { $subject = 'Failed status check (' . $failed . ')'; $message = "Below is a list of each tested url and its status:\n\n"; $message .= $output; $acceptedForDelivery = mail($config['email'], $subject, $message); if ($acceptedForDelivery) { print "Sent email to {$config['email']}.\n"; } else { print "Notification email to {$config['email']} could not be queued for delivery.\n"; } } /** * Returns decoded config defined in config.json */ function url_checker_get_config() { $config_file = __DIR__ . '/config.json'; if (!file_exists($config_file)) { die('Config file not found.'); } $config_file_contents = file_get_contents($config_file); if (empty($config_file_contents)) { die('Config file could not be read.'); } $config = json_decode($config_file_contents); if (!$config) { die('Config file did not contain valid json.'); } // Convert json object to an array. return (array) $config; } /** * Constructs workflow output */ function url_checker_build_output($results, $failed) { $output = "\nURL Checks\n--------\n"; foreach ($results as $item) { $output .= ' ' . $item['status'] . ' - ' . $item['url'] . "\n"; } $output .= "--------\n" . $failed . " failed\n\n"; return $output; } /** * Try to access the specified URL, and return the http status code. */ function url_checker_test_url($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); return $info['http_code']; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/wp_cfm_import/wp_cfm_after_clone.php
wp_cfm_import/wp_cfm_after_clone.php
<?php print( "\n==== WP-CFM Config Import Starting ====\n" ); // Activate the wp-cfm plugin exec( 'wp plugin activate wp-cfm 2>&1' ); // Automagically import config into WP-CFM site upon code deployment $path = $_SERVER['DOCUMENT_ROOT'] . '/private/config'; $files = scandir( $path ); $files = array_diff( scandir( $path ), array( '.', '..' ) ); // Import all config .json files in private/config foreach( $files as $file ){ $file_parts = pathinfo($file); if( $file_parts['extension'] != 'json' ){ continue; } exec( 'wp config pull ' . $file_parts['filename'] . ' 2>&1', $output ); if ( count( $output ) > 0 ) { $output = preg_replace( '/\s+/', ' ', array_slice( $output, 1, - 1 ) ); $output = str_replace( ' update', ' [update]', $output ); $output = str_replace( ' create', ' [create]', $output ); $output = str_replace( ' delete', ' [delete]', $output ); $output = implode( $output, "\n" ); $output = rtrim( $output ); } } // Flush the cache exec( 'wp cache flush' ); print( "\n==== WP-CFM Config Import Complete ====\n" );
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/wp_cfm_import/alter_wpcfm_config_path.php
wp_cfm_import/alter_wpcfm_config_path.php
<?php /* Plugin Name: Alter-wpcfm-config-path Plugin URI: http://www.eyesopen.ca Description: Alters the wpcfm config path Version: 0.1 Author: Grant McInnes Author URI: http://www.eyesopen.ca */ // Tell wp-cfm where our config files live add_filter('wpcfm_config_dir', function($var) { return $_SERVER['DOCUMENT_ROOT'] . '/private/config'; }); add_filter('wpcfm_config_url', function($var) { return WP_HOME . '/private/config'; });
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/drush_revert_features/revert_all_features.php
drush_revert_features/revert_all_features.php
<?php //Revert all features echo "Reverting all features...\n"; passthru('drush fra -y'); echo "Reverting complete.\n"; //Clear all cache echo "Clearing cache.\n"; passthru('drush cc all'); echo "Clearing cache complete.\n";
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/webhook/webhook.php
webhook/webhook.php
<?php // Define the url the data should be sent to. // {wf_type} will be replaced with the workflow operation: // clone_database, clear_cache, deploy, or sync_code. // // Useful to have one webhook handle multiple events. // e.g. https://ifttt.com/maker $url = 'http://example.com/quicksilver/{wf_type}'; $payload = $_POST; // Add the site name to the payload in case the receiving app handles // multiple sites. You can enhance this payload with more data as // needed at this point. $payload['site_name'] = $_ENV['PANTHEON_SITE_NAME']; $payload = http_build_query($payload); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, str_replace('{event}', $_POST['wf_type'], $url)); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); print("\n==== Posting to Webhook URL ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("\n===== Post Complete! =====\n"); curl_close($ch);
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/new_relic_apdex_t/new_relic_apdex_t.php
new_relic_apdex_t/new_relic_apdex_t.php
<?php /** * @file * Sets New Relic Apdex T values for newly created multidev environments. */ define("API_KEY_SECRET_NAME", "new_relic_api_key"); // get New Relic info from the dev environment // Change to test or live as you wish $app_info = get_app_info( 'dev' ); $settings = $app_info['settings']; // The "t" value (number of seconds) for your server-side apdex. // https://docs.newrelic.com/docs/apm/new-relic-apm/apdex/apdex-measuring-user-satisfaction $app_apdex_threshold = $app_info['settings']['app_apdex_threshold']; // Do you want New Relic to add JavaScript to pages to analyze rendering time? // https://newrelic.com/browser-monitoring $enable_real_user_monitoring = $app_info['settings']['enable_real_user_monitoring']; // The "t" value (number of seconds) for browser apdex. (The "real user // monitoring turned off or on with $enable_real_user_monitoring") $end_user_apdex_threshold = $app_info['settings']['end_user_apdex_threshold']; set_thresholds( $app_apdex_threshold, $end_user_apdex_threshold, $enable_real_user_monitoring ); /** * Gets the New Relic API Key so that further requests can be made. * * Also gets New Relic's name for the given environment. */ function get_nr_connection_info() { $output = array(); $output['app_name'] = ini_get('newrelic.appname'); if (function_exists('pantheon_get_secret')) { $output['api_key'] = pantheon_get_secret(API_KEY_SECRET_NAME); } return $output; } /** * Get the id of the current multidev environment. */ function get_app_id( $api_key, $app_name ) { $return = ''; $s = curl_init(); curl_setopt( $s, CURLOPT_URL, 'https://api.newrelic.com/v2/applications.json' ); curl_setopt( $s, CURLOPT_HTTPHEADER, array( 'X-API-KEY:' . $api_key ) ); curl_setopt( $s, CURLOPT_RETURNTRANSFER, 1 ); $result = curl_exec( $s ); curl_close( $s ); $result = json_decode( $result, true ); foreach ( $result['applications'] as $application ) { if ( $application['name'] === $app_name ) { $return = $application['id']; break; } } return $return; } /** * Get New Relic information about a given environment. * * Used to retrive T values for a pre-existing environment. */ function get_app_info( $env = 'dev' ) { $nr_connection_info = get_nr_connection_info(); if ( empty( $nr_connection_info ) ) { echo "Unable to get New Relic connection info\n"; return; } $api_key = $nr_connection_info['api_key']; $app_name = $nr_connection_info['app_name']; $app_id = get_app_id( $api_key, $app_name ); $url = "https://api.newrelic.com/v2/applications/$app_id.json"; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); $headers = [ 'X-API-KEY:' . $api_key ]; curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); $response = curl_exec( $ch ); if ( curl_errno( $ch ) ) { echo 'Error:' . curl_error( $ch ); } curl_close( $ch ); $output = json_decode( $response, true ); return $output['application']; } /** * Sets the apdex thresholds. */ function set_thresholds( $app_apdex_threshold, $end_user_apdex_threshold, $enable_real_user_monitoring ) { $nr_connection_info = get_nr_connection_info(); if ( empty( $nr_connection_info ) ) { echo "Unable to get New Relic connection info\n"; return; } $api_key = $nr_connection_info['api_key']; $app_name = $nr_connection_info['app_name']; $app_id = get_app_id( $api_key, $app_name ); echo "===== Setting New Relic Values for the App '$app_name' =====\n"; echo "Application Apdex Threshold: $app_apdex_threshold\n"; echo "End User Apdex Threshold: $end_user_apdex_threshold\n"; echo "Enable Real User Monitoring: $enable_real_user_monitoring\n"; $url = 'https://api.newrelic.com/v2/applications/' . $app_id . '.json'; $settings = [ 'application' => [ 'name' => $app_name, 'settings' => [ 'app_apdex_threshold' => $app_apdex_threshold, 'end_user_apdex_threshold' => $end_user_apdex_threshold, 'enable_real_user_monitoring' => $enable_real_user_monitoring, ], ], ]; $data_json = json_encode( $settings ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_json ); curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" ); $headers = [ 'X-API-KEY:' . $api_key, 'Content-Type: application/json' ]; curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); $result = curl_exec( $ch ); if ( curl_errno( $ch ) ) { echo 'Error:' . curl_error( $ch ); } curl_close( $ch ); echo "===== Finished Setting New Relic Values =====\n"; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/db_sanitization/db_sanitization_wordpress.php
db_sanitization/db_sanitization_wordpress.php
<?php // Don't ever santize the database on the live environment. Doing so would // destroy the canonical version of the data. if (defined('PANTHEON_ENVIRONMENT') && (PANTHEON_ENVIRONMENT !== 'live')) { // Bootstrap WordPress. require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'; global $wpdb; // Query the database to set all user's email addresses to username@localhost. $wpdb->query("UPDATE wp_users SET user_email = CONCAT(user_login, '@localhost'), user_pass = MD5(CONCAT('MILDSECRET', user_login)), user_activation_key = '';"); }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/db_sanitization/db_sanitization_drupal.php
db_sanitization/db_sanitization_drupal.php
<?php // Don't ever sanitize the database on the live environment. Doing so would // destroy the canonical version of the data. if (defined('PANTHEON_ENVIRONMENT') && (PANTHEON_ENVIRONMENT !== 'live')) { // Run the Drush command to sanitize the database. echo "Sanitizing the database...\n"; passthru('drush sql-sanitize -y'); echo "Database sanitization complete.\n"; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/new_relic_deploy/new_relic_deploy.php
new_relic_deploy/new_relic_deploy.php
<?php // No need to log this script operation in New Relic's stats. // PROTIP: you might also want to use this snippet if you have PHP code handling // very fast things like redirects or the like. if (extension_loaded('newrelic')) { newrelic_ignore_transaction(); } define("API_KEY_SECRET_NAME", "new_relic_api_key"); $data = get_nr_connection_info(); // Fail fast if we're not going to be able to call New Relic. if ($data == false) { echo "\n\nALERT! No New Relic metadata could be found.\n\n"; exit(); } $app_guid = get_app_guid($data['api_key'], $data['app_name']); if (empty($app_guid)) { echo "Error: No New Relic app found with name " . $data['app_name']; exit(); } // This is one example that handles code pushes, dashboard // commits, and deploys between environments. To make sure we // have good deploy markers, we gather data differently depending // on the context. if (in_array($_POST['wf_type'], ['sync_code','sync_code_with_build'])) { // commit 'subject' $description = trim(`git log --pretty=format:"%s" -1`); $revision = trim(`git log --pretty=format:"%h" -1`); if ($_POST['user_role'] == 'super') { // This indicates an in-dashboard SFTP commit. $user = trim(`git log --pretty=format:"%ae" -1`); $changelog = trim(`git log --pretty=format:"%b" -1`); $changelog .= ' (Commit made via Pantheon dashboard.)'; } else { $user = $_POST['user_email']; $changelog = trim(`git log --pretty=format:"%b" -1`); $changelog .= ' (Triggered by remote git push.)'; } } elseif ($_POST['wf_type'] == 'deploy') { // Topline description: $description = 'Deploy to environment triggered via Pantheon'; // Find out if there's a deploy tag: $revision = `git describe --tags --abbrev=0`; // Get the annotation: $changelog = `git tag -l -n99 $revision`; $user = $_POST['user_email']; } // clean up the git output $revision = rtrim($revision, "\n"); $changelog = rtrim($changelog, "\n"); $changelog = str_replace('\'','',$changelog); $changelog = str_replace('"','',$changelog); $deployment_data = [ "deployment" => [ "revision" => $revision, "changelog" => $changelog, "description" => $description, "user" => $user, ] ]; echo "Logging deployment in New Relic App $app_guid...\n"; $response = create_newrelic_deployment_change_tracking($data['api_key'], $app_guid, $user, $revision, $changelog, $description); echo "\nResponse from New Relic:" . $response; echo "\nDone!\n"; /** * Gets the New Relic API Key so that further requests can be made. * * Also gets New Relic's name for the given environment. */ function get_nr_connection_info() { $output = array(); $output['app_name'] = ini_get('newrelic.appname'); if (function_exists('pantheon_get_secret')) { $output['api_key'] = pantheon_get_secret(API_KEY_SECRET_NAME); } return $output; } // Get GUID of the current environment. function get_app_guid(string $api_key, string $app_name): string { $url = 'https://api.newrelic.com/graphql'; $headers = ['Content-Type: application/json', 'API-Key: ' . $api_key]; // Updated entitySearch query with name filter $data = '{ "query": "{ actor { entitySearch(query: \\"(domain = \'APM\' and type = \'APPLICATION\' and name = \'' . $app_name . '\')\\") { count query results { entities { entityType name guid } } } } }" }'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); $decoded_response = json_decode($response, true); // Error handling for API response. if (isset($decoded_response['errors'])) { echo "Error: " . $decoded_response['errors'][0]['message'] . "\n"; return ''; } if (!isset($decoded_response['data']['actor']['entitySearch']['results']['entities']) || !is_array($decoded_response['data']['actor']['entitySearch']['results']['entities'])) { echo "Error: No entities found in New Relic response\n"; return ''; } $entities = $decoded_response['data']['actor']['entitySearch']['results']['entities']; // Since we filtered by name, the first entity should be the correct one. if (isset($entities[0]['guid'])) { return $entities[0]['guid']; } return ''; } function create_newrelic_deployment_change_tracking(string $api_key, string $entityGuid, string $user, string $version, string $changelog, string $description): string { $url = 'https://api.newrelic.com/graphql'; $headers = ['Content-Type: application/json', 'API-Key: ' . $api_key]; $timestamp = round(microtime(true) * 1000); // Construct the mutation with dynamic variables $data = '{ "query": "mutation { changeTrackingCreateDeployment(deployment: { version: \\"' . $version . '\\" user: \\"' . $user . '\\" timestamp: ' . $timestamp . ' entityGuid: \\"' . $entityGuid . '\\" description: \\"' . $description . '\\" changelog: \\"' . $changelog . '\\" }) { changelog deploymentId description entityGuid timestamp user version } }" }'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); return $response; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/wp_search_replace/wp_search_replace.php
wp_search_replace/wp_search_replace.php
<?php echo "Replacing previous environment urls with new environment urls... \n"; if ( ! empty( $_ENV['PANTHEON_ENVIRONMENT'] ) ) { switch( $_ENV['PANTHEON_ENVIRONMENT'] ) { case 'live': passthru('wp search-replace "://test-example.pantheonsite.io" "://example.com" --all-tables '); break; case 'test': passthru('wp search-replace "://example1.pantheonsite.io" "://test-examplesite.pantheonsite.io" --all-tables '); passthru('wp search-replace "://example2.pantheonsite.io" "://test-examplesite.pantheonsite.io" --all-tables '); passthru('wp search-replace "://example3.pantheonsite.io" "://test-examplesite.pantheonsite.io" --all-tables '); break; } } ?>
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/asana_integration/asana_integration.php
asana_integration/asana_integration.php
<?php // Get the environment; we will post a new comment to Asana each time // a commit appears on a new branch on Pantheon. $env = $_ENV['PANTHEON_ENVIRONMENT']; // Do not watch test or live, though. if (($env == 'live') || ($env == 'test')) { exit(0); } // Look up the secrets from the secrets file. $secrets = _get_secrets(array('asana_access_token'), array()); // Get latest commit $current_commithash = shell_exec('git rev-parse HEAD'); $last_commithash = false; // Retrieve the last commit processed by this script $commit_file = $_SERVER['HOME'] . "/files/private/{$env}_asana_integration_commit.txt"; if (file_exists($commit_file)) { $last_processed_commithash = trim(file_get_contents($commit_file)); // We should (almost) always find our last commit still in the repository; // if the user has force-pushed a branch, though, then our last commit // may be overwritten. If this happens, only process the most recent commit. exec("git rev-parse $last_processed_commithash 2> /dev/null", $output, $status); if (!$status) { $last_commithash = $last_processed_commithash; } } // Update the last commit file with the latest commit file_put_contents($commit_file, $current_commithash, LOCK_EX); // Retrieve git log for commits after last processed, to current $commits = _get_commits($current_commithash, $last_commithash, $env); // Check each commit message for Asana task IDs foreach ($commits['asana'] as $task_id => $commit_ids) { foreach ($commit_ids as $commit_id) { send_commit($secrets, $task_id, $commits['history'][$commit_id]); } } /** * Do git operations to find all commits between the specified commit hashes, * and return an associative array containing all applicable commits that * contain references to Asana tasks. */ function _get_commits($current_commithash, $last_commithash, $env) { $commits = array( // Raw output of git log since the last processed 'history_raw' => null, // Formatted array of commits being sent to Asana 'history' => array(), // An array keyed by Asana task id, each holding an // array of commit ids. 'asana' => array() ); $cmd = 'git log'; // add -p to include diff if (!$last_commithash) { $cmd .= ' -n 1'; } else { $cmd .= ' ' . $last_commithash . '...' . $current_commithash; } $commits['history_raw'] = shell_exec($cmd); // Parse raw history into an array of commits $history = preg_split('/^commit /m', $commits['history_raw'], -1, PREG_SPLIT_NO_EMPTY); foreach ($history as $str) { $commit = array( 'full' => 'Commit: ' . $str ); // Only interested in the lines before the diff now $lines = explode("\n", $str); $commit['id'] = $lines[0]; $commit['message'] = trim(implode("\n", array_slice($lines, 4))); $commit['formatted'] = 'Commit: ' . substr($commit['id'], 0, 10) . ' [' . $env . '] ' . $commit['message'] . ' ~' . $lines[1] . ' - ' . $lines[2]; // Look for matches on a Asana task ID format // = [number] preg_match('/\[[0-9]+\]/', $commit['message'], $matches); if (count($matches) > 0) { // Build the $commits['asana'] array so there is // only 1 item per ticket id foreach ($matches as $task_id_enc) { $task_id = substr($task_id_enc, 1, -1); if (!isset($commits['asana'][$task_id])) { $commits['asana'][$task_id] = array(); } // ... and only 1 item per commit id $commits['asana'][$task_id][$commit['id']] = $commit['id']; } // Add the commit to the history array since there was a match. $commits['history'][$commit['id']] = $commit; } } return $commits; } /** * Send commits to Asana */ function send_commit($secrets, $task_id, $commit) { $payload = array( 'text' => $commit['formatted'] ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://app.asana.com/api/1.0/tasks/' . $task_id . '/stories'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$secrets['asana_access_token'])); print("\n==== Posting to Asana ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("\n===== Post Complete! =====\n"); curl_close($ch); } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file ['.$secretsFile.'] found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/jenkins/jenkins_integration.php
jenkins/jenkins_integration.php
<?php // Load a secrets file. // See the included example.secrets.json and instructions in README. $secrets = _get_secrets('secrets.json'); //Create curl post request to hit the Jenkins webhook $curl = curl_init($secrets['jenkins_url']); //Setup header with authentication curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '. base64_encode($secrets['username'] . ":" . $secrets['api_token']), )); //Declare request as a post and setup the fields curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, array( 'token' => $secrets->token, )); //Execute the request $response = curl_exec($curl); // TODO: could produce some richer responses here. // Could even chain this to a slack notification. It's up to you! if ($response) { echo "Build Queued"; } else { echo "Build Failed"; } /** * Get secrets from secrets file. * * @param string $file path within files/private that has your json */ function _get_secrets($file) { $secrets_file = $_SERVER['HOME'] . '/files/private/' . $file; if (!file_exists($secrets_file)) { die('No secrets file found. Aborting!'); } $secrets_json = file_get_contents($secrets_file); $secrets = json_decode($secrets_json, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } return $secrets; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/cloudflare_cache/cloudflare_cache.php
cloudflare_cache/cloudflare_cache.php
<?php // TODO: this header should not be required... header('Content-Type: text/plain; charset=UTF-8'); // Only purge Cloudflare cache when the live environment's cache is cleared. if ($_ENV['PANTHEON_ENVIRONMENT'] != 'live') { die(); } // Retrieve Cloudflare config data $config_file = $_SERVER['HOME'] . '/files/private/cloudflare_cache.json'; $config = json_decode(file_get_contents($_SERVER['HOME'] . '/files/private/cloudflare_cache.json'), 1); if ($config == FALSE) { die('files/private/cloudflare_cache.json not found. Aborting!'); } purge_cache($config); function purge_cache($config) { $payload = json_encode(array('purge_everything' => true)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/zones/' . $config['zone_id'] . '/purge_cache'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-Auth-Email: ' . $config['email'], 'X-Auth-Key: ' . $config['api_key'], 'Content-Type: application/json' )); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); print("\n==== Sending Request to Cloudflare ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("\n===== Request Complete! =====\n"); curl_close($ch); }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/diffy_visualregression/diffyVisualregression.php
diffy_visualregression/diffyVisualregression.php
<?php // An example of using Pantheon's Quicksilver technology to do // automatic visual regression testing using diffy.website define("SITE_URL", "https://app.diffy.website"); echo 'Checking if it is test environment deployment.' . PHP_EOL; if (defined('PANTHEON_ENVIRONMENT') && (PANTHEON_ENVIRONMENT == 'test')) { echo 'Stage deployment. Starting visual testing.' . PHP_EOL; $diffy = new DiffyVisualregression(); $diffy->run(); } else { echo 'No it is not Test environment. Skipping visual testing.' . PHP_EOL; } class DiffyVisualregression { private $jwt; private $error; private $processMsg = ''; private $secrets; public function run() { // Load our hidden credentials. // See the README.md for instructions on storing secrets. $this->secrets = $this->get_secrets(['token', 'project_id']); echo 'Starting a visual regression test between the live and test environments...' . PHP_EOL; $isLoggedIn = $this->login($this->secrets['token']); if (!$isLoggedIn) { echo $this->error; return; } $compare = $this->compare(); if (!$compare) { echo $this->error; return; } echo $this->processMsg; return; } private function compare() { $curl = curl_init(); $authorization = 'Authorization: Bearer ' . $this->jwt; $curlOptions = array( CURLOPT_URL => rtrim(SITE_URL, '/') . '/api/projects/' . $this->secrets['project_id'] . '/compare', CURLOPT_HTTPHEADER => array('Content-Type: application/json' , $authorization ), CURLOPT_POST => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_POSTFIELDS => json_encode(array( 'env1' => 'prod', 'env2' => 'stage', 'withRescan' => false )) ); curl_setopt_array($curl, $curlOptions); $curlResponse = json_decode(curl_exec($curl)); $curlErrorMsg = curl_error($curl); $curlErrno= curl_errno($curl); curl_close($curl); if ($curlErrorMsg) { $this->error = $curlErrno . ': ' . $curlErrorMsg . '\n'; return false; } if (isset($curlResponse->errors)) { $errorMessages = is_object($curlResponse->errors) ? $this->parseProjectErrors($curlResponse->errors) : $curlResponse->errors; $this->error = '-1:' . $errorMessages; return false; } if (strstr($curlResponse, 'diff: ')) { $diffId = (int) str_replace('diff: ', '', $curlResponse); if ($diffId) { $this->processMsg .= 'Check out the result here: ' . rtrim(SITE_URL, '/') . '/#/diffs/' . $diffId . PHP_EOL; return true; } } else { $this->error = '-1:' . $curlResponse . PHP_EOL; return false; } } private function login($token) { $curl = curl_init(); $curlOptions = array( CURLOPT_URL => rtrim(SITE_URL, '/') . '/api/auth/key', CURLOPT_POST => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS => json_encode(array( 'key' => $token, )) ); curl_setopt_array($curl, $curlOptions); $curlResponse = json_decode(curl_exec($curl)); $curlErrorMsg = curl_error($curl); $curlErrno= curl_errno($curl); curl_close($curl); if ($curlErrorMsg) { $this->error = $curlErrno . ': ' . $curlErrorMsg . PHP_EOL; return false; } if (isset($curlResponse->token)) { $this->jwt = $curlResponse->token; return true; } else { $this->jwt = null; $this->error = '401: '.$curlResponse->message . PHP_EOL; return false; } } private function parseProjectErrors($errors) { $errorsString = ''; foreach ($errors as $key => $error) { $errorsString .= $key . ' => ' . $error . PHP_EOL; } return $errorsString; } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ private function get_secrets($requiredKeys) { $secretsFile = $_SERVER['HOME'].'/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: '.implode(',', $missing).'. Aborting!'); } return $secrets; } }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/jira_integration/jira_integration.php
jira_integration/jira_integration.php
<?php // Get the environment; we will post a new comment to Jira each time // a commit appears on a new branch on Pantheon. $env = $_ENV['PANTHEON_ENVIRONMENT']; // Do not watch test or live, though. if (($env == 'live') || ($env == 'test')) { exit(0); } // Look up the secrets from the secrets file. $secrets = _get_secrets(array('jira_url', 'jira_user', 'jira_pass'), array()); // Get latest commit $current_commithash = shell_exec('git rev-parse HEAD'); $last_commithash = false; // Retrieve the last commit processed by this script $commit_file = $_SERVER['HOME'] . "/files/private/{$env}_jira_integration_commit.txt"; if (file_exists($commit_file)) { $last_processed_commithash = trim(file_get_contents($commit_file)); // We should (almost) always find our last commit still in the repository; // if the user has force-pushed a branch, though, then our last commit // may be overwritten. If this happens, only process the most recent commit. exec("git rev-parse $last_processed_commithash 2> /dev/null", $output, $status); if (!$status) { $last_commithash = $last_processed_commithash; } } // Update the last commit file with the latest commit file_put_contents($commit_file, $current_commithash, LOCK_EX); // Retrieve git log for commits after last processed, to current $commits = _get_commits($current_commithash, $last_commithash, $env); // Check each commit message for Jira ticket numbers foreach ($commits['jira'] as $ticket_id => $commit_ids) { foreach ($commit_ids as $commit_id) { send_commit($secrets, $ticket_id, $commits['history'][$commit_id]); } } /** * Do git operations to find all commits between the specified commit hashes, * and return an associative array containing all applicable commits that * contain references to Jira issues. */ function _get_commits($current_commithash, $last_commithash, $env) { $commits = array( // Raw output of git log since the last processed 'history_raw' => null, // Formatted array of commits being sent to jira 'history' => array(), // An array keyed by jira ticket id, each holding an // array of commit ids. 'jira' => array() ); $cmd = 'git log'; // add -p to include diff if (!$last_commithash) { $cmd .= ' -n 1'; } else { $cmd .= ' ' . $last_commithash . '...' . $current_commithash; } $commits['history_raw'] = shell_exec($cmd); // Parse raw history into an array of commits $history = preg_split('/^commit /m', $commits['history_raw'], -1, PREG_SPLIT_NO_EMPTY); foreach ($history as $str) { $commit = array( 'full' => 'Commit: ' . $str ); // Only interested in the lines before the diff now $lines = explode("\n", $str); $commit['id'] = $lines[0]; $commit['message'] = trim(implode("\n", array_slice($lines, 4))); $commit['formatted'] = '{panel:title=Commit: ' . substr($commit['id'], 0, 10) . ' [' . $env . ']|borderStyle=dashed|borderColor=#ccc|titleBGColor=#e5f2ff|bgColor=#f2f2f2} ' . $commit['message'] . ' ~' . $lines[1] . ' - ' . $lines[2] . '~ {panel}'; // Look for matches on a Jira issue ID format // Expected pattern: "PROJECT-ID: comment". preg_match('/([A-Z]+-[0-9]+)/i', $commit['message'], $matches); if (count($matches) > 0) { // Build the $commits['jira'] array so there is // only 1 item per ticket id foreach ($matches as $ticket_id) { $ticket_id = strtoupper($ticket_id); if (!isset($commits['jira'][$ticket_id])) { $commits['jira'][$ticket_id] = array(); } // ... and only 1 item per commit id $commits['jira'][$ticket_id][$commit['id']] = $commit['id']; } // Add the commit to the history array since there was a match. $commits['history'][$commit['id']] = $commit; } } return $commits; } /** * Send commits to Jira */ function send_commit($secrets, $ticket_id, $commit) { $payload = json_encode(array('body' => $commit['formatted'])); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $secrets['jira_url'] . '/rest/api/2/issue/' . $ticket_id . '/comment'); curl_setopt($ch, CURLOPT_USERPWD, $secrets['jira_user'] . ':' . $secrets['jira_pass']); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); print("\n==== Posting to Jira ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("\n===== Post Complete! =====\n"); curl_close($ch); } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/chikka-sms-notification/chikka_sms_notification.php
chikka-sms-notification/chikka_sms_notification.php
<?php // Default values for parameters $defaults = array( 'chikka_url' => 'https://post.chikka.com/smsapi/request', 'mobile_number' => 'xxxxxxxxxxxx', ); // Load our hidden credentials. // See the README.md for instructions on storing secrets. $secrets = _get_secrets(array('chikka_client_id', 'chikka_client_secret', 'chikka_accesscode'), $defaults); $number = $secrets['mobile_number']; $workflow_description = ucfirst($_POST['stage']) . ' ' . str_replace('_', ' ', $_POST['wf_type']); // Customize the message based on the workflow type. Note that chikka_sms_notification.php // must appear in your pantheon.yml for each workflow type you wish to send notifications on. switch($_POST['wf_type']) { case 'deploy': // Find out what tag we are on and get the annotation. $deploy_tag = `git describe --tags`; $deploy_message = $_POST['deploy_message']; // Prepare the message $text = $_POST['user_fullname'] . ' deployed ' . $_ENV['PANTHEON_SITE_NAME'] . ' On branch "' . PANTHEON_ENVIRONMENT . '"Workflow: ' . $workflow_description . ' Deploy Message: ' . htmlentities($deploy_message); break; case 'sync_code': // Get the committer, hash, and message for the most recent commit. $committer = `git log -1 --pretty=%cn`; $email = `git log -1 --pretty=%ce`; $message = `git log -1 --pretty=%B`; $hash = `git log -1 --pretty=%h`; // Prepare the message $text = $_POST['user_fullname'] . ' committed to' . $_ENV['PANTHEON_SITE_NAME'] . ' On branch "' . PANTHEON_ENVIRONMENT . '"Workflow: ' . $workflow_description . ' - ' . htmlentities($message); break; default: $text = "Workflow $workflow_description" . $_POST['qs_description']; break; } $message = $text; if ( sendSMS($number, $message, $secrets['chikka_accesscode'], $secrets['chikka_client_id'], $secrets['chikka_client_secret'], $secrets['chikka_url'] ) == true) { echo "Successfully sent SMS to $number"; } else { echo "ERROR"; } /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; } // Send / Broadcast SMS function sendSMS($mobile_number, $message, $chikka_accesscode, $chikka_client_id, $chikka_client_secret, $chikka_url) { $post = array( "message_type" => "SEND", "mobile_number" => $mobile_number, "shortcode" => $chikka_accesscode, "message_id" => date('YmdHis'), "message" => urlencode($message), "client_id" => $chikka_client_id, "secret_key" => $chikka_client_secret); $result = curl_request($chikka_url, $post); $result = json_decode($result, true); if ($result['status'] == '200') { return true; } else { return false; } } // Reply SMS function replySMS($mobile_number, $request_id, $message, $price = 'P2.50', $chikka_accesscode, $chikka_client_id, $chikka_client_secret, $chikka_url) { $message_id = date('YmdHis'); $post = array( "message_type" => "REPLY", "mobile_number" => $mobile_number, "shortcode" => $chikka_accesscode, "message_id" => $message_id, "message" => urlencode($message), "request_id" => $request_id, "request_cost" => $price, "client_id" => $chikka_client_id, "secret_key" => $chikka_client_secret); $result = curl_request($chikka_url, $post); $result = json_decode($result, true); if ($result['status'] == '200') { return true; } else { return false; } } // Reply SMS function replySMS2($mobile_number, $request_id, $message, $price = 'P2.50', $chikka_accesscode, $chikka_client_id, $chikka_client_secret, $chikka_url) { $message_id = date('YmdHis'); $post = array( "message_type" => "REPLY", "mobile_number" => $mobile_number, "shortcode" => $secrets['chikka_accesscode'], "message_id" => $message_id, "message" => urlencode($message), "request_id" => $request_id, "request_cost" => $price, "client_id" => $secrets['chikka_client_id'], "secret_key" => $secrets['chikka_client_secret'] ); $result = curl_request($secrets['chikka_url'], $post); $result = json_decode($result, true); if ($result['status'] == '200') { return true; } else { return false; } } // Basic Curl Request function curl_request( $URL, $arr_post_body) { $query_string = ""; foreach($arr_post_body as $key => $frow) { $query_string .= '&'.$key.'='.$frow; } $curl_handler = curl_init(); curl_setopt($curl_handler, CURLOPT_URL, $URL); curl_setopt($curl_handler, CURLOPT_POST, count($arr_post_body)); curl_setopt($curl_handler, CURLOPT_POSTFIELDS, $query_string); curl_setopt($curl_handler, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl_handler); if(curl_errno($curl_handler)) { $info = curl_getinfo($curl_handler); } curl_close($curl_handler); return $response; } ?>
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/teams_notification/teams_notification.php
teams_notification/teams_notification.php
<?php // Default values for parameters if needed $defaults = array(); // Load our hidden credentials. // See the README.md for instructions on storing secrets. $secrets = _get_secrets(array('teams_url'), $defaults); $params = [ 'USERMAIL' => $_POST['user_email'], 'USERMAIL_HASH' => md5(strtolower(trim($_POST['user_email']))), 'USERNAME' => $_POST['user_fullname'], 'ENV' => $_ENV['PANTHEON_ENVIRONMENT'], 'PROJECT_NAME' => $_ENV['PANTHEON_SITE_NAME'] ]; switch($_POST['wf_type']) { case 'deploy': // Find out what tag we are on and last commit date $deploy_tag= `git describe --tags`; // [TODO] needs to be more accurate with exact date of the creation of tag and not last commit date $deploy_date = `git log -1 --format=%ai `; // Set additional parameters for deploy case $params += [ 'DEPLOY_NOTE' => $_POST['deploy_message'], 'DEPLOY_TAG' => $deploy_tag, 'DEPLOY_LOG_URL' => 'https://dashboard.pantheon.io/sites/' . $_ENV['PANTHEON_SITE'] . '#'. strtolower($_ENV['PANTHEON_ENVIRONMENT']) .'/deploys', 'ENV_URL' => 'https://' . $_ENV['PANTHEON_ENVIRONMENT'] . '-' . $_ENV['PANTHEON_SITE_NAME'] . '.pantheonsite.io' ]; // Get the "deploy" message template $message = file_get_contents("samples/deploy_msg.json"); break; case 'sync_code': $committer = `git log -1 --pretty=%cn`; $email = `git log -1 --pretty=%ce`; $message = `git log -1 --pretty=%B`; $hash = `git log -1 --pretty=%h`; $text = 'Most recent commit: '. rtrim($hash) . ' by ' . rtrim($committer) . ' (' . $email . '): ' . $message; $params += [ 'MESSAGE' => $text ]; // Get the "sync code" message template $message = file_get_contents("samples/sync_code_msg.json"); break; // [TODO] not working for now case 'clear_cache': // Get the "clear cache" message template $message = file_get_contents("samples/clear_cache_msg.json"); break; default: //$text = "Workflow $workflow_description<br />" . $_POST['qs_description']; break; } $message = preg_replace_callback('/{{((?:[^}]|}[^}])+)}}/', function($match) use ($params) { return ($params[$match[1]]); }, $message); _teams_notification($secrets['teams_url'],$message); /** * Get secrets from secrets file. * * @param array $requiredKeys List of keys in secrets file that must exist. */ function _get_secrets($requiredKeys, $defaults) { $secretsFile = $_SERVER['HOME'] . '/files/private/secrets.json'; if (!file_exists($secretsFile)) { die('No secrets file found. Aborting!'); } $secretsContents = file_get_contents($secretsFile); $secrets = json_decode($secretsContents, 1); if ($secrets == false) { die('Could not parse json in secrets file. Aborting!'); } $secrets += $defaults; $missing = array_diff($requiredKeys, array_keys($secrets)); if (!empty($missing)) { die('Missing required keys in json secrets file: ' . implode(',', $missing) . '. Aborting!'); } return $secrets; } /** * Send notifications to Microsoft Teams */ function _teams_notification($teams_url,$message){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $teams_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, $message); // Watch for messages with `terminus workflows watch --site=SITENAME` print("\n==== Posting to Teams ====\n"); $result = curl_exec($ch); print("RESULT: $result"); print("MESSAGE SENT: $message"); print("\n===== Post Complete! =====\n"); curl_close($ch); }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
pantheon-systems/quicksilver-examples
https://github.com/pantheon-systems/quicksilver-examples/blob/a2e3d7c00ff0bfab06873747e79c8eccae3b81da/enable_dev_modules/enable_dev_modules.php
enable_dev_modules/enable_dev_modules.php
<?php /** * This example enables the devel module when a database is cloned to a dev environment. * * This script should be configured into the clone_database operation in pantheon.yml */ // The clone_database may be triggered on any environment, but we only want // to automatically enable the devel module when this event happens a dev // or multidev environment. if (isset($_POST['environment']) && !in_array($_POST['environment'], array('test', 'live'))) { // First, let's retrieve a list of disabled modules with drush pm-list. // shell_exec() will return the output of an executable as a string. // Pass the --format=json flag into the drush command so the output can be converted into an array with json_decode(). $modules = json_decode(shell_exec('drush pm-list --format=json')); // Now let's enable devel if it is installed and not already enabled. if (isset($modules->devel) && $modules->devel->status !== 'Enabled') { // This time let's just passthru() to run the drush command so the command output prints to the workflow log. passthru('drush pm-enable -y devel'); } }
php
MIT
a2e3d7c00ff0bfab06873747e79c8eccae3b81da
2026-01-05T04:53:04.234036Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/.php-cs-fixer.dist.php
.php-cs-fixer.dist.php
<?php $finder = PhpCsFixer\Finder::create() ->files() ->in(__DIR__ . '/src') ->in(__DIR__ . '/test') ->in(__DIR__ . '/example') ->name('*.php'); $finder->files()->append([__DIR__ . 'composer/bin/mddoc']); return (new PhpCsFixer\Config) ->setUsingCache(true) ->setIndent("\t") ->setLineEnding("\n") //->setUsingLinter(false) ->setRiskyAllowed(true) ->setRules( [ '@PHPUnit60Migration:risky' => true, 'php_unit_test_case_static_method_calls' => [ 'call_type' => 'this', ], 'concat_space' => [ 'spacing' => 'one', ], 'visibility_required' => true, 'indentation_type' => true, 'no_useless_return' => true, 'switch_case_space' => true, 'switch_case_semicolon_to_colon' => true, 'array_syntax' => [ 'syntax' => 'short' ], 'list_syntax' => [ 'syntax' => 'short' ], 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_whitespace_in_blank_line' => true, 'phpdoc_add_missing_param_annotation' => [ 'only_untyped' => true, ], 'phpdoc_indent' => true, 'phpdoc_no_alias_tag' => true, 'phpdoc_no_package' => true, 'phpdoc_no_useless_inheritdoc' => true, 'phpdoc_order' => true, 'phpdoc_scalar' => true, 'phpdoc_single_line_var_spacing' => true, 'phpdoc_var_annotation_correct_order' => true, 'phpdoc_trim' => true, 'phpdoc_trim_consecutive_blank_line_separation' => true, 'phpdoc_types' => true, 'phpdoc_types_order' => [ 'null_adjustment' => 'always_last', 'sort_algorithm' => 'alpha', ], 'phpdoc_align' => [ 'align' => 'vertical', 'tags' => [ 'param' ], ], 'phpdoc_line_span' => [ 'const' => 'single', 'method' => 'multi', 'property' => 'single', ], 'short_scalar_cast' => true, 'standardize_not_equals' => true, 'ternary_operator_spaces' => true, 'no_spaces_after_function_name' => true, 'no_unneeded_control_parentheses' => true, 'return_type_declaration' => [ 'space_before' => 'one', ], 'single_line_after_imports' => true, 'single_blank_line_before_namespace' => true, 'blank_line_after_namespace' => true, 'single_blank_line_at_eof' => true, 'ternary_to_null_coalescing' => true, 'whitespace_after_comma_in_array' => true, 'cast_spaces' => [ 'space' => 'none' ], 'encoding' => true, 'space_after_semicolon' => [ 'remove_in_empty_for_expressions' => true, ], 'align_multiline_comment' => [ 'comment_type' => 'phpdocs_like', ], 'blank_line_before_statement' => [ 'statements' => [ 'continue', 'try', 'switch', 'exit', 'throw', 'return', 'do' ], ], 'no_superfluous_phpdoc_tags' => [ 'remove_inheritdoc' => true, ], 'no_superfluous_elseif' => true, 'no_useless_else' => true, 'combine_consecutive_issets' => true, 'escape_implicit_backslashes' => true, 'explicit_indirect_variable' => true, 'heredoc_to_nowdoc' => true, 'no_singleline_whitespace_before_semicolons' => true, 'no_null_property_initialization' => true, 'no_whitespace_before_comma_in_array' => true, 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_empty_comment' => true, 'no_extra_blank_lines' => true, 'no_blank_lines_after_phpdoc' => true, 'no_spaces_around_offset' => [ 'positions' => [ 'outside' ], ], 'return_assignment' => true, 'lowercase_static_reference' => true, 'method_chaining_indentation' => true, 'method_argument_space' => [ 'on_multiline' => 'ignore', // at least until they fix it 'keep_multiple_spaces_after_comma' => true, ], 'multiline_comment_opening_closing' => true, 'include' => true, 'elseif' => true, 'simple_to_complex_string_variable' => true, 'global_namespace_import' => [ 'import_classes' => false, 'import_constants' => false, 'import_functions' => false, ], 'trailing_comma_in_multiline' => true, 'single_line_comment_style' => true, 'is_null' => true, 'yoda_style' => [ 'equal' => false, 'identical' => false, 'less_and_greater' => null, ], ] ) ->setFinder($finder);
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/ResponseStack.php
src/ResponseStack.php
<?php namespace donatj\MockWebServer; /** * ResponseStack is used to store multiple responses for a request issued by the server in order. * * When the stack is empty, the server will return a customizable response defaulting to a 404. */ class ResponseStack implements InitializingResponseInterface, MultiResponseInterface { /** @var string */ private $ref; /** @var \donatj\MockWebServer\ResponseInterface[] */ private $responses = []; /** @var \donatj\MockWebServer\ResponseInterface|null */ protected $currentResponse; /** @var \donatj\MockWebServer\ResponseInterface */ protected $pastEndResponse; /** * ResponseStack constructor. * * Accepts a variable number of ResponseInterface objects */ public function __construct(ResponseInterface ...$responses) { $refBase = ''; foreach( $responses as $response ) { $this->responses[] = $response; $refBase .= $response->getRef(); } $this->ref = md5($refBase); $this->currentResponse = reset($this->responses) ?: null; $this->pastEndResponse = new Response('Past the end of the ResponseStack', [], 404); } public function initialize( RequestInfo $request ) : void { if( $this->currentResponse instanceof InitializingResponseInterface ) { $this->currentResponse->initialize($request); } } public function next() : bool { array_shift($this->responses); $this->currentResponse = reset($this->responses) ?: null; return (bool)$this->currentResponse; } public function getRef() : string { return $this->ref; } public function getBody( RequestInfo $request ) : string { return $this->currentResponse ? $this->currentResponse->getBody($request) : $this->pastEndResponse->getBody($request); } public function getHeaders( RequestInfo $request ) : array { return $this->currentResponse ? $this->currentResponse->getHeaders($request) : $this->pastEndResponse->getHeaders($request); } public function getStatus( RequestInfo $request ) : int { return $this->currentResponse ? $this->currentResponse->getStatus($request) : $this->pastEndResponse->getStatus($request); } /** * Gets the response returned when the stack is exhausted. */ public function getPastEndResponse() : ResponseInterface { return $this->pastEndResponse; } /** * Set the response to return when the stack is exhausted. */ public function setPastEndResponse( ResponseInterface $pastEndResponse ) : void { $this->pastEndResponse = $pastEndResponse; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/InternalServer.php
src/InternalServer.php
<?php namespace donatj\MockWebServer; use donatj\MockWebServer\Exceptions\ServerException; use donatj\MockWebServer\Responses\DefaultResponse; use donatj\MockWebServer\Responses\NotFoundResponse; /** * Class InternalServer * * @internal */ class InternalServer { /** @var string */ private $tmpPath; /** @var \donatj\MockWebServer\RequestInfo */ private $request; /** @var callable */ private $header; /** @var callable */ private $httpResponseCode; private const DEFAULT_REF = 'default'; public function __construct( string $tmpPath, RequestInfo $request, ?callable $header = null, ?callable $httpResponseCode = null ) { if( $header === null ) { $header = "\\header"; } if( $httpResponseCode === null ) { $httpResponseCode = "\\http_response_code"; } $this->tmpPath = $tmpPath; $count = self::incrementRequestCounter($this->tmpPath); $this->logRequest($request, $count); $this->request = $request; $this->header = $header; $this->httpResponseCode = $httpResponseCode; } /** * @internal */ public static function incrementRequestCounter( string $tmpPath, ?int $int = null ) : int { $countFile = $tmpPath . DIRECTORY_SEPARATOR . MockWebServer::REQUEST_COUNT_FILE; if( $int === null ) { $newInt = file_get_contents($countFile); if( !is_string($newInt) ) { throw new ServerException('failed to fetch request count'); } $int = (int)$newInt + 1; } file_put_contents($countFile, (string)$int); return (int)$int; } private function logRequest( RequestInfo $request, int $count ) : void { $reqStr = serialize($request); file_put_contents($this->tmpPath . DIRECTORY_SEPARATOR . MockWebServer::LAST_REQUEST_FILE, $reqStr); file_put_contents($this->tmpPath . DIRECTORY_SEPARATOR . 'request.' . $count, $reqStr); } /** * @internal */ public static function aliasPath( string $tmpPath, string $path ) : string { $path = '/' . ltrim($path, '/'); return sprintf('%s%salias.%s', $tmpPath, DIRECTORY_SEPARATOR, md5($path) ); } private function responseForRef( string $ref ) : ?ResponseInterface { $path = $this->tmpPath . DIRECTORY_SEPARATOR . $ref; if( !is_readable($path) ) { return null; } $content = file_get_contents($path); if( $content === false ) { throw new ServerException('failed to read response content'); } $response = unserialize($content); if( !$response instanceof ResponseInterface ) { throw new ServerException('invalid serialized response'); } return $response; } public function __invoke() : void { $ref = $this->getRefForUri($this->request->getParsedUri()['path']); if( $ref !== null ) { $response = $this->responseForRef($ref); if( $response ) { $this->sendResponse($response); return; } $this->sendResponse(new NotFoundResponse); return; } $response = $this->responseForRef(self::DEFAULT_REF); if( $response ) { $this->sendResponse($response); return; } $this->sendResponse(new DefaultResponse); } protected function sendResponse( ResponseInterface $response ) : void { if( $response instanceof InitializingResponseInterface ) { $response->initialize($this->request); } ($this->httpResponseCode)($response->getStatus($this->request)); foreach( $response->getHeaders($this->request) as $key => $header ) { if( is_int($key) ) { ($this->header)($header); } else { ($this->header)("{$key}: {$header}"); } } echo $response->getBody($this->request); if( $response instanceof MultiResponseInterface ) { $response->next(); self::storeResponse($this->tmpPath, $response); } } protected function getRefForUri( string $uriPath ) : ?string { $aliasPath = self::aliasPath($this->tmpPath, $uriPath); if( file_exists($aliasPath) ) { if( $path = file_get_contents($aliasPath) ) { return $path; } } elseif( preg_match('%^/' . preg_quote(MockWebServer::VND, '%') . '/([0-9a-fA-F]{32})$%', $uriPath, $matches) ) { return $matches[1]; } return null; } public static function getPathOfRef( string $ref ) : string { return '/' . MockWebServer::VND . '/' . $ref; } /** * @internal */ public static function storeResponse( string $tmpPath, ResponseInterface $response ) : string { $ref = $response->getRef(); self::storeRef($response, $tmpPath, $ref); return $ref; } /** * @internal */ public static function storeDefaultResponse( string $tmpPath, ResponseInterface $response ) : void { self::storeRef($response, $tmpPath, self::DEFAULT_REF); } private static function storeRef( ResponseInterface $response, string $tmpPath, string $ref ) : void { $content = serialize($response); if( !file_put_contents($tmpPath . DIRECTORY_SEPARATOR . $ref, $content) ) { throw new Exceptions\RuntimeException('Failed to write temporary content'); } } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/MultiResponseInterface.php
src/MultiResponseInterface.php
<?php namespace donatj\MockWebServer; /** * MultiResponseInterface is used to vary the response to a request. */ interface MultiResponseInterface extends ResponseInterface { /** * Called after each request is sent * * @internal */ public function next() : bool; }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/Response.php
src/Response.php
<?php namespace donatj\MockWebServer; use donatj\MockWebServer\Exceptions\RuntimeException; class Response implements ResponseInterface { /** @var string */ protected $body; /** @var array */ protected $headers; /** @var int */ protected $status; /** * Response constructor. */ public function __construct( string $body, array $headers = [], int $status = 200 ) { $this->body = $body; $this->headers = $headers; $this->status = $status; } public function getRef() : string { $content = json_encode([ md5($this->body), $this->status, $this->headers, ]); if( $content === false ) { throw new RuntimeException('Failed to encode response content to JSON: ' . json_last_error_msg()); } return md5($content); } public function getBody( RequestInfo $request ) : string { return $this->body; } public function getHeaders( RequestInfo $request ) : array { return $this->headers; } public function getStatus( RequestInfo $request ) : int { return $this->status; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/MockWebServer.php
src/MockWebServer.php
<?php namespace donatj\MockWebServer; use donatj\MockWebServer\Exceptions\RuntimeException; class MockWebServer { public const VND = 'VND.DonatStudios.MockWebServer'; public const LAST_REQUEST_FILE = 'last.request'; public const REQUEST_COUNT_FILE = 'count.request'; public const TMP_ENV = 'MOCK_WEB_SERVER_TMP'; /** @var string */ private $host; /** @var int */ private $port; /** @var string */ private $tmpDir; /** * Contain link to opened process resource * * @var resource */ private $process; /** * Contains the descriptors for the process after it has been started * * @var resource[] */ private $descriptors = []; /** * TestWebServer constructor. * * @param int $port Network port to run on * @param string $host Listening hostname */ public function __construct( int $port = 0, string $host = '127.0.0.1' ) { $this->host = $host; $this->port = $port; if( $this->port === 0 ) { $this->port = $this->findOpenPort(); } $this->tmpDir = $this->getTmpDir(); } /** * Start the Web Server on the selected port and host */ public function start() : void { if( $this->isRunning() ) { return; } $script = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'server' . DIRECTORY_SEPARATOR . 'server.php'; $stdout = tempnam(sys_get_temp_dir(), 'mockserv-stdout-'); $cmd = sprintf("php -S %s:%d %s", $this->host, $this->port, escapeshellarg($script)); if( !putenv(self::TMP_ENV . '=' . $this->tmpDir) ) { throw new Exceptions\RuntimeException('Unable to put environmental variable'); } $fullCmd = sprintf('%s > %s 2>&1', $cmd, $stdout ); InternalServer::incrementRequestCounter($this->tmpDir, 0); [ $this->process, $this->descriptors ] = $this->startServer($fullCmd); for( $i = 0; $i <= 20; $i++ ) { usleep(100000); $open = @fsockopen($this->host, $this->port); if( is_resource($open) ) { fclose($open); break; } } if( !$this->isRunning() ) { throw new Exceptions\ServerException("Failed to start server. Is something already running on port {$this->port}?"); } register_shutdown_function(function () { if( $this->isRunning() ) { $this->stop(); } }); } /** * Is the Web Server currently running? */ public function isRunning() : bool { if( !is_resource($this->process) ) { return false; } $processStatus = proc_get_status($this->process); if( !$processStatus ) { return false; } return $processStatus['running']; } /** * Stop the Web Server */ public function stop() : void { if( $this->isRunning() ) { proc_terminate($this->process); $attempts = 0; while( $this->isRunning() ) { if( ++$attempts > 1000 ) { throw new Exceptions\ServerException('Failed to stop server.'); } usleep(10000); } } foreach( $this->descriptors as $descriptor ) { @fclose($descriptor); } $this->descriptors = []; } /** * Get the HTTP root of the webserver * e.g.: http://127.0.0.1:8123 */ public function getServerRoot() : string { return "http://{$this->host}:{$this->port}"; } /** * Get a URL providing the specified response. * * @return string URL where response can be found */ public function getUrlOfResponse( ResponseInterface $response ) : string { $ref = InternalServer::storeResponse($this->tmpDir, $response); return $this->getServerRoot() . InternalServer::getPathOfRef($ref); } /** * Set a specified path to provide a specific response */ public function setResponseOfPath( string $path, ResponseInterface $response ) : string { $ref = InternalServer::storeResponse($this->tmpDir, $response); $aliasPath = InternalServer::aliasPath($this->tmpDir, $path); if( !file_put_contents($aliasPath, $ref) ) { throw new \RuntimeException('Failed to store path alias'); } return $this->getServerRoot() . $path; } /** * Override the default server response, e.g. Fallback or 404 */ public function setDefaultResponse( ResponseInterface $response ) : void { InternalServer::storeDefaultResponse($this->tmpDir, $response); } /** * @internal */ private function getTmpDir() : string { $tmpDir = sys_get_temp_dir() ?: '/tmp'; if( !is_dir($tmpDir) || !is_writable($tmpDir) ) { throw new \RuntimeException('Unable to find system tmp directory'); } $tmpPath = $tmpDir . DIRECTORY_SEPARATOR . 'MockWebServer'; if( !is_dir($tmpPath) ) { if( !mkdir($tmpPath) && !is_dir($tmpPath) ) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $tmpPath)); } } $tmpPath .= DIRECTORY_SEPARATOR . $this->port; if( !is_dir($tmpPath) ) { if( !mkdir($tmpPath) && !is_dir($tmpPath) ) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $tmpPath)); } } $tmpPath .= DIRECTORY_SEPARATOR . md5(microtime(true) . ':' . rand(0, 100000)); if( !is_dir($tmpPath) ) { if( !mkdir($tmpPath) && !is_dir($tmpPath) ) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $tmpPath)); } } return $tmpPath; } /** * Get the previous requests associated request data. */ public function getLastRequest() : ?RequestInfo { $path = $this->tmpDir . DIRECTORY_SEPARATOR . self::LAST_REQUEST_FILE; if( file_exists($path) ) { $content = file_get_contents($path); if( $content === false ) { throw new RuntimeException('failed to read last request'); } $data = @unserialize($content); if( $data instanceof RequestInfo ) { return $data; } } return null; } /** * Get request by offset * * If offset is non-negative, the request will be the index from the start of the server. * If offset is negative, the request will be that from the end of the requests. */ public function getRequestByOffset( int $offset ) : ?RequestInfo { $reqs = glob($this->tmpDir . DIRECTORY_SEPARATOR . 'request.*') ?: []; natsort($reqs); $item = array_slice($reqs, $offset, 1); if( !$item ) { return null; } $path = reset($item); if( !$path ) { return null; } $content = file_get_contents($path); if( $content === false ) { throw new RuntimeException("failed to read request from '{$path}'"); } $data = @unserialize($content); if( $data instanceof RequestInfo ) { return $data; } return null; } /** * Get the host of the server. */ public function getHost() : string { return $this->host; } /** * Get the port the network server is to be ran on. */ public function getPort() : int { return $this->port; } /** * Let the OS find an open port for you. */ private function findOpenPort() : int { $sock = socket_create(AF_INET, SOCK_STREAM, 0); if( $sock === false ) { throw new RuntimeException('Failed to create socket'); } // Bind the socket to an address/port if( !socket_bind($sock, $this->getHost(), 0) ) { throw new RuntimeException('Could not bind to address'); } socket_getsockname($sock, $checkAddress, $checkPort); socket_close($sock); if( $checkPort > 0 ) { return $checkPort; } throw new RuntimeException('Failed to find open port'); } private function isWindowsPlatform() : bool { return defined('PHP_WINDOWS_VERSION_MAJOR'); } /** * @return array{resource,array{resource,resource,resource}} */ private function startServer( string $fullCmd ) : array { if( !$this->isWindowsPlatform() ) { // We need to prefix exec to get the correct process http://php.net/manual/ru/function.proc-get-status.php#93382 $fullCmd = 'exec ' . $fullCmd; } $pipes = []; $env = null; $cwd = null; $stdoutf = tempnam(sys_get_temp_dir(), 'MockWebServer.stdout'); if( $stdoutf === false ) { throw new RuntimeException('error creating stdout temp file'); } $stderrf = tempnam(sys_get_temp_dir(), 'MockWebServer.stderr'); if( $stderrf === false ) { throw new RuntimeException('error creating stderr temp file'); } $stdin = fopen('php://stdin', 'rb'); if( $stdin === false ) { throw new RuntimeException('error opening stdin'); } $stdout = fopen($stdoutf, 'ab'); if( $stdout === false ) { throw new RuntimeException('error opening stdout'); } $stderr = fopen($stderrf, 'ab'); if( $stderr === false ) { throw new RuntimeException('error opening stderr'); } $descriptorSpec = [ $stdin, $stdout, $stderr ]; $process = proc_open($fullCmd, $descriptorSpec, $pipes, $cwd, $env, [ 'suppress_errors' => false, 'bypass_shell' => true, ]); if( $process === false ) { throw new Exceptions\ServerException('Error starting server'); } return [ $process, $descriptorSpec ]; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/ResponseInterface.php
src/ResponseInterface.php
<?php namespace donatj\MockWebServer; interface ResponseInterface { /** * Get a unique identifier for the response. * * Expected to be 32 characters of hexadecimal * * @internal */ public function getRef() : string; /** * Get the body of the response * * @internal */ public function getBody( RequestInfo $request ) : string; /** * Get the headers as either an array of key => value or ["Full: Header","OtherFull: Header"] * * @internal */ public function getHeaders( RequestInfo $request ) : array; /** * Get the HTTP Status Code * * @internal */ public function getStatus( RequestInfo $request ) : int; }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/ResponseByMethod.php
src/ResponseByMethod.php
<?php namespace donatj\MockWebServer; /** * ResponseByMethod is used to vary the response to a request by the called HTTP Method. */ class ResponseByMethod implements MultiResponseInterface { public const METHOD_GET = 'GET'; public const METHOD_POST = 'POST'; public const METHOD_PUT = 'PUT'; public const METHOD_PATCH = 'PATCH'; public const METHOD_DELETE = 'DELETE'; public const METHOD_HEAD = 'HEAD'; public const METHOD_OPTIONS = 'OPTIONS'; public const METHOD_TRACE = 'TRACE'; /** @var ResponseInterface[] */ private $responses = []; /** @var ResponseInterface */ private $defaultResponse; /** @var string|null */ private $latestMethod; /** * MethodResponse constructor. * * @param array<string, ResponseInterface> $responses A map of responses keyed by their method. * @param ResponseInterface|null $defaultResponse The fallthrough response to return if a response for a * given method is not found. If this is not defined the * server will return an HTTP 501 error. */ public function __construct( array $responses = [], ?ResponseInterface $defaultResponse = null ) { foreach( $responses as $method => $response ) { $this->setMethodResponse($method, $response); } if( $defaultResponse ) { $this->defaultResponse = $defaultResponse; } else { $this->defaultResponse = new Response('MethodResponse - Method Not Defined', [], 501); } } public function getRef() : string { $refBase = $this->defaultResponse->getRef(); foreach( $this->responses as $response ) { $refBase .= $response->getRef(); } return md5($refBase); } public function getBody( RequestInfo $request ) : string { return $this->getMethodResponse($request)->getBody($request); } public function getHeaders( RequestInfo $request ) : array { return $this->getMethodResponse($request)->getHeaders($request); } public function getStatus( RequestInfo $request ) : int { return $this->getMethodResponse($request)->getStatus($request); } private function getMethodResponse( RequestInfo $request ) : ResponseInterface { $method = $request->getRequestMethod(); $this->latestMethod = $method; return $this->responses[$method] ?? $this->defaultResponse; } /** * Set the Response for the Given Method */ public function setMethodResponse( string $method, ResponseInterface $response ) : void { $this->responses[$method] = $response; } public function next() : bool { $method = $this->latestMethod; if( !$method ) { return false; } if( !isset($this->responses[$method]) ) { return false; } if( !$this->responses[$method] instanceof MultiResponseInterface ) { return false; } return $this->responses[$method]->next(); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/InitializingResponseInterface.php
src/InitializingResponseInterface.php
<?php namespace donatj\MockWebServer; /** * InitializingResponseInterface is used to initialize a response before headers are sent. */ interface InitializingResponseInterface extends ResponseInterface { /** * @internal */ public function initialize( RequestInfo $request ) : void; }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/RequestInfo.php
src/RequestInfo.php
<?php namespace donatj\MockWebServer; use donatj\MockWebServer\Exceptions\RuntimeException; class RequestInfo implements \JsonSerializable { public const JSON_KEY_GET = '_GET'; public const JSON_KEY_POST = '_POST'; public const JSON_KEY_FILES = '_FILES'; public const JSON_KEY_COOKIE = '_COOKIE'; public const JSON_KEY_HEADERS = 'HEADERS'; public const JSON_KEY_METHOD = 'METHOD'; public const JSON_KEY_INPUT = 'INPUT'; public const JSON_KEY_PARSED_INPUT = 'PARSED_INPUT'; public const JSON_KEY_REQUEST_URI = 'REQUEST_URI'; public const JSON_KEY_PARSED_REQUEST_URI = 'PARSED_REQUEST_URI'; /** @var array */ private $parsedUri; /** @var array */ private $server; /** @var array */ private $get; /** @var array */ private $post; /** @var array */ private $files; /** @var array */ private $cookie; /** @var array */ private $HEADERS; /** @var string */ private $INPUT; /** @var array|null */ private $PARSED_INPUT; public function __construct( array $server, array $get, array $post, array $files, array $cookie, array $HEADERS, string $INPUT ) { $this->server = $server; $this->get = $get; $this->post = $post; $this->files = $files; $this->cookie = $cookie; $this->HEADERS = $HEADERS; $this->INPUT = $INPUT; parse_str($INPUT, $PARSED_INPUT); $this->PARSED_INPUT = $PARSED_INPUT; if( !isset($server['REQUEST_URI']) ) { throw new RuntimeException('REQUEST_URI not set'); } if( !isset($server['REQUEST_METHOD']) ) { throw new RuntimeException('REQUEST_METHOD not set'); } $parsedUrl = parse_url($server['REQUEST_URI']); if( $parsedUrl === false ) { throw new RuntimeException('Failed to parse REQUEST_URI: ' . $server['REQUEST_URI']); } $this->parsedUri = $parsedUrl; } /** * Specify data which should be serialized to JSON */ public function jsonSerialize() : array { return [ self::JSON_KEY_GET => $this->get, self::JSON_KEY_POST => $this->post, self::JSON_KEY_FILES => $this->files, self::JSON_KEY_COOKIE => $this->cookie, self::JSON_KEY_HEADERS => $this->HEADERS, self::JSON_KEY_METHOD => $this->getRequestMethod(), self::JSON_KEY_INPUT => $this->INPUT, self::JSON_KEY_PARSED_INPUT => $this->PARSED_INPUT, self::JSON_KEY_REQUEST_URI => $this->getRequestUri(), self::JSON_KEY_PARSED_REQUEST_URI => $this->parsedUri, ]; } /** * @return array */ public function getParsedUri() { return $this->parsedUri; } public function getRequestUri() : string { return $this->server['REQUEST_URI']; } public function getRequestMethod() : string { return $this->server['REQUEST_METHOD']; } public function getServer() : array { return $this->server; } public function getGet() : array { return $this->get; } public function getPost() : array { return $this->post; } public function getFiles() : array { return $this->files; } public function getCookie() : array { return $this->cookie; } public function getHeaders() : array { return $this->HEADERS; } public function getInput() : string { return $this->INPUT; } public function getParsedInput() : ?array { return $this->PARSED_INPUT; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/DelayedResponse.php
src/DelayedResponse.php
<?php namespace donatj\MockWebServer; /** * DelayedResponse wraps a response, causing it when called to be delayed by a specified number of microseconds. * * This is useful for simulating slow responses and testing timeouts. */ class DelayedResponse implements InitializingResponseInterface, MultiResponseInterface { /** @var int Microseconds to delay the response by. */ protected $delay; /** @var \donatj\MockWebServer\ResponseInterface */ protected $response; /** @var callable */ protected $usleep; /** * @param int $delay Microseconds to delay the response */ public function __construct( ResponseInterface $response, int $delay, ?callable $usleep = null ) { $this->response = $response; $this->delay = $delay; $this->usleep = '\\usleep'; if( $usleep ) { $this->usleep = $usleep; } } public function getRef() : string { return md5('delayed.' . $this->response->getRef()); } public function initialize( RequestInfo $request ) : void { ($this->usleep)($this->delay); } public function getBody( RequestInfo $request ) : string { return $this->response->getBody($request); } public function getHeaders( RequestInfo $request ) : array { return $this->response->getHeaders($request); } public function getStatus( RequestInfo $request ) : int { return $this->response->getStatus($request); } public function next() : bool { if( $this->response instanceof MultiResponseInterface ) { return $this->response->next(); } return false; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/Exceptions/ServerException.php
src/Exceptions/ServerException.php
<?php namespace donatj\MockWebServer\Exceptions; class ServerException extends RuntimeException { }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/Exceptions/RuntimeException.php
src/Exceptions/RuntimeException.php
<?php namespace donatj\MockWebServer\Exceptions; class RuntimeException extends \RuntimeException { }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/Responses/DefaultResponse.php
src/Responses/DefaultResponse.php
<?php namespace donatj\MockWebServer\Responses; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\ResponseInterface; /** * The Built-In Default Response. * Results in an HTTP 200 with a JSON encoded version of the incoming Request */ class DefaultResponse implements ResponseInterface { public function getRef() : string { return md5(MockWebServer::VND . '.default-ref'); } public function getBody( RequestInfo $request ) : string { return json_encode($request, JSON_PRETTY_PRINT) . "\n"; } public function getHeaders( RequestInfo $request ) : array { return [ 'Content-Type' => 'application/json' ]; } public function getStatus( RequestInfo $request ) : int { return 200; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/src/Responses/NotFoundResponse.php
src/Responses/NotFoundResponse.php
<?php namespace donatj\MockWebServer\Responses; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\ResponseInterface; /** * Basic Built-In 404 Response */ class NotFoundResponse implements ResponseInterface { public function getRef() : string { return md5(MockWebServer::VND . '.not-found'); } public function getBody( RequestInfo $request ) : string { $path = $request->getParsedUri()['path']; return MockWebServer::VND . ": Resource '{$path}' not found!\n"; } public function getHeaders( RequestInfo $request ) : array { return []; } public function getStatus( RequestInfo $request ) : int { return 404; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/ResponseStackTest.php
test/ResponseStackTest.php
<?php namespace Test; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\Response; use donatj\MockWebServer\ResponseStack; use PHPUnit\Framework\TestCase; class ResponseStackTest extends TestCase { public function testEmpty() : void { $mock = $this->getMockBuilder(RequestInfo::class)->disableOriginalConstructor()->getMock(); $x = new ResponseStack; $this->assertSame('Past the end of the ResponseStack', $x->getBody($mock)); $this->assertSame(404, $x->getStatus($mock)); $this->assertSame([], $x->getHeaders($mock)); $this->assertFalse($x->next()); } /** * @dataProvider customResponseProvider */ public function testCustomPastEndResponse( $body, $headers, $status ) : void { $mock = $this->getMockBuilder(RequestInfo::class)->disableOriginalConstructor()->getMock(); $x = new ResponseStack; $x->setPastEndResponse(new Response($body, $headers, $status)); $this->assertSame($body, $x->getBody($mock)); $this->assertSame($status, $x->getStatus($mock)); $this->assertSame($headers, $x->getHeaders($mock)); $this->assertFalse($x->next()); } public function customResponseProvider() : array { return [ [ 'PastEnd', [ 'HeaderA' => 'BVAL' ], 420 ], [ ' Leading and trailing whitespace ', [], 0 ], ]; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/DelayedResponseTest.php
test/DelayedResponseTest.php
<?php namespace Test; use donatj\MockWebServer\DelayedResponse; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\Response; use donatj\MockWebServer\Responses\DefaultResponse; use donatj\MockWebServer\ResponseStack; use PHPUnit\Framework\TestCase; class DelayedResponseTest extends TestCase { public function testInitialize() : void { $foundDelay = null; $resp = new DelayedResponse(new DefaultResponse, 1234, function ( int $delay ) use ( &$foundDelay ) { $foundDelay = $delay; }); $requestInfo = $this->getMockBuilder(RequestInfo::class) ->disableOriginalConstructor() ->getMock(); $resp->initialize($requestInfo); $this->assertSame(1234, $foundDelay); } public function testNext() : void { $resp = new DelayedResponse(new DefaultResponse, 1234); $this->assertFalse($resp->next()); $resp = new DelayedResponse(new DelayedResponse(new DefaultResponse, 1234), 1234); $this->assertFalse($resp->next()); $resp = new DelayedResponse(new ResponseStack( new Response('foo'), new Response('bar'), new Response('baz') ), 1234); $req = $this->getMockBuilder(RequestInfo::class) ->disableOriginalConstructor() ->getMock(); $this->assertSame('foo', $resp->getBody($req)); $this->assertTrue($resp->next()); $this->assertSame('bar', $resp->getBody($req)); $this->assertTrue($resp->next()); $this->assertSame('baz', $resp->getBody($req)); $this->assertFalse($resp->next()); } public function testGetRef() : void { $resp1 = new DelayedResponse(new DefaultResponse, 1234); $this->assertNotFalse( preg_match('/^[a-f0-9]{32}$/', $resp1->getRef()), 'Ref must be a 32 character hex string' ); $resp2 = new DelayedResponse(new Response('foo'), 1234); $this->assertNotFalse( preg_match('/^[a-f0-9]{32}$/', $resp2->getRef()), 'Ref is a 32 character hex string' ); $this->assertNotSame($resp1->getRef(), $resp2->getRef(), 'Ref is unique per response'); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/InternalServerTest.php
test/InternalServerTest.php
<?php namespace Test; use donatj\MockWebServer\InternalServer; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\RequestInfo; use PHPUnit\Framework\TestCase; class InternalServerTest extends TestCase { private $testTmpDir; /** * @before */ public function beforeEachTest() : void { $this->testTmpDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'testTemp'; mkdir($this->testTmpDir); $counterFileName = $this->testTmpDir . DIRECTORY_SEPARATOR . MockWebServer::REQUEST_COUNT_FILE; file_put_contents($counterFileName, '0'); } /** * @after */ public function afterEachTest() : void { $this->removeTempDirectory(); } private function removeTempDirectory() : void { $it = new \RecursiveDirectoryIterator($this->testTmpDir, \FilesystemIterator::SKIP_DOTS); $files = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::CHILD_FIRST); foreach( $files as $file ) { if( $file->isDir() ) { rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($this->testTmpDir); } /** * @dataProvider countProvider */ public function testShouldIncrementRequestCounter( ?int $inputCount, int $expectedCount ) : void { $counterFileName = $this->testTmpDir . DIRECTORY_SEPARATOR . MockWebServer::REQUEST_COUNT_FILE; file_put_contents($counterFileName, '0'); InternalServer::incrementRequestCounter($this->testTmpDir, $inputCount); $this->assertStringEqualsFile($counterFileName, (string)$expectedCount); } public function countProvider() : array { return [ 'null count' => [ 'inputCount' => null, 'expectedCount' => 1, ], 'int count' => [ 'inputCount' => 25, 'expectedCount' => 25, ], ]; } public function testShouldLogRequestsOnInstanceCreate() : void { $fakeReq = new RequestInfo([ 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET', ], [], [], [], [], [], ''); new InternalServer($this->testTmpDir, $fakeReq); $lastRequestFile = $this->testTmpDir . DIRECTORY_SEPARATOR . MockWebServer::LAST_REQUEST_FILE; $requestFile = $this->testTmpDir . DIRECTORY_SEPARATOR . 'request.1'; $lastRequestContent = file_get_contents($lastRequestFile); $requestContent = file_get_contents($requestFile); $this->assertSame($lastRequestContent, $requestContent); $this->assertSame(serialize($fakeReq), $requestContent); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Integration/InternalServer_IntegrationTest.php
test/Integration/InternalServer_IntegrationTest.php
<?php namespace Test\Integration; use donatj\MockWebServer\InternalServer; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\Response; use PHPUnit\Framework\TestCase; use Test\Integration\Mock\ExampleInitializingResponse; class InternalServer_IntegrationTest extends TestCase { private function getTempDirectory() : string { $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5(microtime(true) . ':' . rand(0, 100000)); mkdir($tmp); InternalServer::incrementRequestCounter($tmp, 0); return $tmp; } private function getRequestInfo( string $uri, array $GET = [], array $POST = [], array $HEADERS = [], array $FILES = [], array $COOKIE = [], string $method = 'GET' ) : RequestInfo { return new RequestInfo( [ 'REQUEST_METHOD' => $method, 'REQUEST_URI' => $uri, ], $GET, $POST, $FILES, $COOKIE, $HEADERS, '' ); } public function testInternalServer_DefaultResponse() : void { $tmp = $this->getTempDirectory(); $headers = []; $header = static function ( $header ) use ( &$headers ) { $headers[] = $header; }; $statusCode = null; $httpResponseCode = static function ( $code ) use ( &$statusCode ) { $statusCode = $code; }; $r = $this->getRequestInfo('/test?foo=bar&baz[]=qux&baz[]=quux', [ 'foo' => 1 ], [ 'baz' => 2 ]); $server = new InternalServer($tmp, $r, $header, $httpResponseCode); ob_start(); $server(); $contents = ob_get_clean(); $body = json_decode($contents, true); $this->assertSame(200, $statusCode); $this->assertSame([ 'Content-Type: application/json', ], $headers); $expectedBody = [ '_GET' => [ 'foo' => 1, ], '_POST' => [ 'baz' => 2, ], '_FILES' => [ ], '_COOKIE' => [ ], 'HEADERS' => [ ], 'METHOD' => 'GET', 'INPUT' => '', 'PARSED_INPUT' => [ ], 'REQUEST_URI' => '/test?foo=bar&baz[]=qux&baz[]=quux', 'PARSED_REQUEST_URI' => [ 'path' => '/test', 'query' => 'foo=bar&baz[]=qux&baz[]=quux', ], ]; $this->assertSame($expectedBody, $body); } /** * @dataProvider provideBodyWithContentType */ public function testInternalServer_CustomResponse( string $body, string $contentType ) : void { $tmp = $this->getTempDirectory(); $headers = []; $header = static function ( $header ) use ( &$headers ) { $headers[] = $header; }; $statusCode = null; $httpResponseCode = static function ( $code ) use ( &$statusCode ) { $statusCode = $code; }; $response = new Response($body, [ 'Content-Type' => $contentType ], 200); $r = $this->getRequestInfo(InternalServer::getPathOfRef($response->getRef())); InternalServer::storeResponse($tmp, $response); $server = new InternalServer($tmp, $r, $header, $httpResponseCode); ob_start(); $server(); $contents = ob_get_clean(); $this->assertSame(200, $statusCode); $this->assertSame([ 'Content-Type: ' . $contentType, ], $headers); $this->assertSame($body, $contents); } public function provideBodyWithContentType() : \Generator { yield [ 'Hello World!', 'text/plain; charset=UTF-8' ]; yield [ '{"foo":"bar"}', 'application/json' ]; yield [ '<html><body><h1>Test</h1></body></html>', 'text/html' ]; } public function testInternalServer_DefaultResponseFallthrough() : void { $tmp = $this->getTempDirectory(); $headers = []; $header = static function ( $header ) use ( &$headers ) { $headers[] = $header; }; $statusCode = null; $httpResponseCode = static function ( $code ) use ( &$statusCode ) { $statusCode = $code; }; $response = new Response('Default Response!!!', [ 'Default' => 'Response!' ], 400); $r = $this->getRequestInfo('/any/invalid/response'); InternalServer::storeDefaultResponse($tmp, $response); $server = new InternalServer($tmp, $r, $header, $httpResponseCode); ob_start(); $server(); $contents = ob_get_clean(); $this->assertSame(400, $statusCode); $this->assertSame([ 'Default: Response!', ], $headers); $this->assertSame('Default Response!!!', $contents); } public function testInternalServer_InitializingResponse() : void { $tmp = $this->getTempDirectory(); $response = new ExampleInitializingResponse; $headers = []; $header = static function ( $header ) use ( &$headers ) { $headers[] = $header; }; $r = $this->getRequestInfo(InternalServer::getPathOfRef($response->getRef())); InternalServer::storeResponse($tmp, $response); $server = new InternalServer($tmp, $r, $header, function () { }); ob_start(); $server(); ob_end_clean(); $this->assertSame([ 'X-Did-Call-Init: YES' ], $headers); } public function testInternalServer_InvalidRef404() : void { $tmp = $this->getTempDirectory(); $headers = []; $header = static function ( $header ) use ( &$headers ) { $headers[] = $header; }; $statusCode = null; $httpResponseCode = static function ( $code ) use ( &$statusCode ) { $statusCode = $code; }; $r = $this->getRequestInfo(InternalServer::getPathOfRef(str_repeat('a', 32))); $server = new InternalServer($tmp, $r, $header, $httpResponseCode); ob_start(); $server(); $contents = ob_get_clean(); $this->assertSame(404, $statusCode); $this->assertSame([], $headers); $this->assertSame("VND.DonatStudios.MockWebServer: Resource '/VND.DonatStudios.MockWebServer/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' not found!\n", $contents); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Integration/MockWebServer_IntegrationTest.php
test/Integration/MockWebServer_IntegrationTest.php
<?php namespace Test\Integration; use donatj\MockWebServer\DelayedResponse; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; use donatj\MockWebServer\ResponseByMethod; use donatj\MockWebServer\ResponseStack; use PHPUnit\Framework\TestCase; class MockWebServer_IntegrationTest extends TestCase { /** @var MockWebServer */ protected static $server; public static function setUpBeforeClass() : void { self::$server = new MockWebServer; self::$server->start(); } public function testBasic() : void { $url = self::$server->getServerRoot() . '/endpoint?get=foobar'; $content = file_get_contents($url); // Some versions of PHP send it with file_get_contents, others do not. // Might be removable with a context but until I figure that out, terrible hack $content = preg_replace('/,\s*"Connection": "close"/', '', $content); $body = [ '_GET' => [ 'get' => 'foobar', ], '_POST' => [], '_FILES' => [], '_COOKIE' => [], 'HEADERS' => [ 'Host' => '127.0.0.1:' . self::$server->getPort(), ], 'METHOD' => 'GET', 'INPUT' => '', 'PARSED_INPUT' => [], 'REQUEST_URI' => '/endpoint?get=foobar', 'PARSED_REQUEST_URI' => [ 'path' => '/endpoint', 'query' => 'get=foobar', ], ]; $this->assertJsonStringEqualsJsonString($content, json_encode($body)); $lastReq = self::$server->getLastRequest()->jsonSerialize(); foreach( $body as $key => $val ) { if( $key === 'HEADERS' ) { // This is the same horrible connection hack as above. Fix in time. unset($lastReq[$key]['Connection']); } $this->assertSame($lastReq[$key], $val); } } public function testSimple() : void { // We define the servers response to requests of the /definedPath endpoint $url = self::$server->setResponseOfPath( '/definedPath', new Response( 'This is our http body response', [ 'X-Foo-Bar' => 'BazBazBaz' ], 200 ) ); $content = file_get_contents($url); $this->assertContains('X-Foo-Bar: BazBazBaz', $http_response_header); $this->assertEquals("This is our http body response", $content); } public function testMulti() : void { $url = self::$server->getUrlOfResponse( new ResponseStack( new Response("Response One", [ 'X-Boop-Bat' => 'Sauce' ], 500), new Response("Response Two", [ 'X-Slaw-Dawg: FranCran' ], 400) ) ); $ctx = stream_context_create([ 'http' => [ 'ignore_errors' => true ] ]); $content = file_get_contents($url, false, $ctx); if( !( in_array('HTTP/1.0 500 Internal Server Error', $http_response_header, true) || in_array('HTTP/1.1 500 Internal Server Error', $http_response_header, true)) ) { $this->fail('must contain 500 Internal Server Error'); } $this->assertContains('X-Boop-Bat: Sauce', $http_response_header); $this->assertEquals("Response One", $content); $content = file_get_contents($url, false, $ctx); if( !( in_array('HTTP/1.0 400 Bad Request', $http_response_header, true) || in_array('HTTP/1.1 400 Bad Request', $http_response_header, true)) ) { $this->fail('must contain 400 Bad Request'); } $this->assertContains('X-Slaw-Dawg: FranCran', $http_response_header); $this->assertEquals("Response Two", $content); // this is expected to fail as we only have two responses in said stack $content = file_get_contents($url, false, $ctx); if( !( in_array('HTTP/1.0 404 Not Found', $http_response_header, true) || in_array('HTTP/1.1 404 Not Found', $http_response_header, true)) ) { $this->fail('must contain 404 Not Found'); } $this->assertEquals("Past the end of the ResponseStack", $content); } public function testHttpMethods() : void { $methods = [ ResponseByMethod::METHOD_GET, ResponseByMethod::METHOD_POST, ResponseByMethod::METHOD_PUT, ResponseByMethod::METHOD_PATCH, ResponseByMethod::METHOD_DELETE, ResponseByMethod::METHOD_HEAD, ResponseByMethod::METHOD_OPTIONS, ResponseByMethod::METHOD_TRACE, ]; $response = new ResponseByMethod; foreach( $methods as $method ) { $response->setMethodResponse($method, new Response( "This is our http $method body response", [ 'X-Foo-Bar' => 'Baz ' . $method ], 200 )); } $url = self::$server->setResponseOfPath('/definedPath', $response); foreach( $methods as $method ) { $context = stream_context_create([ 'http' => [ 'method' => $method ] ]); $content = file_get_contents($url, false, $context); $this->assertContains('X-Foo-Bar: Baz ' . $method, $http_response_header); if( $method !== ResponseByMethod::METHOD_HEAD ) { $this->assertEquals("This is our http $method body response", $content); } } $context = stream_context_create([ 'http' => [ 'method' => 'PROPFIND' ] ]); $content = @file_get_contents($url, false, $context); $this->assertFalse($content); $this->assertStringEndsWith('501 Not Implemented', $http_response_header[0]); } public function testHttpMethods_fallthrough() : void { $response = new ResponseByMethod([], new Response('Default Fallthrough', [], 400)); $url = self::$server->setResponseOfPath('/definedPath', $response); $context = stream_context_create([ 'http' => [ 'method' => 'PROPFIND', 'ignore_errors' => true ] ]); $content = @file_get_contents($url, false, $context); $this->assertSame('Default Fallthrough', $content); $this->assertStringEndsWith('400 Bad Request', $http_response_header[0]); } public function testDelayedResponse() : void { $realtimeResponse = new Response( 'This is our http body response', [ 'X-Foo-Bar' => 'BazBazBaz' ], 200 ); $delayedResponse = new DelayedResponse($realtimeResponse, 1000000); $this->assertNotSame($realtimeResponse->getRef(), $delayedResponse->getRef(), 'DelayedResponse should change the ref. If they are the same, using both causes issues.'); $realtimeUrl = self::$server->setResponseOfPath('/realtimePath', $realtimeResponse); $delayedUrl = self::$server->setResponseOfPath('/delayedPath', $delayedResponse); $realtimeStart = microtime(true); $content = @file_get_contents($realtimeUrl); $this->assertNotFalse($content); $delayedStart = microtime(true); $delayedContent = file_get_contents($delayedUrl); $end = microtime(true); $this->assertGreaterThan(.9, ($end - $delayedStart) - ($delayedStart - $realtimeStart), 'Delayed response should take ~1 seconds longer than realtime response'); $this->assertEquals('This is our http body response', $delayedContent); $this->assertContains('X-Foo-Bar: BazBazBaz', $http_response_header); } public function testDelayedMultiResponse() : void { $multi = new ResponseStack( new Response('Response One', [ 'X-Boop-Bat' => 'Sauce' ], 200), new Response('Response Two', [ 'X-Slaw-Dawg: FranCran' ], 200) ); $delayed = new DelayedResponse($multi, 1000000); $path = self::$server->setResponseOfPath('/delayedMultiPath', $delayed); $start = microtime(true); $contentOne = file_get_contents($path); $this->assertSame($contentOne, 'Response One'); $this->assertContains('X-Boop-Bat: Sauce', $http_response_header); $this->assertGreaterThan(.9, microtime(true) - $start, 'Delayed response should take ~1 seconds longer than realtime response'); $start = microtime(true); $contentTwo = file_get_contents($path); $this->assertSame($contentTwo, 'Response Two'); $this->assertContains('X-Slaw-Dawg: FranCran', $http_response_header); $this->assertGreaterThan(.9, microtime(true) - $start, 'Delayed response should take ~1 seconds longer than realtime response'); } public function testMultiResponseWithPartialDelay() : void { $multi = new ResponseStack( new Response('Response One', [ 'X-Boop-Bat' => 'Sauce' ], 200), new DelayedResponse(new Response('Response Two', [ 'X-Slaw-Dawg: FranCran' ], 200), 1000000) ); $path = self::$server->setResponseOfPath('/delayedMultiPath', $multi); $start = microtime(true); $contentOne = file_get_contents($path); $this->assertSame($contentOne, 'Response One'); $this->assertContains('X-Boop-Bat: Sauce', $http_response_header); $this->assertLessThan(.2, microtime(true) - $start, 'Delayed response should take less than 200ms'); $start = microtime(true); $contentTwo = file_get_contents($path); $this->assertSame($contentTwo, 'Response Two'); $this->assertContains('X-Slaw-Dawg: FranCran', $http_response_header); $this->assertGreaterThan(.9, microtime(true) - $start, 'Delayed response should take ~1 seconds longer than realtime response'); } /** * Regression Test - Was a problem in 1.0.0-beta.2 */ public function testEmptySingle() : void { $url = self::$server->getUrlOfResponse(new Response('')); $this->assertSame('', file_get_contents($url)); } public function testBinaryResponse() : void { $response = new Response( gzencode('This is our http body response'), [ 'Content-Encoding: gzip' ], 200 ); $url = self::$server->setResponseOfPath('/', $response); $content = @file_get_contents($url); $this->assertNotFalse($content); $this->assertSame('This is our http body response', gzdecode($content)); $this->assertContains('Content-Encoding: gzip', $http_response_header); } /** * @dataProvider requestInfoProvider */ public function testRequestInfo( $method, $uri, $respBody, $reqBody, array $headers, $status, $query, array $expectedCookies, array $serverVars ) { $url = self::$server->setResponseOfPath($uri, new Response($respBody, $headers, $status)); // Get cURL resource $ch = curl_init(); // Set url curl_setopt($ch, CURLOPT_URL, $url . '?' . $query); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $xheaders = []; foreach( $headers as $hkey => $hval ) { $xheaders[] = "{$hkey}: $hval"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $xheaders); // Create body if( is_array($reqBody) ) { $encReqBody = http_build_query($reqBody); } else { $encReqBody = $reqBody ?: ''; } if( $encReqBody ) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $encReqBody); } // Send the request & save response to $resp $resp = curl_exec($ch); $this->assertNotEmpty($resp, "response body is empty, request failed"); $this->assertSame($status, curl_getinfo($ch, CURLINFO_HTTP_CODE)); // Close request to clear up some resources curl_close($ch); $request = self::$server->getLastRequest(); $this->assertSame($uri . '?' . $query, $request->getRequestUri()); $this->assertSame([ 'path' => $uri, 'query' => ltrim($query, '?') ], $request->getParsedUri()); $this->assertContains(self::$server->getHost() . ':' . self::$server->getPort(), $request->getHeaders()); $reqHeaders = $request->getHeaders(); foreach( $headers as $hkey => $hval ) { $this->assertSame($reqHeaders[$hkey], $hval); } $this->assertSame($query, http_build_query($request->getGet())); $this->assertSame($method, $request->getRequestMethod()); $this->assertSame($expectedCookies, $request->getCookie()); $this->assertSame($encReqBody, $request->getInput()); parse_str($encReqBody, $decReqBody); $this->assertSame($decReqBody, $request->getParsedInput()); if( $method === 'POST' ) { $this->assertSame($decReqBody, $request->getPost()); } $server = $request->getServer(); $this->assertEquals(self::$server->getHost(), $server['SERVER_NAME']); $this->assertEquals(self::$server->getPort(), $server['SERVER_PORT']); foreach( $serverVars as $sKey => $sVal ) { $this->assertSame($server[$sKey], $sVal); } } public function requestInfoProvider() : array { return [ [ 'GET', '/requestInfoPath', 'This is our http body response', null, [ 'X-Foo-Bar' => 'BazBazBaz', 'Accept' => 'Juice' ], 200, 'foo=bar', [], [ 'HTTP_ACCEPT' => 'Juice', 'QUERY_STRING' => 'foo=bar' ], ], [ 'POST', '/requestInfoPath', 'This is my POST response', [ 'a' => 1 ], [ 'X-Boo-Bop' => 'Beep Boop', 'Cookie' => 'juice=mango' ], 301, 'x=1', [ 'juice' => 'mango', ], [ 'REQUEST_METHOD' => 'POST', 'QUERY_STRING' => 'x=1' ], ], [ 'PUT', '/put/path/90210', 'Put put put', [ 'a' => 1 ], [ 'X-Boo-Bop' => 'Beep Boop', 'Cookie' => 'a=b; c=d; e=f; what="soup"' ], 301, 'x=1', [ 'a' => 'b', 'c' => 'd', 'e' => 'f', 'what' => '"soup"', ], [ 'REQUEST_METHOD' => 'PUT', 'QUERY_STRING' => 'x=1' ], ], ]; } public function testStartStopServer() : void { $server = new MockWebServer; $server->start(); $this->assertTrue($server->isRunning()); $server->stop(); $this->assertFalse($server->isRunning()); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Integration/MockWebServer_ChangedDefault_IntegrationTest.php
test/Integration/MockWebServer_ChangedDefault_IntegrationTest.php
<?php namespace Test\Integration; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; use donatj\MockWebServer\Responses\NotFoundResponse; use PHPUnit\Framework\TestCase; class MockWebServer_ChangedDefault_IntegrationTest extends TestCase { public function testChangingDefaultResponse() : void { $server = new MockWebServer; $server->start(); $server->setResponseOfPath('funk', new Response('fresh')); $path = $server->getUrlOfResponse(new Response('fries')); $content = file_get_contents($server->getServerRoot() . '/PageDoesNotExist'); $result = json_decode($content, true); $this->assertNotFalse(stripos($http_response_header[0], '200 OK')); $this->assertSame('/PageDoesNotExist', $result['PARSED_REQUEST_URI']['path']); // try with a 404 $server->setDefaultResponse(new NotFoundResponse); $content = file_get_contents($server->getServerRoot() . '/PageDoesNotExist', false, stream_context_create([ 'http' => [ 'ignore_errors' => true ], // allow reading 404s ])); $this->assertNotFalse(stripos($http_response_header[0], '404 Not Found')); $this->assertSame("VND.DonatStudios.MockWebServer: Resource '/PageDoesNotExist' not found!\n", $content); // try with a custom response $server->setDefaultResponse(new Response('cool beans')); $content = file_get_contents($server->getServerRoot() . '/BadUrlBadTime'); $this->assertSame('cool beans', $content); // ensure non-404-ing pages continue to work as expected $content = file_get_contents($server->getServerRoot() . '/funk'); $this->assertSame('fresh', $content); $content = file_get_contents($path); $this->assertSame('fries', $content); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Integration/MockWebServer_GetRequestByOffset_IntegrationTest.php
test/Integration/MockWebServer_GetRequestByOffset_IntegrationTest.php
<?php namespace Test\Integration; use donatj\MockWebServer\MockWebServer; use PHPUnit\Framework\TestCase; class MockWebServer_GetRequestByOffset_IntegrationTest extends TestCase { public function testGetRequestByOffset() : void { $server = new MockWebServer; $server->start(); for( $i = 0; $i <= 80; $i++ ) { $link = $server->getServerRoot() . '/link' . $i; $content = @file_get_contents($link); $this->assertNotFalse($content, "test link $i"); } for( $i = 0; $i <= 80; $i++ ) { $this->assertSame('/link' . $i, $server->getRequestByOffset($i)->getRequestUri(), "test positive offset alignment"); } for( $i = 0; $i <= 80; $i++ ) { $this->assertSame('/link' . $i, $server->getRequestByOffset(-81 + $i)->getRequestUri(), "test negative offset alignment"); } } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Integration/Mock/ExampleInitializingResponse.php
test/Integration/Mock/ExampleInitializingResponse.php
<?php namespace Test\Integration\Mock; use donatj\MockWebServer\InitializingResponseInterface; use donatj\MockWebServer\RequestInfo; use donatj\MockWebServer\Response; class ExampleInitializingResponse extends Response implements InitializingResponseInterface { public function __construct() { parent::__construct('Initializing Response'); } public function initialize( RequestInfo $request ) : void { $this->headers['X-Did-Call-Init'] = 'YES'; } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Regression/ResponseByMethod_RegressionTest.php
test/Regression/ResponseByMethod_RegressionTest.php
<?php namespace Test\Regression; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; use donatj\MockWebServer\ResponseByMethod; use donatj\MockWebServer\ResponseStack; use PHPUnit\Framework\TestCase; class ResponseByMethod_RegressionTest extends TestCase { public function test_forwardNextAsExpected() : void { $server = new MockWebServer; $path = $server->setResponseOfPath( '/interest-categories/cat-xyz/interests', new ResponseByMethod([ ResponseByMethod::METHOD_GET => new ResponseStack( new Response('get-a'), new Response('get-b'), new Response('get-c') ), ResponseByMethod::METHOD_DELETE => new ResponseStack( new Response('delete-a'), new Response('delete-b'), new Response('delete-c') ), ]) ); $server->start(); $method = function ( string $method ) { return stream_context_create([ 'http' => [ 'method' => $method ] ]); }; $this->assertSame('get-a', file_get_contents($path)); $this->assertSame('delete-a', file_get_contents($path, false, $method('DELETE'))); $this->assertSame('get-b', file_get_contents($path)); $this->assertSame('delete-b', file_get_contents($path, false, $method('DELETE'))); $this->assertSame('delete-c', file_get_contents($path, false, $method('DELETE'))); $this->assertSame(false, @file_get_contents($path, false, $method('DELETE'))); $this->assertSame('get-c', file_get_contents($path)); $this->assertSame(false, @file_get_contents($path)); $server->stop(); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/test/Regression/MockWebServer_RegressionTest.php
test/Regression/MockWebServer_RegressionTest.php
<?php namespace Test\Regression; use donatj\MockWebServer\MockWebServer; use PHPUnit\Framework\TestCase; class MockWebServer_RegressionTest extends TestCase { /** * @doesNotPerformAssertions */ public function test_stopTwiceShouldNotExplode() : void { $server = new MockWebServer; $server->start(); $server->stop(); $server->stop(); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/.phan/config.php
.phan/config.php
<?php /** * This configuration will be read and overlaid on top of the * default configuration. Command line arguments will be applied * after this file is read. */ return [ // Supported values: '7.0', '7.1', '7.2', '7.3', null. // If this is set to null, // then Phan assumes the PHP version which is closest to the minor version // of the php executable used to execute phan. "target_php_version" => '7.1', // A list of directories that should be parsed for class and // method information. After excluding the directories // defined in exclude_analysis_directory_list, the remaining // files will be statically analyzed for errors. // // Thus, both first-party and third-party code being used by // your application should be included in this list. 'directory_list' => [ 'src', 'vendor/ralouphie', ], "exclude_file_list" => [ ], // "exclude_file_regex" => "@\.html\.php$@", // A directory list that defines files that will be excluded // from static analysis, but whose class and method // information should be included. // // Generally, you'll want to include the directories for // third-party code (such as "vendor/") in this list. // // n.b.: If you'd like to parse but not analyze 3rd // party code, directories containing that code // should be added to the `directory_list` as // to `exclude_analysis_directory_list`. "exclude_analysis_directory_list" => [ 'vendor/', ], 'plugin_config' => [ 'infer_pure_methods' => true, ], // A list of plugin files to execute. // See https://github.com/phan/phan/tree/master/.phan/plugins for even more. // (Pass these in as relative paths. // Base names without extensions such as 'AlwaysReturnPlugin' // can be used to refer to a plugin that is bundled with Phan) 'plugins' => [ // checks if a function, closure or method unconditionally returns. // can also be written as 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php' 'AlwaysReturnPlugin', // Checks for syntactically unreachable statements in // the global scope or function bodies. 'UnreachableCodePlugin', 'DollarDollarPlugin', 'DuplicateExpressionPlugin', 'DuplicateArrayKeyPlugin', 'PregRegexCheckerPlugin', 'PrintfCheckerPlugin', 'PHPUnitNotDeadCodePlugin', 'LoopVariableReusePlugin', 'UseReturnValuePlugin', 'RedundantAssignmentPlugin', 'InvalidVariableIssetPlugin', ], // Add any issue types (such as 'PhanUndeclaredMethod') // to this black-list to inhibit them from being reported. 'suppress_issue_types' => [ 'PhanUnusedPublicMethodParameter', ], 'unused_variable_detection' => true, ];
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/basic.php
example/basic.php
<?php use donatj\MockWebServer\MockWebServer; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); $url = $server->getServerRoot() . '/endpoint?get=foobar'; echo "Requesting: $url\n\n"; echo file_get_contents($url);
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/delayed.php
example/delayed.php
<?php use donatj\MockWebServer\DelayedResponse; use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); $response = new Response( 'This is our http body response', [ 'Cache-Control' => 'no-cache' ], 200 ); // Wrap the response in a DelayedResponse object, which will delay the response $delayedResponse = new DelayedResponse( $response, 100000 // sets a delay of 100000 microseconds (.1 seconds) before returning the response ); $realtimeUrl = $server->setResponseOfPath('/realtime', $response); $delayedUrl = $server->setResponseOfPath('/delayed', $delayedResponse); echo "Requesting: $realtimeUrl\n\n"; // This request will run as quickly as possible $start = microtime(true); file_get_contents($realtimeUrl); echo "Realtime Request took: " . (microtime(true) - $start) . " seconds\n\n"; echo "Requesting: $delayedUrl\n\n"; // The request will take the delayed time + the time it takes to make and transfer the request $start = microtime(true); file_get_contents($delayedUrl); echo "Delayed Request took: " . (microtime(true) - $start) . " seconds\n\n";
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/notfound.php
example/notfound.php
<?php use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Responses\NotFoundResponse; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); // The default response is donatj\MockWebServer\Responses\DefaultResponse // which returns an HTTP 200 and a descriptive JSON payload. // // Change the default response to donatj\MockWebServer\Responses\NotFoundResponse // to get a standard 404. // // Any other response may be specified as default as well. $server->setDefaultResponse(new NotFoundResponse); $content = file_get_contents($server->getServerRoot() . '/PageDoesNotExist', false, stream_context_create([ 'http' => [ 'ignore_errors' => true ], // allow reading 404s ])); // $http_response_header is a little known variable magically defined // in the current scope by file_get_contents with the response headers echo implode("\n", $http_response_header) . "\n\n"; echo $content . "\n";
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/multi.php
example/multi.php
<?php use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; use donatj\MockWebServer\ResponseStack; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); // We define the servers response to requests of the /definedPath endpoint $url = $server->setResponseOfPath( '/definedPath', new ResponseStack( new Response("Response One"), new Response("Response Two") ) ); echo "Requesting: $url\n\n"; $contentOne = file_get_contents($url); $contentTwo = file_get_contents($url); // This third request is expected to 404 which will error if errors are not ignored $contentThree = file_get_contents($url, false, stream_context_create([ 'http' => [ 'ignore_errors' => true ] ])); // $http_response_header is a little known variable magically defined // in the current scope by file_get_contents with the response headers echo $contentOne . "\n"; echo $contentTwo . "\n"; echo $contentThree . "\n";
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/methods.php
example/methods.php
<?php use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; use donatj\MockWebServer\ResponseByMethod; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); // Create a response for both a POST and GET request to the same URL $response = new ResponseByMethod([ ResponseByMethod::METHOD_GET => new Response("This is our http GET response"), ResponseByMethod::METHOD_POST => new Response("This is our http POST response", [], 201), ]); $url = $server->setResponseOfPath('/foo/bar', $response); foreach( [ ResponseByMethod::METHOD_GET, ResponseByMethod::METHOD_POST ] as $method ) { echo "$method request to $url:\n"; $context = stream_context_create([ 'http' => [ 'method' => $method ] ]); $content = file_get_contents($url, false, $context); echo $content . "\n\n"; }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/simple.php
example/simple.php
<?php use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; require __DIR__ . '/../vendor/autoload.php'; $server = new MockWebServer; $server->start(); // We define the server's response to requests of the /definedPath endpoint $url = $server->setResponseOfPath( '/definedPath', new Response( 'This is our http body response', [ 'Cache-Control' => 'no-cache' ], 200 ) ); echo "Requesting: $url\n\n"; $content = file_get_contents($url); // $http_response_header is a little known variable magically defined // in the current scope by file_get_contents with the response headers echo implode("\n", $http_response_header) . "\n\n"; echo $content . "\n";
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/example/phpunit.php
example/phpunit.php
<?php use donatj\MockWebServer\MockWebServer; use donatj\MockWebServer\Response; class ExampleTest extends PHPUnit\Framework\TestCase { /** @var MockWebServer */ protected static $server; public static function setUpBeforeClass() : void { self::$server = new MockWebServer; self::$server->start(); } public function testGetParams() : void { $result = file_get_contents(self::$server->getServerRoot() . '/autoEndpoint?foo=bar'); $decoded = json_decode($result, true); $this->assertSame('bar', $decoded['_GET']['foo']); } public function testGetSetPath() : void { // $url = http://127.0.0.1:8123/definedEndPoint $url = self::$server->setResponseOfPath('/definedEndPoint', new Response('foo bar content')); $result = file_get_contents($url); $this->assertSame('foo bar content', $result); } public static function tearDownAfterClass() : void { // stopping the web server during tear down allows us to reuse the port for later tests self::$server->stop(); } }
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
donatj/mock-webserver
https://github.com/donatj/mock-webserver/blob/01be0a641fda727c7fc140679c924fc8c8dc120e/server/server.php
server/server.php
<?php use donatj\MockWebServer\MockWebServer; $files = [ __DIR__ . '/../vendor/autoload.php', __DIR__ . '/../../../autoload.php', ]; foreach( $files as $file ) { if( file_exists($file) ) { require_once $file; break; } } $INPUT = file_get_contents("php://input"); if( $INPUT === false ) { throw new RuntimeException('Failed to read php://input'); } $HEADERS = getallheaders(); $tmp = getenv(MockWebServer::TMP_ENV); if( $tmp === false || $tmp === '' ) { throw new RuntimeException('Environment variable ' . MockWebServer::TMP_ENV . ' is not set'); } $r = new \donatj\MockWebServer\RequestInfo($_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $HEADERS, $INPUT); $server = new \donatj\MockWebServer\InternalServer($tmp, $r); $server();
php
MIT
01be0a641fda727c7fc140679c924fc8c8dc120e
2026-01-05T04:53:13.099180Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/JobStatusTest.php
test/Resque/Tests/JobStatusTest.php
<?php require_once dirname(__FILE__) . '/bootstrap.php'; /** * Resque_Job_Status tests. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_JobStatusTest extends Resque_Tests_TestCase { public function setUp() { parent::setUp(); // Register a worker to test with $this->worker = new Resque_Worker('jobs'); } public function testJobStatusCanBeTracked() { $token = Resque::enqueue('jobs', 'Test_Job', null, true); $status = new Resque_Job_Status($token); $this->assertTrue($status->isTracking()); } public function testJobStatusIsReturnedViaJobInstance() { $token = Resque::enqueue('jobs', 'Test_Job', null, true); $job = Resque_Job::reserve('jobs'); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $job->getStatus()); } public function testQueuedJobReturnsQueuedStatus() { $token = Resque::enqueue('jobs', 'Test_Job', null, true); $status = new Resque_Job_Status($token); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get()); } public function testRunningJobReturnsRunningStatus() { $token = Resque::enqueue('jobs', 'Failing_Job', null, true); $job = $this->worker->reserve(); $this->worker->workingOn($job); $status = new Resque_Job_Status($token); $this->assertEquals(Resque_Job_Status::STATUS_RUNNING, $status->get()); } public function testFailedJobReturnsFailedStatus() { $token = Resque::enqueue('jobs', 'Failing_Job', null, true); $this->worker->work(0); $status = new Resque_Job_Status($token); $this->assertEquals(Resque_Job_Status::STATUS_FAILED, $status->get()); } public function testCompletedJobReturnsCompletedStatus() { $token = Resque::enqueue('jobs', 'Test_Job', null, true); $this->worker->work(0); $status = new Resque_Job_Status($token); $this->assertEquals(Resque_Job_Status::STATUS_COMPLETE, $status->get()); } public function testStatusIsNotTrackedWhenToldNotTo() { $token = Resque::enqueue('jobs', 'Test_Job', null, false); $status = new Resque_Job_Status($token); $this->assertFalse($status->isTracking()); } public function testStatusTrackingCanBeStopped() { Resque_Job_Status::create('test'); $status = new Resque_Job_Status('test'); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $status->get()); $status->stop(); $this->assertFalse($status->get()); } public function testRecreatedJobWithTrackingStillTracksStatus() { $originalToken = Resque::enqueue('jobs', 'Test_Job', null, true); $job = $this->worker->reserve(); // Mark this job as being worked on to ensure that the new status is still // waiting. $this->worker->workingOn($job); // Now recreate it $newToken = $job->recreate(); // Make sure we've got a new job returned $this->assertNotEquals($originalToken, $newToken); // Now check the status of the new job $newJob = Resque_Job::reserve('jobs'); $this->assertEquals(Resque_Job_Status::STATUS_WAITING, $newJob->getStatus()); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/JobTest.php
test/Resque/Tests/JobTest.php
<?php require_once dirname(__FILE__) . '/bootstrap.php'; /** * Resque_Job tests. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_JobTest extends Resque_Tests_TestCase { protected $worker; public function setUp() { parent::setUp(); // Register a worker to test with $this->worker = new Resque_Worker('jobs'); $this->worker->registerWorker(); } public function testJobCanBeQueued() { $this->assertTrue((bool)Resque::enqueue('jobs', 'Test_Job')); } public function testQeueuedJobCanBeReserved() { Resque::enqueue('jobs', 'Test_Job'); $job = Resque_Job::reserve('jobs'); if ($job == false) { $this->fail('Job could not be reserved.'); } $this->assertEquals('jobs', $job->queue); $this->assertEquals('Test_Job', $job->payload['class']); } /** * @expectedException InvalidArgumentException */ public function testObjectArgumentsCannotBePassedToJob() { $args = new stdClass; $args->test = 'somevalue'; Resque::enqueue('jobs', 'Test_Job', $args); } public function testQueuedJobReturnsExactSamePassedInArguments() { $args = [ 'int' => 123, 'numArray' => [ 1, 2, ], 'assocArray' => [ 'key1' => 'value1', 'key2' => 'value2', ], ]; Resque::enqueue('jobs', 'Test_Job', $args); $job = Resque_Job::reserve('jobs'); $this->assertEquals($args, $job->getArguments()); } public function testAfterJobIsReservedItIsRemoved() { Resque::enqueue('jobs', 'Test_Job'); Resque_Job::reserve('jobs'); $this->assertFalse(Resque_Job::reserve('jobs')); } public function testRecreatedJobMatchesExistingJob() { $args = [ 'int' => 123, 'numArray' => [ 1, 2, ], 'assocArray' => [ 'key1' => 'value1', 'key2' => 'value2', ], ]; Resque::enqueue('jobs', 'Test_Job', $args); $job = Resque_Job::reserve('jobs'); // Now recreate it $job->recreate(); $newJob = Resque_Job::reserve('jobs'); $this->assertEquals($job->payload['class'], $newJob->payload['class']); $this->assertEquals($job->payload['args'], $newJob->getArguments()); } public function testFailedJobExceptionsAreCaught() { $payload = [ 'class' => 'Failing_Job', 'id' => 'randomId', 'args' => null, ]; $job = new Resque_Job('jobs', $payload); $job->worker = $this->worker; $this->worker->perform($job); $this->assertEquals(1, Resque_Stat::get('failed')); $this->assertEquals(1, Resque_Stat::get('failed:' . $this->worker)); } /** * @expectedException Resque_Exception */ public function testJobWithoutPerformMethodThrowsException() { Resque::enqueue('jobs', 'Test_Job_Without_Perform_Method'); $job = $this->worker->reserve(); $job->worker = $this->worker; $job->perform(); } /** * @expectedException Resque_Exception */ public function testInvalidJobThrowsException() { Resque::enqueue('jobs', 'Invalid_Job'); $job = $this->worker->reserve(); $job->worker = $this->worker; $job->perform(); } public function testJobWithSetUpCallbackFiresSetUp() { $payload = [ 'class' => 'Test_Job_With_SetUp', 'args' => [ 'somevar', 'somevar2', ], ]; $job = new Resque_Job('jobs', $payload); $job->perform(); $this->assertTrue(Test_Job_With_SetUp::$called); } public function testJobWithTearDownCallbackFiresTearDown() { $payload = [ 'class' => 'Test_Job_With_TearDown', 'args' => [ 'somevar', 'somevar2', ], ]; $job = new Resque_Job('jobs', $payload); $job->perform(); $this->assertTrue(Test_Job_With_TearDown::$called); } public function testJobWithNamespace() { Resque::setBackend(REDIS_HOST, REDIS_DATABASE, 'php'); $queue = 'jobs'; $payload = ['another_value']; Resque::enqueue($queue, 'Test_Job_With_TearDown', $payload); $this->assertEquals(Resque::queues(), ['jobs']); $this->assertEquals(Resque::size($queue), 1); Resque::setBackend(REDIS_HOST, REDIS_DATABASE, REDIS_NAMESPACE); $this->assertEquals(Resque::size($queue), 0); } public function testDequeueAll() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue'); $this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::dequeue($queue), 2); $this->assertEquals(Resque::size($queue), 0); } public function testDequeueMakeSureNotDeleteOthers() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue'); Resque::enqueue($queue, 'Test_Job_Dequeue'); $other_queue = 'other_jobs'; Resque::enqueue($other_queue, 'Test_Job_Dequeue'); Resque::enqueue($other_queue, 'Test_Job_Dequeue'); $this->assertEquals(Resque::size($queue), 2); $this->assertEquals(Resque::size($other_queue), 2); $this->assertEquals(Resque::dequeue($queue), 2); $this->assertEquals(Resque::size($queue), 0); $this->assertEquals(Resque::size($other_queue), 2); } public function testDequeueSpecificItem() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue2'); $this->assertEquals(Resque::size($queue), 2); $test = ['Test_Job_Dequeue2']; $this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::size($queue), 1); } public function testDequeueSpecificMultipleItems() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue3'); $this->assertEquals(Resque::size($queue), 3); $test = ['Test_Job_Dequeue2', 'Test_Job_Dequeue3']; $this->assertEquals(Resque::dequeue($queue, $test), 2); $this->assertEquals(Resque::size($queue), 1); } public function testDequeueNonExistingItem() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue3'); $this->assertEquals(Resque::size($queue), 3); $test = ['Test_Job_Dequeue4']; $this->assertEquals(Resque::dequeue($queue, $test), 0); $this->assertEquals(Resque::size($queue), 3); } public function testDequeueNonExistingItem2() { $queue = 'jobs'; Resque::enqueue($queue, 'Test_Job_Dequeue1'); Resque::enqueue($queue, 'Test_Job_Dequeue2'); Resque::enqueue($queue, 'Test_Job_Dequeue3'); $this->assertEquals(Resque::size($queue), 3); $test = ['Test_Job_Dequeue4', 'Test_Job_Dequeue1']; $this->assertEquals(Resque::dequeue($queue, $test), 1); $this->assertEquals(Resque::size($queue), 2); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/EventTest.php
test/Resque/Tests/EventTest.php
<?php require_once dirname(__FILE__) . '/bootstrap.php'; /** * Resque_Event tests. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_EventTest extends Resque_Tests_TestCase { private $callbacksHit = array(); public function setUp() { Test_Job::$called = false; // Register a worker to test with $this->worker = new Resque_Worker('jobs'); $this->worker->registerWorker(); } public function tearDown() { Resque_Event::clearListeners(); $this->callbacksHit = array(); } public function getEventTestJob() { $payload = array( 'class' => 'Test_Job', 'id' => 'randomId', 'args' => array( 'somevar', ), ); $job = new Resque_Job('jobs', $payload); $job->worker = $this->worker; return $job; } public function eventCallbackProvider() { return array( array('beforePerform', 'beforePerformEventCallback'), array('afterPerform', 'afterPerformEventCallback'), array('afterFork', 'afterForkEventCallback'), ); } /** * @dataProvider eventCallbackProvider */ public function testEventCallbacksFire($event, $callback) { Resque_Event::listen($event, array($this, $callback)); $job = $this->getEventTestJob(); $this->worker->perform($job); $this->worker->work(0); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); } public function testBeforeForkEventCallbackFires() { $event = 'beforeFork'; $callback = 'beforeForkEventCallback'; Resque_Event::listen($event, array($this, $callback)); Resque::enqueue('jobs', 'Test_Job', array( 'somevar' )); $job = $this->getEventTestJob(); $this->worker->work(0); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); } public function testBeforePerformEventCanStopWork() { $callback = 'beforePerformEventDontPerformCallback'; Resque_Event::listen('beforePerform', array($this, $callback)); $job = $this->getEventTestJob(); $this->assertFalse($job->perform()); $this->assertContains($callback, $this->callbacksHit, $callback . ' callback was not called'); $this->assertFalse(Test_Job::$called, 'Job was still performed though Resque_Job_DontPerform was thrown'); } public function testAfterEnqueueEventCallbackFires() { $callback = 'afterEnqueueEventCallback'; $event = 'afterEnqueue'; Resque_Event::listen($event, array($this, $callback)); Resque::enqueue('jobs', 'Test_Job', array( 'somevar' )); $this->assertContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was not called'); } public function testStopListeningRemovesListener() { $callback = 'beforePerformEventCallback'; $event = 'beforePerform'; Resque_Event::listen($event, array($this, $callback)); Resque_Event::stopListening($event, array($this, $callback)); $job = $this->getEventTestJob(); $this->worker->perform($job); $this->worker->work(0); $this->assertNotContains($callback, $this->callbacksHit, $event . ' callback (' . $callback .') was called though Resque_Event::stopListening was called' ); } public function beforePerformEventDontPerformCallback($instance) { $this->callbacksHit[] = __FUNCTION__; throw new Resque_Job_DontPerform; } public function assertValidEventCallback($function, $job) { $this->callbacksHit[] = $function; if (!$job instanceof Resque_Job) { $this->fail('Callback job argument is not an instance of Resque_Job'); } $args = $job->getArguments(); $this->assertEquals($args[0], 'somevar'); } public function afterEnqueueEventCallback($class, $args) { $this->callbacksHit[] = __FUNCTION__; $this->assertEquals('Test_Job', $class); $this->assertEquals(array( 'somevar', ), $args); } public function beforePerformEventCallback($job) { $this->assertValidEventCallback(__FUNCTION__, $job); } public function afterPerformEventCallback($job) { $this->assertValidEventCallback(__FUNCTION__, $job); } public function beforeForkEventCallback($job) { $this->assertValidEventCallback(__FUNCTION__, $job); } public function afterForkEventCallback($job) { $this->assertValidEventCallback(__FUNCTION__, $job); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/TestCase.php
test/Resque/Tests/TestCase.php
<?php /** * Resque test case class. Contains setup and teardown methods. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_TestCase extends PHPUnit_Framework_TestCase { protected $resque; protected $redis; public function setUp() { $config = file_get_contents(REDIS_CONF); preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches); $this->redis = new RedisApi('localhost', $matches[1]); $this->redis->prefix(REDIS_NAMESPACE); $this->redis->select(REDIS_DATABASE); // Flush redis $this->redis->flushAll(); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/StatTest.php
test/Resque/Tests/StatTest.php
<?php require_once dirname(__FILE__) . '/bootstrap.php'; /** * Resque_Stat tests. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_StatTest extends Resque_Tests_TestCase { public function testStatCanBeIncremented() { Resque_Stat::incr('test_incr'); Resque_Stat::incr('test_incr'); $this->assertEquals(2, $this->redis->get('stat:test_incr')); } public function testStatCanBeIncrementedByX() { Resque_Stat::incr('test_incrX', 10); Resque_Stat::incr('test_incrX', 11); $this->assertEquals(21, $this->redis->get('stat:test_incrX')); } public function testStatCanBeDecremented() { Resque_Stat::incr('test_decr', 22); Resque_Stat::decr('test_decr'); $this->assertEquals(21, $this->redis->get('stat:test_decr')); } public function testStatCanBeDecrementedByX() { Resque_Stat::incr('test_decrX', 22); Resque_Stat::decr('test_decrX', 11); $this->assertEquals(11, $this->redis->get('stat:test_decrX')); } public function testGetStatByName() { Resque_Stat::incr('test_get', 100); $this->assertEquals(100, Resque_Stat::get('test_get')); } public function testGetUnknownStatReturns0() { $this->assertEquals(0, Resque_Stat::get('test_get_unknown')); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/bootstrap.php
test/Resque/Tests/bootstrap.php
<?php /** * Resque test bootstrap file - sets up a test environment. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ define('CWD', dirname(__FILE__)); define('RESQUE_LIB', CWD . '/../../../lib/'); define('TEST_MISC', realpath(CWD . '/../../misc/')); define('REDIS_CONF', TEST_MISC . '/redis.conf'); // Change to the directory this file lives in. This is important, due to // how we'll be running redis. require_once CWD . '/TestCase.php'; // Include Resque require_once RESQUE_LIB . 'Resque.php'; require_once RESQUE_LIB . 'Resque/Worker.php'; require_once RESQUE_LIB . 'Resque/Redis.php'; // Attempt to start our own redis instance for tesitng. exec('which redis-server', $output, $returnVar); if($returnVar != 0) { echo "Cannot find redis-server in path. Please make sure redis is installed.\n"; exit(1); } exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar); usleep(500000); if($returnVar != 0) { echo "Cannot start redis-server.\n"; exit(1); } // Get redis port from conf $config = file_get_contents(REDIS_CONF); if(!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) { echo "Could not determine redis port from redis.conf"; exit(1); } define('REDIS_HOST', 'localhost:' . $matches[1]); define('REDIS_DATABASE', 7); define('REDIS_NAMESPACE', 'testResque'); Resque::setBackend(REDIS_HOST, REDIS_DATABASE, REDIS_NAMESPACE); // Shutdown function killRedis($pid) { if (getmypid() !== $pid) { return; // don't kill from a forked worker } $config = file_get_contents(REDIS_CONF); if(!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches)) { return; } $pidFile = TEST_MISC . '/' . $matches[1]; if (file_exists($pidFile)) { $pid = trim(file_get_contents($pidFile)); posix_kill((int) $pid, 9); if(is_file($pidFile)) { unlink($pidFile); } } // Remove the redis database if(!preg_match('#^\s*dir\s+([^\s]+)#m', $config, $matches)) { return; } $dir = $matches[1]; if(!preg_match('#^\s*dbfilename\s+([^\s]+)#m', $config, $matches)) { return; } $filename = TEST_MISC . '/' . $dir . '/' . $matches[1]; if(is_file($filename)) { unlink($filename); } } register_shutdown_function('killRedis', getmypid()); if(function_exists('pcntl_signal')) { // Override INT and TERM signals, so they do a clean shutdown and also // clean up redis-server as well. function sigint() { exit; } pcntl_signal(SIGINT, 'sigint'); pcntl_signal(SIGTERM, 'sigint'); } class Test_Job { public static $called = false; public function perform() { self::$called = true; } } class Failing_Job_Exception extends Exception { } class Failing_Job { public function perform() { throw new Failing_Job_Exception('Message!'); } } class Test_Job_Without_Perform_Method { } class Test_Job_With_SetUp { public static $called = false; public $args = false; public function setUp() { self::$called = true; } public function perform() { } } class Test_Job_With_TearDown { public static $called = false; public $args = false; public function perform() { } public function tearDown() { self::$called = true; } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/test/Resque/Tests/WorkerTest.php
test/Resque/Tests/WorkerTest.php
<?php require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'bootstrap.php'; /** * Resque_Worker tests. * * @package Resque/Tests * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Tests_WorkerTest extends Resque_Tests_TestCase { public function testWorkerRegistersInList() { $worker = new Resque_Worker('*'); $worker->registerWorker(); // Make sure the worker is in the list $this->assertTrue((bool)$this->redis->sismember('workers', (string)$worker)); } public function testGetAllWorkers() { $num = 3; // Register a few workers for($i = 0; $i < $num; ++$i) { $worker = new Resque_Worker('queue_' . $i); $worker->registerWorker(); } // Now try to get them $this->assertEquals($num, count(Resque_Worker::all())); } public function testGetWorkerById() { $worker = new Resque_Worker('*'); $worker->registerWorker(); $newWorker = Resque_Worker::find((string)$worker); $this->assertEquals((string)$worker, (string)$newWorker); } public function testInvalidWorkerDoesNotExist() { $this->assertFalse(Resque_Worker::exists('blah')); } public function testWorkerCanUnregister() { $worker = new Resque_Worker('*'); $worker->registerWorker(); $worker->unregisterWorker(); $this->assertFalse(Resque_Worker::exists((string)$worker)); $this->assertEquals(array(), Resque_Worker::all()); $this->assertEquals(array(), $this->redis->smembers('resque:workers')); } public function testPausedWorkerDoesNotPickUpJobs() { $worker = new Resque_Worker('*'); $worker->pauseProcessing(); Resque::enqueue('jobs', 'Test_Job'); $worker->work(0); $worker->work(0); $this->assertEquals(0, Resque_Stat::get('processed')); } public function testResumedWorkerPicksUpJobs() { $worker = new Resque_Worker('*'); $worker->pauseProcessing(); Resque::enqueue('jobs', 'Test_Job'); $worker->work(0); $this->assertEquals(0, Resque_Stat::get('processed')); $worker->unPauseProcessing(); $worker->work(0); $this->assertEquals(1, Resque_Stat::get('processed')); } public function testWorkerCanWorkOverMultipleQueues() { $worker = new Resque_Worker(array( 'queue1', 'queue2' )); $worker->registerWorker(); Resque::enqueue('queue1', 'Test_Job_1'); Resque::enqueue('queue2', 'Test_Job_2'); $job = $worker->reserve(); $this->assertEquals('queue1', $job->queue); $job = $worker->reserve(); $this->assertEquals('queue2', $job->queue); } public function testWorkerWorksQueuesInSpecifiedOrder() { $worker = new Resque_Worker(array( 'high', 'medium', 'low' )); $worker->registerWorker(); // Queue the jobs in a different order Resque::enqueue('low', 'Test_Job_1'); Resque::enqueue('high', 'Test_Job_2'); Resque::enqueue('medium', 'Test_Job_3'); // Now check we get the jobs back in the right order $job = $worker->reserve(); $this->assertEquals('high', $job->queue); $job = $worker->reserve(); $this->assertEquals('medium', $job->queue); $job = $worker->reserve(); $this->assertEquals('low', $job->queue); } public function testWildcardQueueWorkerWorksAllQueues() { $worker = new Resque_Worker('*'); $worker->registerWorker(); Resque::enqueue('queue1', 'Test_Job_1'); Resque::enqueue('queue2', 'Test_Job_2'); $job = $worker->reserve(); $this->assertEquals('queue1', $job->queue); $job = $worker->reserve(); $this->assertEquals('queue2', $job->queue); } public function testWorkerDoesNotWorkOnUnknownQueues() { $worker = new Resque_Worker('queue1'); $worker->registerWorker(); Resque::enqueue('queue2', 'Test_Job'); $this->assertFalse($worker->reserve()); } public function testWorkerClearsItsStatusWhenNotWorking() { Resque::enqueue('jobs', 'Test_Job'); $worker = new Resque_Worker('jobs'); $job = $worker->reserve(); $worker->workingOn($job); $worker->doneWorking(); $this->assertEquals(array(), $worker->job()); } public function testWorkerRecordsWhatItIsWorkingOn() { $worker = new Resque_Worker('jobs'); $worker->registerWorker(); $payload = array( 'class' => 'Test_Job' ); $job = new Resque_Job('jobs', $payload); $worker->workingOn($job); $job = $worker->job(); $this->assertEquals('jobs', $job['queue']); if(!isset($job['run_at'])) { $this->fail('Job does not have run_at time'); } $this->assertEquals($payload, $job['payload']); } public function testWorkerErasesItsStatsWhenShutdown() { Resque::enqueue('jobs', 'Test_Job'); Resque::enqueue('jobs', 'Invalid_Job'); $worker = new Resque_Worker('jobs'); $worker->work(0); $worker->work(0); $this->assertEquals(0, $worker->getStat('processed')); $this->assertEquals(0, $worker->getStat('failed')); } public function testWorkerCleansUpDeadWorkersOnStartup() { // Register a good worker $goodWorker = new Resque_Worker('jobs'); $goodWorker->registerWorker(); $workerId = explode(':', $goodWorker); // Register some bad workers $worker = new Resque_Worker('jobs'); $worker->setId($workerId[0].':1:jobs'); $worker->registerWorker(); $worker = new Resque_Worker(array('high', 'low')); $worker->setId($workerId[0].':2:high,low'); $worker->registerWorker(); $this->assertEquals(3, count(Resque_Worker::all())); $goodWorker->pruneDeadWorkers(); // There should only be $goodWorker left now $this->assertEquals(1, count(Resque_Worker::all())); } public function testDeadWorkerCleanUpDoesNotCleanUnknownWorkers() { // Register a bad worker on this machine $worker = new Resque_Worker('jobs'); $workerId = explode(':', $worker); $worker->setId($workerId[0].':1:jobs'); $worker->registerWorker(); // Register some other false workers $worker = new Resque_Worker('jobs'); $worker->setId('my.other.host:1:jobs'); $worker->registerWorker(); $this->assertEquals(2, count(Resque_Worker::all())); $worker->pruneDeadWorkers(); // my.other.host should be left $workers = Resque_Worker::all(); $this->assertEquals(1, count($workers)); $this->assertEquals((string)$worker, (string)$workers[0]); } public function testWorkerFailsUncompletedJobsOnExit() { $worker = new Resque_Worker('jobs'); $worker->registerWorker(); $payload = array( 'class' => 'Test_Job', 'id' => 'randomId' ); $job = new Resque_Job('jobs', $payload); $worker->workingOn($job); $worker->unregisterWorker(); $this->assertEquals(1, Resque_Stat::get('failed')); } public function testWorkerLogAllMessageOnVerbose() { $worker = new Resque_Worker('jobs'); $worker->logLevel = Resque_Worker::LOG_VERBOSE; $worker->logOutput = fopen('php://memory', 'r+'); $message = array('message' => 'x', 'data' => ''); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_DEBUG)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_INFO)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_WARNING)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_CRITICAL)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_ERROR)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_ALERT)); rewind($worker->logOutput); $output = stream_get_contents($worker->logOutput); $lines = explode("\n", $output); $this->assertEquals(6, count($lines) -1); } public function testWorkerLogOnlyInfoMessageOnNonVerbose() { $worker = new Resque_Worker('jobs'); $worker->logLevel = Resque_Worker::LOG_NORMAL; $worker->logOutput = fopen('php://memory', 'r+'); $message = array('message' => 'x', 'data' => ''); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_DEBUG)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_INFO)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_WARNING)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_CRITICAL)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_ERROR)); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_ALERT)); rewind($worker->logOutput); $output = stream_get_contents($worker->logOutput); $lines = explode("\n", $output); $this->assertEquals(5, count($lines) -1); } public function testWorkerLogNothingWhenLogNone() { $worker = new Resque_Worker('jobs'); $worker->logLevel = Resque_Worker::LOG_NONE; $worker->logOutput = fopen('php://memory', 'r+'); $message = array('message' => 'x', 'data' => ''); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_DEBUG)); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_INFO)); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_WARNING)); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_CRITICAL)); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_ERROR)); $this->assertEquals(false, $worker->log($message, Resque_Worker::LOG_TYPE_ALERT)); rewind($worker->logOutput); $output = stream_get_contents($worker->logOutput); $lines = explode("\n", $output); $this->assertEquals(0, count($lines) -1); } public function testWorkerLogWithISOTime() { $worker = new Resque_Worker('jobs'); $worker->logLevel = Resque_Worker::LOG_NORMAL; $worker->logOutput = fopen('php://memory', 'r+'); $message = array('message' => 'x', 'data' => ''); $now = date('c'); $this->assertEquals(true, $worker->log($message, Resque_Worker::LOG_TYPE_INFO)); rewind($worker->logOutput); $output = stream_get_contents($worker->logOutput); $lines = explode("\n", $output); $this->assertEquals(1, count($lines) -1); $this->assertEquals('[' . $now . '] x', $lines[0]); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque.php
lib/Resque.php
<?php require_once dirname(__FILE__) . '/Resque/Event.php'; require_once dirname(__FILE__) . '/Resque/Exception.php'; /** * Base Resque class. * * @package Resque * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque { const VERSION = '1.2.5'; /** * @var Resque_Redis Instance of Resque_Redis that talks to redis. */ public static $redis = null; /** * @var mixed Host/port conbination separated by a colon, or a nested * array of server swith host/port pairs */ protected static $redisServer = null; /** * @var int ID of Redis database to select. */ protected static $redisDatabase = 0; /** * @var string namespace of the redis keys */ protected static $namespace = ''; /** * @var string password for the redis server */ protected static $password = null; /** * @var int PID of current process. Used to detect changes when forking * and implement "thread" safety to avoid race conditions. */ protected static $pid = null; /** * Given a host/port combination separated by a colon, set it as * the redis server that Resque will talk to. * * @param mixed $server Host/port combination separated by a colon, or * a nested array of servers with host/port pairs. * @param int $database */ public static function setBackend($server, $database = 0, $namespace = 'resque', $password = null) { self::$redisServer = $server; self::$redisDatabase = $database; self::$redis = null; self::$namespace = $namespace; self::$password = $password; } /** * Return an instance of the Resque_Redis class instantiated for Resque. * * @return Resque_Redis Instance of Resque_Redis. */ public static function redis() { // Detect when the PID of the current process has changed (from a fork, etc) // and force a reconnect to redis. $pid = getmypid(); if (self::$pid !== $pid) { self::$redis = null; self::$pid = $pid; } if (!is_null(self::$redis)) { return self::$redis; } $server = self::$redisServer; if (empty($server)) { $server = 'localhost:6379'; } if (is_array($server)) { require_once dirname(__FILE__) . '/Resque/RedisCluster.php'; self::$redis = new Resque_RedisCluster($server); } else { if (strpos($server, 'unix:') === false) { list($host, $port) = explode(':', $server); } else { $host = $server; $port = null; } require_once dirname(__FILE__) . '/Resque/Redis.php'; $redisInstance = new Resque_Redis($host, $port, self::$password); $redisInstance->prefix(self::$namespace); self::$redis = $redisInstance; } if (!empty(self::$redisDatabase)) { self::$redis->select(self::$redisDatabase); } return self::$redis; } /** * Push a job to the end of a specific queue. If the queue does not * exist, then create it as well. * * @param string $queue The name of the queue to add the job to. * @param array $item Job description as an array to be JSON encoded. */ public static function push($queue, $item) { self::redis()->sadd('queues', $queue); self::redis()->rpush('queue:' . $queue, json_encode($item)); } /** * Pop an item off the end of the specified queue, decode it and * return it. * * @param string $queue The name of the queue to fetch an item from. * @return array Decoded item from the queue. */ public static function pop($queue) { $item = self::redis()->lpop('queue:' . $queue); if (!$item) { return; } return json_decode($item, true); } /** * Remove items of the specified queue * * @param string $queue The name of the queue to fetch an item from. * @param array $items * @return integer number of deleted items */ public static function dequeue($queue, $items = []) { if (count($items) > 0) { return self::removeItems($queue, $items); } else { return self::removeList($queue); } } /** * Return the size (number of pending jobs) of the specified queue. * * @param $queue name of the queue to be checked for pending jobs * * @return int The size of the queue. */ public static function size($queue) { return self::redis()->llen('queue:' . $queue); } /** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @param string $class The name of the class that contains the code to execute the job. * @param array $args Any optional arguments that should be passed when the job is executed. * @param boolean $trackStatus Set to true to be able to monitor the status of a job. * * @return string */ public static function enqueue($queue, $class, $args = null, $trackStatus = false) { require_once dirname(__FILE__) . '/Resque/Job.php'; $result = Resque_Job::create($queue, $class, $args, $trackStatus); if ($result) { Resque_Event::trigger('afterEnqueue', [ 'class' => $class, 'args' => $args, 'queue' => $queue, ]); } return $result; } /** * Reserve and return the next available job in the specified queue. * * @param string $queue Queue to fetch next available job from. * @return Resque_Job Instance of Resque_Job to be processed, false if none or error. */ public static function reserve($queue) { require_once dirname(__FILE__) . '/Resque/Job.php'; return Resque_Job::reserve($queue); } /** * Get an array of all known queues. * * @return array Array of queues. */ public static function queues() { $queues = self::redis()->smembers('queues'); if (!is_array($queues)) { $queues = []; } return $queues; } /** * Remove Items from the queue * Safely moving each item to a temporary queue before processing it * If the Job matches, counts otherwise puts it in a requeue_queue * which at the end eventually be copied back into the original queue * * @private * * @param string $queue The name of the queue * @param array $items * @return integer number of deleted items */ private static function removeItems($queue, $items = []) { $counter = 0; $originalQueue = 'queue:' . $queue; $tempQueue = $originalQueue . ':temp:' . time(); $requeueQueue = $tempQueue . ':requeue'; // move each item from original queue to temp queue and process it $finished = false; while (!$finished) { $string = self::redis()->rpoplpush($originalQueue, self::redis()->getPrefix() . $tempQueue); if (!empty($string)) { if (self::matchItem($string, $items)) { self::redis()->rpop($tempQueue); $counter++; } else { self::redis()->rpoplpush($tempQueue, self::redis()->getPrefix() . $requeueQueue); } } else { $finished = true; } } // move back from temp queue to original queue $finished = false; while (!$finished) { $string = self::redis()->rpoplpush($requeueQueue, self::redis()->getPrefix() . $originalQueue); if (empty($string)) { $finished = true; } } // remove temp queue and requeue queue self::redis()->del($requeueQueue); self::redis()->del($tempQueue); return $counter; } /** * matching item * item can be ['class'] or ['class' => 'id'] or ['class' => {:foo => 1, :bar => 2}] * @private * * @params string $string redis result in json * @params $items * * @return (bool) */ private static function matchItem($string, $items) { $decoded = json_decode($string, true); foreach ($items as $key => $val) { # class name only ex: item[0] = ['class'] if (is_numeric($key)) { if ($decoded['class'] == $val) { return true; } # class name with args , example: item[0] = ['class' => {'foo' => 1, 'bar' => 2}] } elseif (is_array($val)) { $decodedArgs = (array)$decoded['args'][0]; if ($decoded['class'] == $key && count($decodedArgs) > 0 && count(array_diff($decodedArgs, $val)) == 0 ) { return true; } # class name with ID, example: item[0] = ['class' => 'id'] } else { if ($decoded['class'] == $key && $decoded['id'] == $val) { return true; } } } return false; } /** * Remove List * * @private * * @params string $queue the name of the queue * @return integer number of deleted items belongs to this list */ private static function removeList($queue) { $counter = self::size($queue); $result = self::redis()->del('queue:' . $queue); return ($result == 1) ? $counter : 0; } /* * Generate an identifier to attach to a job for status tracking. * * @return string */ public static function generateJobId() { return md5(uniqid('', true)); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Redis.php
lib/Resque/Redis.php
<?php if (class_exists('Redis')) { class RedisApi extends Redis { private static $defaultNamespace = 'resque:'; public function __construct($host, $port, $timeout = 5, $password = null) { parent::__construct(); $this->host = $host; $this->port = $port; $this->timeout = $timeout; $this->password = $password; $this->establishConnection(); } function establishConnection() { $this->pconnect($this->host, (int)$this->port, (int)$this->timeout, getmypid()); if ($this->password !== null) { $this->auth($this->password); } $this->setOption(Redis::OPT_PREFIX, self::$defaultNamespace); } public function prefix($namespace) { if (empty($namespace)) $namespace = self::$defaultNamespace; if (strpos($namespace, ':') === false) { $namespace .= ':'; } self::$defaultNamespace = $namespace; $this->setOption(Redis::OPT_PREFIX, self::$defaultNamespace); } public static function getPrefix() { return ''; } } } else { // Third- party apps may have already loaded Resident from elsewhere // so lets be careful. if (!class_exists('Redisent', false)) { require_once dirname(__FILE__) . '/../Redisent/Redisent.php'; } /** * Extended Redisent class used by Resque for all communication with * redis. Essentially adds namespace support to Redisent. * * @package Resque/Redis * @author Chris Boulton <chris.boulton@interspire.com> * @copyright (c) 2010 Chris Boulton * @license http://www.opensource.org/licenses/mit-license.php */ class RedisApi extends Redisent { /** * Redis namespace * @var string */ private static $defaultNamespace = 'resque:'; /** * @var array List of all commands in Redis that supply a key as their * first argument. Used to prefix keys with the Resque namespace. */ private $keyCommands = [ 'exists', 'del', 'type', 'keys', 'expire', 'ttl', 'move', 'set', 'setex', 'get', 'getset', 'setnx', 'incr', 'incrby', 'decr', 'decrby', 'rpush', 'lpush', 'llen', 'lrange', 'ltrim', 'lindex', 'lset', 'lrem', 'lpop', 'rpop', 'sadd', 'srem', 'spop', 'scard', 'sismember', 'smembers', 'srandmember', 'zadd', 'zrem', 'zrange', 'zrevrange', 'zrangebyscore', 'zcard', 'zscore', 'zremrangebyscore', 'sort', 'rpoplpush', ]; // sinterstore // sunion // sunionstore // sdiff // sdiffstore // sinter // smove // rename // mget // msetnx // mset // renamenx /** * Set Redis namespace (prefix) default: resque * @param string $namespace */ public function prefix($namespace) { if (strpos($namespace, ':') === false) { $namespace .= ':'; } self::$defaultNamespace = $namespace; } /** * Magic method to handle all function requests and prefix key based * operations with the {self::$defaultNamespace} key prefix. * * @param string $name The name of the method called. * @param array $args Array of supplied arguments to the method. * @return mixed Return value from Resident::call() based on the command. */ public function __call($name, $args) { $args = func_get_args(); if (in_array(strtolower($name), $this->keyCommands)) { $args[1][0] = self::$defaultNamespace . $args[1][0]; } try { return parent::__call($name, $args[1]); } catch (RedisException $e) { return false; } } public static function getPrefix() { return self::$defaultNamespace; } } } class Resque_Redis extends redisApi { public function __construct($host, $port, $password = null) { if (is_subclass_of($this, 'Redis')) { parent::__construct($host, $port, 5, $password); } else { parent::__construct($host, $port); } } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Job.php
lib/Resque/Job.php
<?php require_once dirname(__FILE__) . '/Event.php'; require_once dirname(__FILE__) . '/Job/Status.php'; require_once dirname(__FILE__) . '/Job/DontPerform.php'; /** * Resque job. * * @package Resque/Job * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Job { /** * @var string The name of the queue that this job belongs to. */ public $queue; /** * @var Resque_Worker Instance of the Resque worker running this job. */ public $worker; /** * @var object Object containing details of the job. */ public $payload; /** * @var object Instance of the class performing work for this job. */ private $instance; /** * Instantiate a new instance of a job. * * @param string $queue The queue that the job belongs to. * @param array $payload array containing details of the job. */ public function __construct($queue, $payload) { $this->queue = $queue; $this->payload = $payload; } /** * Create a new job and save it to the specified queue. * * @param string $queue The name of the queue to place the job in. * @param string $class The name of the class that contains the code to execute the job. * @param array $args Any optional arguments that should be passed when the job is executed. * @param boolean $monitor Set to true to be able to monitor the status of a job. * * @return string */ public static function create($queue, $class, $args = null, $monitor = false) { if ($args !== null && !is_array($args)) { throw new InvalidArgumentException( 'Supplied $args must be an array.' ); } $new = true; if(isset($args['id'])) { $id = $args['id']; unset($args['id']); $new = false; } else { $id = md5(uniqid('', true)); } Resque::push($queue, array( 'class' => $class, 'args' => array($args), 'id' => $id, )); if ($monitor) { if ($new) { Resque_Job_Status::create($id); } else { $statusInstance = new Resque_Job_Status($id); $statusInstance->update($id, Resque_Job_Status::STATUS_WAITING); } } return $id; } /** * Find the next available job from the specified queue and return an * instance of Resque_Job for it. * * @param string $queue The name of the queue to check for a job in. * @return null|object Null when there aren't any waiting jobs, instance of Resque_Job when a job was found. */ public static function reserve($queue) { $payload = Resque::pop($queue); if(!is_array($payload)) { return false; } return new Resque_Job($queue, $payload); } /** * Update the status of the current job. * * @param int $status Status constant from Resque_Job_Status indicating the current status of a job. */ public function updateStatus($status) { if(empty($this->payload['id'])) { return; } $statusInstance = new Resque_Job_Status($this->payload['id']); $statusInstance->update($status); } /** * Return the status of the current job. * * @return int The status of the job as one of the Resque_Job_Status constants. */ public function getStatus() { $status = new Resque_Job_Status($this->payload['id']); return $status->get(); } /** * Get the arguments supplied to this job. * * @return array Array of arguments. */ public function getArguments() { if (!isset($this->payload['args'])) { return array(); } return $this->payload['args'][0]; } /** * Get the instantiated object for this job that will be performing work. * * @return object Instance of the object that this job belongs to. */ public function getInstance() { if (!is_null($this->instance)) { return $this->instance; } if (class_exists('Resque_Job_Creator')) { $this->instance = Resque_Job_Creator::createJob($this->payload['class'], $this->getArguments()); } else { if(!class_exists($this->payload['class'])) { throw new Resque_Exception( 'Could not find job class ' . $this->payload['class'] . '.' ); } if(!method_exists($this->payload['class'], 'perform')) { throw new Resque_Exception( 'Job class ' . $this->payload['class'] . ' does not contain a perform method.' ); } $this->instance = new $this->payload['class'](); } $this->instance->job = $this; $this->instance->args = $this->getArguments(); $this->instance->queue = $this->queue; return $this->instance; } /** * Actually execute a job by calling the perform method on the class * associated with the job with the supplied arguments. * * @return bool * @throws Resque_Exception When the job's class could not be found or it does not contain a perform method. */ public function perform() { $instance = $this->getInstance(); try { Resque_Event::trigger('beforePerform', $this); if(method_exists($instance, 'setUp')) { $instance->setUp(); } $instance->perform(); if(method_exists($instance, 'tearDown')) { $instance->tearDown(); } Resque_Event::trigger('afterPerform', $this); } // beforePerform/setUp have said don't perform this job. Return. catch(Resque_Job_DontPerform $e) { return false; } return true; } /** * Mark the current job as having failed. * * @param $exception */ public function fail($exception) { Resque_Event::trigger('onFailure', array( 'exception' => $exception, 'job' => $this, )); $this->updateStatus(Resque_Job_Status::STATUS_FAILED); require_once dirname(__FILE__) . '/Failure.php'; Resque_Failure::create( $this->payload, $exception, $this->worker, $this->queue ); Resque_Stat::incr('failed'); Resque_Stat::incr('failed:' . $this->worker); } /** * Re-queue the current job. * @return string */ public function recreate() { $status = new Resque_Job_Status($this->payload['id']); $monitor = false; if($status->isTracking()) { $monitor = true; } return self::create($this->queue, $this->payload['class'], $this->payload['args'], $monitor); } /** * Generate a string representation used to describe the current job. * * @return string The string representation of the job. */ public function __toString() { return json_encode(array( 'queue' => $this->queue, 'id' => !empty($this->payload['id']) ? $this->payload['id'] : '', 'class' => $this->payload['class'], 'args' => !empty($this->payload['args']) ? $this->payload['args'] : '' )); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Failure.php
lib/Resque/Failure.php
<?php require_once dirname(__FILE__) . '/Failure/Interface.php'; /** * Failed Resque job. * * @package Resque/Failure * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Failure { /** * @var string Class name representing the backend to pass failed jobs off to. */ private static $backend; /** * Create a new failed job on the backend. * * @param object $payload The contents of the job that has just failed. * @param \Exception $exception The exception generated when the job failed to run. * @param \Resque_Worker $worker Instance of Resque_Worker that was running this job when it failed. * @param string $queue The name of the queue that this job was fetched from. */ public static function create($payload, Exception $exception, Resque_Worker $worker, $queue) { $backend = self::getBackend(); new $backend($payload, $exception, $worker, $queue); } /** * Return an instance of the backend for saving job failures. * * @return object Instance of backend object. */ public static function getBackend() { if(self::$backend === null) { require dirname(__FILE__) . '/Failure/Redis.php'; self::$backend = 'Resque_Failure_Redis'; } return self::$backend; } /** * Set the backend to use for raised job failures. The supplied backend * should be the name of a class to be instantiated when a job fails. * It is your responsibility to have the backend class loaded (or autoloaded) * * @param string $backend The class name of the backend to pipe failures to. */ public static function setBackend($backend) { self::$backend = $backend; } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Exception.php
lib/Resque/Exception.php
<?php /** * Resque exception. * * @package Resque * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Exception extends Exception { } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Stat.php
lib/Resque/Stat.php
<?php /** * Resque statistic management (jobs processed, failed, etc) * * @package Resque/Stat * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Stat { /** * Get the value of the supplied statistic counter for the specified statistic. * * @param string $stat The name of the statistic to get the stats for. * @return mixed Value of the statistic. */ public static function get($stat) { return (int)Resque::redis()->get('stat:' . $stat); } /** * Increment the value of the specified statistic by a certain amount (default is 1) * * @param string $stat The name of the statistic to increment. * @param int $by The amount to increment the statistic by. * @return boolean True if successful, false if not. */ public static function incr($stat, $by = 1) { return (bool)Resque::redis()->incrby('stat:' . $stat, $by); } /** * Decrement the value of the specified statistic by a certain amount (default is 1) * * @param string $stat The name of the statistic to decrement. * @param int $by The amount to decrement the statistic by. * @return boolean True if successful, false if not. */ public static function decr($stat, $by = 1) { return (bool)Resque::redis()->decrby('stat:' . $stat, $by); } /** * Delete a statistic with the given name. * * @param string $stat The name of the statistic to delete. * @return boolean True if successful, false if not. */ public static function clear($stat) { return (bool)Resque::redis()->del('stat:' . $stat); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Event.php
lib/Resque/Event.php
<?php /** * Resque event/plugin system class * * @package Resque/Event * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Event { /** * @var array Array containing all registered callbacks, indexked by event name. */ private static $events = array(); /** * Raise a given event with the supplied data. * * @param string $event Name of event to be raised. * @param mixed $data Optional, any data that should be passed to each callback. * @return true */ public static function trigger($event, $data = null) { if (!is_array($data)) { $data = array($data); } if (empty(self::$events[$event])) { return true; } foreach (self::$events[$event] as $callback) { if (!is_callable($callback)) { continue; } call_user_func_array($callback, $data); } return true; } /** * Listen in on a given event to have a specified callback fired. * * @param string $event Name of event to listen on. * @param mixed $callback Any callback callable by call_user_func_array. * @return true */ public static function listen($event, $callback) { if (!isset(self::$events[$event])) { self::$events[$event] = array(); } self::$events[$event][] = $callback; return true; } /** * Stop a given callback from listening on a specific event. * * @param string $event Name of event. * @param mixed $callback The callback as defined when listen() was called. * @return true */ public static function stopListening($event, $callback) { if (!isset(self::$events[$event])) { return true; } $key = array_search($callback, self::$events[$event]); if ($key !== false) { unset(self::$events[$event][$key]); } return true; } /** * Call all registered listeners. */ public static function clearListeners() { self::$events = array(); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Worker.php
lib/Resque/Worker.php
<?php require_once dirname(__FILE__) . '/Stat.php'; require_once dirname(__FILE__) . '/Event.php'; require_once dirname(__FILE__) . '/Job.php'; require_once dirname(__FILE__) . '/Job/DirtyExitException.php'; // Find and initialize Composer $files = array( __DIR__ . '/../../vendor/autoload.php', __DIR__ . '/../../../autoload.php', __DIR__ . '/../../../../autoload.php', __DIR__ . '/../vendor/autoload.php' ); foreach ($files as $file) { if (file_exists($file)) { require_once $file; break; } } if (!class_exists('Composer\Autoload\ClassLoader', false)) { die( 'You need to set up the project dependencies using the following commands:' . PHP_EOL . 'curl -s http://getcomposer.org/installer | php' . PHP_EOL . 'php composer.phar install' . PHP_EOL ); } /** * Resque worker that handles checking queues for jobs, fetching them * off the queues, running them and handling the result. * * @package Resque/Worker * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Worker { const LOG_NONE = 0; const LOG_NORMAL = 1; const LOG_VERBOSE = 2; const LOG_TYPE_DEBUG = 100; const LOG_TYPE_INFO = 200; const LOG_TYPE_WARNING = 300; const LOG_TYPE_ERROR = 400; const LOG_TYPE_CRITICAL = 500; const LOG_TYPE_ALERT = 550; public $logOutput = STDOUT; /** * @var int Current log level of this worker. */ public $logLevel = self::LOG_NONE; /** * @var array Array of all associated queues for this worker. */ protected $queues = array(); /** * @var string The hostname of this worker. */ protected $hostname; /** * @var boolean True if on the next iteration, the worker should shutdown. */ protected $shutdown = false; /** * @var boolean True if this worker is paused. */ protected $paused = false; /** * @var string String identifying this worker. */ protected $id; /** * @var Resque_Job Current job, if any, being processed by this worker. * */ protected $currentJob = null; /** * @var int Process ID of child worker processes. */ protected $child = null; protected $logger = null; /** * Return all workers known to Resque as instantiated instances. * @return array */ public static function all() { $workers = Resque::redis()->smembers('workers'); if (!is_array($workers)) { $workers = array(); } $instances = array(); foreach ($workers as $workerId) { $instances[] = self::find($workerId); } return $instances; } /** * Given a worker ID, check if it is registered/valid. * * @param string $workerId ID of the worker. * @return boolean True if the worker exists, false if not. */ public static function exists($workerId) { return (bool)Resque::redis()->sismember('workers', $workerId); } /** * Given a worker ID, find it and return an instantiated worker class for it. * * @param string $workerId The ID of the worker. * @return Resque_Worker Instance of the worker. False if the worker does not exist. */ public static function find($workerId) { if (!self::exists($workerId) || false === strpos($workerId, ":")) { return false; } list($hostname, $pid, $queues) = explode(':', $workerId, 3); $queues = explode(',', $queues); $worker = new self($queues); $worker->setId($workerId); $worker->logger = $worker->getLogger($workerId); return $worker; } /** * Set the ID of this worker to a given ID string. * * @param string $workerId ID for the worker. */ public function setId($workerId) { $this->id = $workerId; } /** * Instantiate a new worker, given a list of queues that it should be working * on. The list of queues should be supplied in the priority that they should * be checked for jobs (first come, first served) * * Passing a single '*' allows the worker to work on all queues in alphabetical * order. You can easily add new queues dynamically and have them worked on using * this method. * * @param string|array $queues String with a single queue name, array with multiple. */ public function __construct($queues) { if (!is_array($queues)) { $queues = array($queues); } $this->queues = $queues; if (function_exists('gethostname')) { $hostname = gethostname(); } else { $hostname = php_uname('n'); } $this->hostname = $hostname; $this->id = $this->hostname . ':'.getmypid() . ':' . implode(',', $this->queues); } /** * The primary loop for a worker which when called on an instance starts * the worker's life cycle. * * Queues are checked every $interval (seconds) for new jobs. * * @param int $interval How often to check for new jobs across the queues. */ public function work($interval = 5) { $this->updateProcLine('Starting'); $this->startup(); while (true) { if ($this->shutdown) { break; } // Attempt to find and reserve a job $job = false; if (!$this->paused) { try { $job = $this->reserve(); } catch (\RedisException $e) { $this->log(array('message' => 'Redis exception caught: ' . $e->getMessage(), 'data' => array('type' => 'fail', 'log' => $e->getMessage(), 'time' => time())), self::LOG_TYPE_ALERT); } } if (!$job) { // For an interval of 0, break now - helps with unit testing etc if ($interval == 0) { break; } // If no job was found, we sleep for $interval before continuing and checking again $this->log(array('message' => 'Sleeping for ' . $interval, 'data' => array('type' => 'sleep', 'second' => $interval)), self::LOG_TYPE_DEBUG); if ($this->paused) { $this->updateProcLine('Paused'); } else { $this->updateProcLine('Waiting for ' . implode(',', $this->queues)); } usleep($interval * 1000000); continue; } $this->log(array('message' => 'got ' . $job, 'data' => array('type' => 'got', 'args' => $job)), self::LOG_TYPE_INFO); Resque_Event::trigger('beforeFork', $job); $this->workingOn($job); $workerName = $this->hostname . ':'.getmypid(); $this->child = $this->fork(); // Forked and we're the child. Run the job. if ($this->child === 0 || $this->child === false) { $status = 'Processing ID:' . $job->payload['id'] . ' in ' . $job->queue; $this->updateProcLine($status); $this->log(array('message' => $status, 'data' => array('type' => 'process', 'worker' => $workerName, 'job_id' => $job->payload['id'])), self::LOG_TYPE_INFO); $this->perform($job); if ($this->child === 0) { exit(0); } } if ($this->child > 0) { // Parent process, sit and wait $status = 'Forked ' . $this->child . ' for ID:' . $job->payload['id']; $this->updateProcLine($status); $this->log(array('message' => $status, 'data' => array('type' => 'fork', 'worker' => $workerName, 'job_id' => $job->payload['id'])), self::LOG_TYPE_DEBUG); // Wait until the child process finishes before continuing pcntl_wait($status); $exitStatus = pcntl_wexitstatus($status); if ($exitStatus !== 0) { $job->fail(new Resque_Job_DirtyExitException('Job exited with exit code ' . $exitStatus)); } } $this->child = null; $this->doneWorking(); } $this->unregisterWorker(); } /** * Process a single job. * * @param Resque_Job $job The job to be processed. */ public function perform(Resque_Job $job) { $startTime = microtime(true); try { Resque_Event::trigger('afterFork', $job); $job->perform(); $this->log(array('message' => 'done ID:' . $job->payload['id'], 'data' => array('type' => 'done', 'job_id' => $job->payload['id'], 'time' => round(microtime(true) - $startTime, 3) * 1000)), self::LOG_TYPE_INFO); } catch (Exception $e) { $this->log(array('message' => $job . ' failed: ' . $e->getMessage(), 'data' => array('type' => 'fail', 'log' => $e->getMessage(), 'job_id' => $job->payload['id'], 'time' => round(microtime(true) - $startTime, 3) * 1000)), self::LOG_TYPE_ERROR); $job->fail($e); return; } $job->updateStatus(Resque_Job_Status::STATUS_COMPLETE); } /** * Attempt to find a job from the top of one of the queues for this worker. * * @return object|boolean Instance of Resque_Job if a job is found, false if not. */ public function reserve() { $queues = $this->queues(); if (!is_array($queues)) { return; } foreach ($queues as $queue) { $this->log(array('message' => 'Checking ' . $queue, 'data' => array('type' => 'check', 'queue' => $queue)), self::LOG_TYPE_DEBUG); $job = Resque_Job::reserve($queue); if ($job) { $this->log(array('message' => 'Found job on ' . $queue, 'data' => array('type' => 'found', 'queue' => $queue)), self::LOG_TYPE_DEBUG); return $job; } } return false; } /** * Return an array containing all of the queues that this worker should use * when searching for jobs. * * If * is found in the list of queues, every queue will be searched in * alphabetic order. (@see $fetch) * * @param boolean $fetch If true, and the queue is set to *, will fetch * all queue names from redis. * @return array Array of associated queues. */ public function queues($fetch = true) { if (!in_array('*', $this->queues) || $fetch == false) { return $this->queues; } $queues = Resque::queues(); sort($queues); return $queues; } /** * Attempt to fork a child process from the parent to run a job in. * * Return values are those of pcntl_fork(). * * @return int -1 if the fork failed, 0 for the forked child, the PID of the child for the parent. */ protected function fork() { if (!function_exists('pcntl_fork')) { return false; } $pid = pcntl_fork(); if ($pid === -1) { throw new RuntimeException('Unable to fork child worker.'); } return $pid; } /** * Perform necessary actions to start a worker. */ protected function startup() { $this->log(array('message' => 'Starting worker ' . $this, 'data' => array('type' => 'start', 'worker' => (string) $this)), self::LOG_TYPE_INFO); $this->registerSigHandlers(); $this->pruneDeadWorkers(); Resque_Event::trigger('beforeFirstFork', $this); $this->registerWorker(); } /** * On supported systems (with the PECL proctitle module installed), update * the name of the currently running process to indicate the current state * of a worker. * * @param string $status The updated process title. */ protected function updateProcLine($status) { if (function_exists('setproctitle')) { setproctitle('resque-' . Resque::VERSION . ': ' . $status); } } /** * Register signal handlers that a worker should respond to. * * TERM: Shutdown immediately and stop processing jobs. * INT: Shutdown immediately and stop processing jobs. * QUIT: Shutdown after the current job finishes processing. * USR1: Kill the forked child immediately and continue processing jobs. */ protected function registerSigHandlers() { if (!function_exists('pcntl_signal')) { $this->log(array('message' => 'Signals handling is unsupported', 'data' => array('type' => 'signal')), self::LOG_TYPE_WARNING); return; } declare(ticks = 1); pcntl_signal(SIGTERM, array($this, 'shutDownNow')); pcntl_signal(SIGINT, array($this, 'shutDownNow')); pcntl_signal(SIGQUIT, array($this, 'shutdown')); pcntl_signal(SIGUSR1, array($this, 'killChild')); pcntl_signal(SIGUSR2, array($this, 'pauseProcessing')); pcntl_signal(SIGCONT, array($this, 'unPauseProcessing')); pcntl_signal(SIGPIPE, array($this, 'reestablishRedisConnection')); $this->log(array('message' => 'Registered signals', 'data' => array('type' => 'signal')), self::LOG_TYPE_DEBUG); } /** * Signal handler callback for USR2, pauses processing of new jobs. */ public function pauseProcessing() { $this->log(array('message' => 'USR2 received; pausing job processing', 'data' => array('type' => 'pause')), self::LOG_TYPE_INFO); $this->paused = true; } /** * Signal handler callback for CONT, resumes worker allowing it to pick * up new jobs. */ public function unPauseProcessing() { $this->log(array('message' => 'CONT received; resuming job processing', 'data' => array('type' => 'resume')), self::LOG_TYPE_INFO); $this->paused = false; } /** * Signal handler for SIGPIPE, in the event the redis connection has gone away. * Attempts to reconnect to redis, or raises an Exception. */ public function reestablishRedisConnection() { $this->log(array('message' => 'SIGPIPE received; attempting to reconnect', 'data' => array('type' => 'reconnect')), self::LOG_TYPE_INFO); Resque::redis()->establishConnection(); } /** * Schedule a worker for shutdown. Will finish processing the current job * and when the timeout interval is reached, the worker will shut down. */ public function shutdown() { $this->shutdown = true; $this->log(array('message' => 'Exiting...', 'data' => array('type' => 'shutdown')), self::LOG_TYPE_INFO); } /** * Force an immediate shutdown of the worker, killing any child jobs * currently running. */ public function shutdownNow() { $this->shutdown(); $this->killChild(); } /** * Kill a forked child job immediately. The job it is processing will not * be completed. */ public function killChild() { if (!$this->child) { $this->log(array('message' => 'No child to kill.', 'data' => array('type' => 'kill', 'child' => null)), self::LOG_TYPE_DEBUG); return; } $this->log(array('message' => 'Killing child at ' . $this->child, 'data' => array('type' => 'kill', 'child' => $this->child)), self::LOG_TYPE_DEBUG); if (exec('ps -o pid,state -p ' . $this->child, $output, $returnCode) && $returnCode != 1) { $this->log(array('message' => 'Killing child at ' . $this->child, 'data' => array('type' => 'kill', 'child' => $this->child)), self::LOG_TYPE_DEBUG); posix_kill($this->child, SIGKILL); $this->child = null; } else { $this->log(array('message' => 'Child ' . $this->child . ' not found, restarting.', 'data' => array('type' => 'kill', 'child' => $this->child)), self::LOG_TYPE_ERROR); $this->shutdown(); } } /** * Look for any workers which should be running on this server and if * they're not, remove them from Redis. * * This is a form of garbage collection to handle cases where the * server may have been killed and the Resque workers did not die gracefully * and therefore leave state information in Redis. */ public function pruneDeadWorkers() { $workerPids = $this->workerPids(); $workers = self::all(); foreach ($workers as $worker) { if (is_object($worker)) { list($host, $pid, $queues) = explode(':', (string)$worker, 3); if ($host != $this->hostname || in_array($pid, $workerPids) || $pid == getmypid()) { continue; } $this->log(array('message' => 'Pruning dead worker: ' . (string)$worker, 'data' => array('type' => 'prune')), self::LOG_TYPE_DEBUG); $worker->unregisterWorker(); } } } /** * Return an array of process IDs for all of the Resque workers currently * running on this machine. * * @return array Array of Resque worker process IDs. */ public function workerPids() { $pids = array(); exec('ps -A -o pid,comm | grep [r]esque', $cmdOutput); foreach ($cmdOutput as $line) { list($pids[]) = explode(' ', trim($line), 2); } return $pids; } /** * Register this worker in Redis. */ public function registerWorker() { Resque::redis()->sadd('workers', (string)$this); Resque::redis()->set('worker:' . (string)$this . ':started', strftime('%a %b %d %H:%M:%S %Z %Y')); } /** * Unregister this worker in Redis. (shutdown etc) */ public function unregisterWorker() { if (is_object($this->currentJob)) { $this->currentJob->fail(new Resque_Job_DirtyExitException); } $id = (string)$this; Resque::redis()->srem('workers', $id); Resque::redis()->del('worker:' . $id); Resque::redis()->del('worker:' . $id . ':started'); Resque_Stat::clear('processed:' . $id); Resque_Stat::clear('failed:' . $id); Resque::redis()->hdel('workerLogger', $id); } /** * Tell Redis which job we're currently working on. * * @param object $job Resque_Job instance containing the job we're working on. */ public function workingOn(Resque_Job $job) { $job->worker = $this; $this->currentJob = $job; $job->updateStatus(Resque_Job_Status::STATUS_RUNNING); $data = json_encode( array( 'queue' => $job->queue, 'run_at' => strftime('%a %b %d %H:%M:%S %Z %Y'), 'payload' => $job->payload ) ); Resque::redis()->set('worker:' . $job->worker, $data); } /** * Notify Redis that we've finished working on a job, clearing the working * state and incrementing the job stats. */ public function doneWorking() { $this->currentJob = null; Resque_Stat::incr('processed'); Resque_Stat::incr('processed:' . (string)$this); Resque::redis()->del('worker:' . (string)$this); } /** * Generate a string representation of this worker. * * @return string String identifier for this worker instance. */ public function __toString() { return $this->id; } /** * Output a given log message to STDOUT. * * @param string $message Message to output. * @return boolean True if the message is logged */ public function log($message, $code = self::LOG_TYPE_INFO) { if ($this->logLevel === self::LOG_NONE) { return false; } /*if ($this->logger === null) { if ($this->logLevel === self::LOG_NORMAL && $code !== self::LOG_TYPE_DEBUG) { fwrite($this->logOutput, "*** " . $message['message'] . "\n"); } else if ($this->logLevel === self::LOG_VERBOSE) { fwrite($this->logOutput, "** [" . strftime('%T %Y-%m-%d') . "] " . $message['message'] . "\n"); } else { return false; } return true; } else {*/ $extra = array(); if (is_array($message)) { $extra = $message['data']; $message = $message['message']; } if (!isset($extra['worker'])) { if ($this->child > 0) { $extra['worker'] = $this->hostname . ':' . getmypid(); } else { list($host, $pid, $queues) = explode(':', (string) $this, 3); $extra['worker'] = $host . ':' . $pid; } } if (($this->logLevel === self::LOG_NORMAL || $this->logLevel === self::LOG_VERBOSE) && $code !== self::LOG_TYPE_DEBUG) { if ($this->logger === null) { fwrite($this->logOutput, "[" . date('c') . "] " . $message . "\n"); } else { switch ($code) { case self::LOG_TYPE_INFO: $this->logger->addInfo($message, $extra); break; case self::LOG_TYPE_WARNING: $this->logger->addWarning($message, $extra); break; case self::LOG_TYPE_ERROR: $this->logger->addError($message, $extra); break; case self::LOG_TYPE_CRITICAL: $this->logger->addCritical($message, $extra); break; case self::LOG_TYPE_ALERT: $this->logger->addAlert($message, $extra); } } } else if ($code === self::LOG_TYPE_DEBUG && $this->logLevel === self::LOG_VERBOSE) { if ($this->logger === null) { fwrite($this->logOutput, "[" . date('c') . "] " . $message . "\n"); } else { $this->logger->addDebug($message, $extra); } } else { return false; } return true; //} } public function registerLogger($logger = null) { $this->logger = $logger->getInstance(); Resque::redis()->hset('workerLogger', (string)$this, json_encode(array($logger->handler, $logger->target))); } public function getLogger($workerId) { $settings = json_decode(Resque::redis()->hget('workerLogger', (string)$workerId)); $logger = new MonologInit\MonologInit($settings[0], $settings[1]); return $logger->getInstance(); } /** * Return an object describing the job this worker is currently working on. * * @return object Object with details of current job. */ public function job() { $job = Resque::redis()->get('worker:' . $this); if (!$job) { return array(); } else { return json_decode($job, true); } } /** * Get a statistic belonging to this worker. * * @param string $stat Statistic to fetch. * @return int Statistic value. */ public function getStat($stat) { return Resque_Stat::get($stat . ':' . $this); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/RedisCluster.php
lib/Resque/RedisCluster.php
<?php // Third- party apps may have already loaded Resident from elsewhere // so lets be careful. if(!class_exists('RedisentCluster', false)) { require_once dirname(__FILE__) . '/../Redisent/RedisentCluster.php'; } /** * Extended Redisent class used by Resque for all communication with * redis. Essentially adds namespace support to Redisent. * * @package Resque/Redis * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_RedisCluster extends RedisentCluster { /** * Redis namespace * @var string */ private static $defaultNamespace = 'resque:'; /** * @var array List of all commands in Redis that supply a key as their * first argument. Used to prefix keys with the Resque namespace. */ private $keyCommands = array( 'exists', 'del', 'type', 'keys', 'expire', 'ttl', 'move', 'set', 'get', 'getset', 'setnx', 'incr', 'incrby', 'decrby', 'decrby', 'rpush', 'lpush', 'llen', 'lrange', 'ltrim', 'lindex', 'lset', 'lrem', 'lpop', 'rpop', 'sadd', 'srem', 'spop', 'scard', 'sismember', 'smembers', 'srandmember', 'zadd', 'zrem', 'zrange', 'zrevrange', 'zrangebyscore', 'zcard', 'zscore', 'zremrangebyscore', 'sort' ); // sinterstore // sunion // sunionstore // sdiff // sdiffstore // sinter // smove // rename // rpoplpush // mget // msetnx // mset // renamenx /** * Set Redis namespace (prefix) default: resque * @param string $namespace */ public static function prefix($namespace) { if (strpos($namespace, ':') === false) { $namespace .= ':'; } self::$defaultNamespace = $namespace; } /** * Magic method to handle all function requests and prefix key based * operations with the '{self::$defaultNamespace}' key prefix. * * @param string $name The name of the method called. * @param array $args Array of supplied arguments to the method. * @return mixed Return value from Resident::call() based on the command. */ public function __call($name, $args) { $args = func_get_args(); if(in_array($name, $this->keyCommands)) { $args[1][0] = self::$defaultNamespace . $args[1][0]; } try { return parent::__call($name, $args[1]); } catch(RedisException $e) { return false; } } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Failure/Redis.php
lib/Resque/Failure/Redis.php
<?php /** * Redis backend for storing failed Resque jobs. * * @package Resque/Failure * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Failure_Redis implements Resque_Failure_Interface { /** * Initialize a failed job class and save it (where appropriate). * * @param object $payload Object containing details of the failed job. * @param object $exception Instance of the exception that was thrown by the failed job. * @param object $worker Instance of Resque_Worker that received the job. * @param string $queue The name of the queue the job was fetched from. */ public function __construct($payload, $exception, $worker, $queue) { $data = array(); $data['failed_at'] = strftime('%a %b %d %H:%M:%S %Z %Y'); $data['payload'] = $payload; $data['exception'] = get_class($exception); $data['error'] = $exception->getMessage(); $data['backtrace'] = explode("\n", $exception->getTraceAsString()); $data['worker'] = (string)$worker; $data['queue'] = $queue; Resque::Redis()->setex('failed:'.$payload['id'], 3600*14, serialize($data)); } static public function get($jobId) { $data = Resque::Redis()->get('failed:' . $jobId); return unserialize($data); } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Failure/Interface.php
lib/Resque/Failure/Interface.php
<?php /** * Interface that all failure backends should implement. * * @package Resque/Failure * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ interface Resque_Failure_Interface { /** * Initialize a failed job class and save it (where appropriate). * * @param object $payload Object containing details of the failed job. * @param object $exception Instance of the exception that was thrown by the failed job. * @param object $worker Instance of Resque_Worker that received the job. * @param string $queue The name of the queue the job was fetched from. */ public function __construct($payload, $exception, $worker, $queue); /** * Return details about a failed jobs * @param string job Id * @return object Object containing details of the failed job. */ static public function get($jobId); } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Job/DirtyExitException.php
lib/Resque/Job/DirtyExitException.php
<?php /** * Runtime exception class for a job that does not exit cleanly. * * @package Resque/Job * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Job_DirtyExitException extends RuntimeException { }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Job/Status.php
lib/Resque/Job/Status.php
<?php /** * Status tracker/information for a job. * * @package Resque/Job * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Job_Status { const STATUS_WAITING = 1; const STATUS_RUNNING = 2; const STATUS_FAILED = 3; const STATUS_COMPLETE = 4; /** * @var string The ID of the job this status class refers back to. */ private $id; /** * @var mixed Cache variable if the status of this job is being monitored or not. * True/false when checked at least once or null if not checked yet. */ private $isTracking = null; /** * @var array Array of statuses that are considered final/complete. */ private static $completeStatuses = array( self::STATUS_FAILED, self::STATUS_COMPLETE ); /** * Setup a new instance of the job monitor class for the supplied job ID. * * @param string $id The ID of the job to manage the status for. */ public function __construct($id) { $this->id = $id; } /** * Create a new status monitor item for the supplied job ID. Will create * all necessary keys in Redis to monitor the status of a job. * * @param string $id The ID of the job to monitor the status of. */ public static function create($id, $status = self::STATUS_WAITING) { $statusPacket = array( 'status' => $status, 'updated' => time(), 'started' => time(), ); Resque::redis()->set('job:' . $id . ':status', json_encode($statusPacket)); } /** * Check if we're actually checking the status of the loaded job status * instance. * * @return boolean True if the status is being monitored, false if not. */ public function isTracking() { if($this->isTracking === false) { return false; } if(!Resque::redis()->exists((string)$this)) { $this->isTracking = false; return false; } $this->isTracking = true; return true; } /** * Update the status indicator for the current job with a new status. * * @param int The status of the job (see constants in Resque_Job_Status) */ public function update($status) { if(!$this->isTracking()) { return; } $statusPacket = array( 'status' => $status, 'updated' => time(), ); Resque::redis()->set((string)$this, json_encode($statusPacket)); // Expire the status for completed jobs after 24 hours if(in_array($status, self::$completeStatuses)) { Resque::redis()->expire((string)$this, 86400); } } /** * Fetch the status for the job being monitored. * * @return mixed False if the status is not being monitored, otherwise the status as * as an integer, based on the Resque_Job_Status constants. */ public function get() { if(!$this->isTracking()) { return false; } $statusPacket = json_decode(Resque::redis()->get((string)$this), true); if(!$statusPacket) { return false; } return $statusPacket['status']; } /** * Stop tracking the status of a job. */ public function stop() { Resque::redis()->del((string)$this); } /** * Generate a string representation of this object. * * @return string String representation of the current job status class. */ public function __toString() { return 'job:' . $this->id . ':status'; } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Resque/Job/DontPerform.php
lib/Resque/Job/DontPerform.php
<?php /** * Exception to be thrown if a job should not be performed/run. * * @package Resque/Job * @author Chris Boulton <chris@bigcommerce.com> * @license http://www.opensource.org/licenses/mit-license.php */ class Resque_Job_DontPerform extends Exception { }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Redisent/Redisent.php
lib/Redisent/Redisent.php
<?php /** * Redisent, a Redis interface for the modest * @author Justin Poliey <jdp34@njit.edu> * @copyright 2009 Justin Poliey <jdp34@njit.edu> * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @package Redisent */ define('CRLF', sprintf('%s%s', chr(13), chr(10))); /** * Wraps native Redis errors in friendlier PHP exceptions * Only declared if class doesn't already exist to ensure compatibility with php-redis */ if (! class_exists('RedisException', false)) { class RedisException extends Exception { } } /** * Redisent, a Redis interface for the modest among us */ class Redisent { /** * Socket connection to the Redis server * @var resource * @access private */ private $__sock; /** * Host of the Redis server * @var string * @access public */ public $host; /** * Port on which the Redis server is running * @var integer * @access public */ public $port; /** * Creates a Redisent connection to the Redis server on host {@link $host} and port {@link $port}. * @param string $host The hostname of the Redis server * @param integer $port The port number of the Redis server */ function __construct($host, $port = 6379) { $this->host = $host; $this->port = $port; $this->establishConnection(); } function establishConnection() { $this->__sock = fsockopen($this->host, $this->port, $errno, $errstr); if (!$this->__sock) { throw new Exception("{$errno} - {$errstr}"); } } function __destruct() { fclose($this->__sock); } function __call($name, $args) { /* Build the Redis unified protocol command */ array_unshift($args, strtoupper($name)); $command = sprintf('*%d%s%s%s', count($args), CRLF, implode(array_map(array($this, 'formatArgument'), $args), CRLF), CRLF); /* Open a Redis connection and execute the command */ for ($written = 0; $written < strlen($command); $written += $fwrite) { $fwrite = fwrite($this->__sock, substr($command, $written)); if ($fwrite === FALSE) { throw new Exception('Failed to write entire command to stream'); } } /* Parse the response based on the reply identifier */ $reply = trim(fgets($this->__sock, 512)); switch (substr($reply, 0, 1)) { /* Error reply */ case '-': throw new RedisException(substr(trim($reply), 4)); break; /* Inline reply */ case '+': $response = substr(trim($reply), 1); break; /* Bulk reply */ case '$': $response = null; if ($reply == '$-1') { break; } $read = 0; $size = substr($reply, 1); do { $block_size = ($size - $read) > 1024 ? 1024 : ($size - $read); $response .= fread($this->__sock, $block_size); $read += $block_size; } while ($read < $size); fread($this->__sock, 2); /* discard crlf */ break; /* Multi-bulk reply */ case '*': $count = substr($reply, 1); if ($count == '-1') { return null; } $response = array(); for ($i = 0; $i < $count; $i++) { $bulk_head = trim(fgets($this->__sock, 512)); $size = substr($bulk_head, 1); if ($size == '-1') { $response[] = null; } else { $read = 0; $block = ""; do { $block_size = ($size - $read) > 1024 ? 1024 : ($size - $read); $block .= fread($this->__sock, $block_size); $read += $block_size; } while ($read < $size); fread($this->__sock, 2); /* discard crlf */ $response[] = $block; } } break; /* Integer reply */ case ':': $response = intval(substr(trim($reply), 1)); break; default: throw new RedisException("invalid server response: {$reply}"); break; } /* Party on */ return $response; } private function formatArgument($arg) { if (is_array($arg)) { $arg = implode(' ', $arg); } return sprintf('$%d%s%s', strlen($arg), CRLF, $arg); } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/lib/Redisent/RedisentCluster.php
lib/Redisent/RedisentCluster.php
<?php /** * Redisent, a Redis interface for the modest * @author Justin Poliey <jdp34@njit.edu> * @copyright 2009 Justin Poliey <jdp34@njit.edu> * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @package Redisent */ require_once dirname(__FILE__) . '/Redisent.php'; /** * A generalized Redisent interface for a cluster of Redis servers */ class RedisentCluster { /** * Collection of Redisent objects attached to Redis servers * @var array * @access private */ private $redisents; /** * Aliases of Redisent objects attached to Redis servers, used to route commands to specific servers * @see RedisentCluster::to * @var array * @access private */ private $aliases; /** * Hash ring of Redis server nodes * @var array * @access private */ private $ring; /** * Individual nodes of pointers to Redis servers on the hash ring * @var array * @access private */ private $nodes; /** * Number of replicas of each node to make around the hash ring * @var integer * @access private */ private $replicas = 128; /** * The commands that are not subject to hashing * @var array * @access private */ private $dont_hash = array( 'RANDOMKEY', 'DBSIZE', 'SELECT', 'MOVE', 'FLUSHDB', 'FLUSHALL', 'SAVE', 'BGSAVE', 'LASTSAVE', 'SHUTDOWN', 'INFO', 'MONITOR', 'SLAVEOF' ); /** * Creates a Redisent interface to a cluster of Redis servers * @param array $servers The Redis servers in the cluster. Each server should be in the format array('host' => hostname, 'port' => port) */ function __construct($servers) { $this->ring = array(); $this->aliases = array(); foreach ($servers as $alias => $server) { $this->redisents[] = new Redisent($server['host'], $server['port']); if (is_string($alias)) { $this->aliases[$alias] = $this->redisents[count($this->redisents)-1]; } for ($replica = 1; $replica <= $this->replicas; $replica++) { $this->ring[crc32($server['host'].':'.$server['port'].'-'.$replica)] = $this->redisents[count($this->redisents)-1]; } } ksort($this->ring, SORT_NUMERIC); $this->nodes = array_keys($this->ring); } /** * Routes a command to a specific Redis server aliased by {$alias}. * @param string $alias The alias of the Redis server * @return Redisent The Redisent object attached to the Redis server */ function to($alias) { if (isset($this->aliases[$alias])) { return $this->aliases[$alias]; } else { throw new Exception("That Redisent alias does not exist"); } } /* Execute a Redis command on the cluster */ function __call($name, $args) { /* Pick a server node to send the command to */ $name = strtoupper($name); if (!in_array($name, $this->dont_hash)) { $node = $this->nextNode(crc32($args[0])); $redisent = $this->ring[$node]; } else { $redisent = $this->redisents[0]; } /* Execute the command on the server */ return call_user_func_array(array($redisent, $name), $args); } /** * Routes to the proper server node * @param integer $needle The hash value of the Redis command * @return Redisent The Redisent object associated with the hash */ private function nextNode($needle) { $haystack = $this->nodes; while (count($haystack) > 2) { $try = floor(count($haystack) / 2); if ($haystack[$try] == $needle) { return $needle; } if ($needle < $haystack[$try]) { $haystack = array_slice($haystack, 0, $try + 1); } if ($needle > $haystack[$try]) { $haystack = array_slice($haystack, $try + 1); } } return $haystack[count($haystack)-1]; } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/extras/sample-plugin.php
extras/sample-plugin.php
<?php // Somewhere in our application, we need to register: Resque_Event::listen('afterEnqueue', array('My_Resque_Plugin', 'afterEnqueue')); Resque_Event::listen('beforeFirstFork', array('My_Resque_Plugin', 'beforeFirstFork')); Resque_Event::listen('beforeFork', array('My_Resque_Plugin', 'beforeFork')); Resque_Event::listen('afterFork', array('My_Resque_Plugin', 'afterFork')); Resque_Event::listen('beforePerform', array('My_Resque_Plugin', 'beforePerform')); Resque_Event::listen('afterPerform', array('My_Resque_Plugin', 'afterPerform')); Resque_Event::listen('onFailure', array('My_Resque_Plugin', 'onFailure')); class My_Resque_Plugin { public static function afterEnqueue($class, $arguments) { echo "Job was queued for " . $class . ". Arguments:"; print_r($arguments); } public static function beforeFirstFork($worker) { echo "Worker started. Listening on queues: " . implode(', ', $worker->queues(false)) . "\n"; } public static function beforeFork($job) { echo "Just about to fork to run " . $job; } public static function afterFork($job) { echo "Forked to run " . $job . ". This is the child process.\n"; } public static function beforePerform($job) { echo "Cancelling " . $job . "\n"; // throw new Resque_Job_DontPerform; } public static function afterPerform($job) { echo "Just performed " . $job . "\n"; } public static function onFailure($exception, $job) { echo $job . " threw an exception:\n" . $exception; } }
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/bad_job.php
demo/bad_job.php
<?php class Bad_PHP_Job { public function perform() { throw new Exception('Unable to run this job!'); } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/check_status.php
demo/check_status.php
<?php if(empty($argv[1])) { die('Specify the ID of a job to monitor the status of.'); } require '../lib/Resque/Job/Status.php'; require '../lib/Resque.php'; date_default_timezone_set('GMT'); Resque::setBackend('127.0.0.1:6379'); $status = new Resque_Job_Status($argv[1]); if(!$status->isTracking()) { die("Resque is not tracking the status of this job.\n"); } echo "Tracking status of ".$argv[1].". Press [break] to stop.\n\n"; while(true) { fwrite(STDOUT, "Status of ".$argv[1]." is: ".$status->get()."\n"); sleep(1); } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/queue.php
demo/queue.php
<?php if(empty($argv[1])) { die('Specify the name of a job to add. e.g, php queue.php PHP_Job'); } require '../lib/Resque.php'; date_default_timezone_set('GMT'); Resque::setBackend('127.0.0.1:6379'); $args = array( 'time' => time(), 'array' => array( 'test' => 'test', ), ); $jobId = Resque::enqueue('default', $argv[1], $args, true); echo "Queued job ".$jobId."\n\n"; ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/php_error_job.php
demo/php_error_job.php
<?php class PHP_Error_Job { public function perform() { callToUndefinedFunction(); } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/long_job.php
demo/long_job.php
<?php class Long_PHP_Job { public function perform() { sleep(600); } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/job.php
demo/job.php
<?php class PHP_Job { public function perform() { sleep(120); fwrite(STDOUT, 'Hello!'); } } ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
wa0x6e/php-resque-ex
https://github.com/wa0x6e/php-resque-ex/blob/e024280dae4d7cfe5bae1c34a993f4d82087e28c/demo/resque.php
demo/resque.php
<?php date_default_timezone_set('GMT'); require 'bad_job.php'; require 'job.php'; require 'php_error_job.php'; require '../bin/resque'; ?>
php
MIT
e024280dae4d7cfe5bae1c34a993f4d82087e28c
2026-01-05T04:53:25.889096Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/routing.php
routing.php
<?php declare(strict_types=1); require_once __DIR__."/src/bootstrap.php"; use AugmentedSteam\Server\Environment\Container; use AugmentedSteam\Server\Routing\Router; $container = Container::getInstance(); (new Router())->route($container);
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/job.php
src/job.php
<?php use AugmentedSteam\Server\Cron\CronJobFactory; use AugmentedSteam\Server\Environment\Container; require_once __DIR__."/bootstrap.php"; /** @var string[] $argv */ $container = Container::getInstance(); (new CronJobFactory($container)) ->getJob(...array_slice($argv, 1)) ->execute();
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false