Files
xxx/tests/php/Support/FakeRecaptcha.php
2026-09-26 15:27:51 +02:00

69 lines
2.1 KiB
PHP

<?php
namespace Xxx\Tests\Support;
/*
* A stream wrapper that takes the place of https:// while it is
* installed, so that captcha_verify_response() talks to this class
* instead of Google. It records each request (the URL, the HTTP context
* options and the decoded POST body) and returns $reply: a string, FALSE
* for "server not reachable", or a Closure that gets the POST fields and
* returns one of these.
*/
class FakeRecaptcha {
public const PASS = '{"tokenProperties":{"valid":true,"hostname":"site.test","action":"submit"}}';
public static array $requests = array();
public static $reply = self::PASS;
private static bool $active = FALSE;
public $context;
private string $data = '';
private int $position = 0;
public static function install($reply = self::PASS): void {
self::$requests = array();
self::$reply = $reply;
if (!self::$active) {
stream_wrapper_unregister('https');
stream_wrapper_register('https', self::class);
self::$active = TRUE;
}
}
public static function uninstall(): void {
if (self::$active) {
stream_wrapper_restore('https');
self::$active = FALSE;
}
}
public function stream_open($path, $mode, $options, &$opened_path) {
$context = $this->context ? stream_context_get_options($this->context) : array();
$http = $context['http'] ?? array();
$post = json_decode((string)($http['content'] ?? ''), TRUE) ?? array();
self::$requests[] = array('url' => $path, 'http' => $http, 'post' => $post);
$reply = self::$reply instanceof \Closure ? (self::$reply)($post) : self::$reply;
if ($reply === FALSE)
return FALSE;
$this->data = (string)$reply;
return TRUE;
}
public function stream_read($count) {
$chunk = substr($this->data, $this->position, $count);
$this->position += strlen($chunk);
return $chunk;
}
public function stream_eof() {
return $this->position >= strlen($this->data);
}
public function stream_stat() {
return array('size' => strlen($this->data));
}
public function stream_set_option($option, $arg1, $arg2) {
return FALSE;
}
}