Drop refund handling, finalize captures via webhook, add profanity filter

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 10:20:53 -08:00
1 parent 35f5d1acfb
commit 2e3abf33d9
11 files changed
+420 -82

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Streamer-controlled word masker. Pure PHP (no WordPress calls), never throws.
*
* - Whole words only (so "Scunthorpe", "class", "assist" are never touched).
* - Case-insensitive, Unicode-safe (mb_* / PCRE /u).
* - Simple leetspeak: @ 4 -> a, 3 -> e, 1 ! -> i, 0 -> o, $ 5 -> s, 7 -> t.
* Leet mapping is only applied to tokens that contain at least one letter,
* so plain numbers such as "455" are left alone.
* - Each matched word is replaced by asterisks of the same character length.
*
* Settings keys read: profanity_filter, profanity_use_builtin, profanity_words.
*/
final class ProfanityFilter {
public const MAX_WORD_LENGTH = 40;
public const MAX_WORDS = 500;
public const MAX_RAW_BYTES = 20000;
public const MAX_INPUT_BYTES = 20000;
/** Deliberately short; the streamer adds the rest via profanity_words. */
public const BUILTIN = array(
'fuck', 'fucker', 'fucking', 'shit', 'bitch', 'asshole', 'cunt', 'dick', 'bastard',
'nigger', 'nigga', 'faggot', 'fag', 'retard', 'whore', 'slut',
);
private const LEET = array(
'@' => 'a', '4' => 'a', '3' => 'e', '1' => 'i', '!' => 'i',
'0' => 'o', '$' => 's', '5' => 's', '7' => 't',
);
private bool $enabled;
/** @var array<string,true> normalized word => true */
private array $words = array();
/** @param array $settings Settings::all()-shaped array (missing keys use defaults). */
public function __construct( array $settings ) {
$this->enabled = self::truthy( $settings['profanity_filter'] ?? true );
if ( ! $this->enabled ) {
return;
}
if ( self::truthy( $settings['profanity_use_builtin'] ?? true ) ) {
foreach ( self::BUILTIN as $w ) {
$this->words[ self::normalize( $w ) ] = true;
}
}
$raw = $settings['profanity_words'] ?? '';
foreach ( self::parseWords( is_string( $raw ) ? $raw : '' ) as $w ) {
$this->words[ self::normalize( $w ) ] = true;
}
}
public function isEnabled(): bool {
return $this->enabled && array() !== $this->words;
}
/** Mask every listed word; everything else is returned byte-for-byte (after UTF-8 scrubbing). */
public function filter( string $text ): string {
if ( ! $this->isEnabled() || '' === $text ) {
return $text;
}
try {
if ( strlen( $text ) > self::MAX_INPUT_BYTES ) {
$text = substr( $text, 0, self::MAX_INPUT_BYTES );
}
$text = mb_scrub( $text, 'UTF-8' );
$out = preg_replace_callback(
'/[\p{L}\p{M}\p{N}@$!]+/u',
function ( array $m ): string {
$tok = $m[0];
// "!" is only a leet char inside a word; trailing/leading punctuation is not part of it.
$core = trim( $tok, '!' );
if ( '' === $core || ! $this->isListed( $core ) ) {
return $tok;
}
$lead = (int) strspn( $tok, '!' );
$trail = strlen( $tok ) - strlen( rtrim( $tok, '!' ) );
return str_repeat( '!', $lead ) . str_repeat( '*', mb_strlen( $core ) ) . str_repeat( '!', $trail );
},
$text
);
return is_string( $out ) ? $out : $text;
} catch ( \Throwable $e ) {
return $text;
}
}
private function isListed( string $token ): bool {
return isset( $this->words[ self::normalize( $token ) ] );
}
/** Lowercase; apply leetspeak mapping only when the token contains a letter. */
private static function normalize( string $word ): string {
$lower = mb_strtolower( $word, 'UTF-8' );
if ( 1 !== preg_match( '/\p{L}/u', $lower ) ) {
return $lower;
}
return strtr( $lower, self::LEET );
}
/** @return string[] one word per line; blanks, #comments and multi-word lines ignored; capped. */
public static function parseWords( string $raw ): array {
if ( strlen( $raw ) > self::MAX_RAW_BYTES ) {
$raw = substr( $raw, 0, self::MAX_RAW_BYTES );
}
$raw = mb_scrub( $raw, 'UTF-8' );
$out = array();
$lines = preg_split( '/\R/u', $raw ) ?: array();
foreach ( $lines as $line ) {
$line = trim( $line );
if ( '' === $line || '#' === $line[0] || 1 === preg_match( '/\s/u', $line ) ) {
continue;
}
if ( mb_strlen( $line ) > self::MAX_WORD_LENGTH ) {
continue;
}
$out[ $line ] = $line;
if ( count( $out ) >= self::MAX_WORDS ) {
break;
}
}
return array_values( $out );
}
private static function truthy( mixed $v ): bool {
if ( is_string( $v ) ) {
return ! in_array( strtolower( trim( $v ) ), array( '', '0', 'false', 'off', 'no' ), true );
}
return (bool) $v;
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
use StreamGoals\Core\Money;
/**
* Pure decision logic shared by the capture endpoint and the COMPLETED webhook:
* a donation leaves "pending" only when PayPal reports a COMPLETED capture whose
* amount and currency match what we stored. Otherwise it stays pending until the
* webhook delivers a matching, finalized capture. The pending->completed
* transition is atomic (callable returns true for exactly one caller), so
* replays and races finalize at most once.
*/
final class CaptureFinalizer {
public const COMPLETED = 'completed'; // this call finalized the donation
public const DUPLICATE = 'duplicate'; // already finalized / not pending
public const PENDING = 'pending'; // capture looks off; donation left pending
/**
* @param object|array $row Donation row (status, total_minor, currency).
* @param callable $markCompleted fn(int $id, string $captureId): bool atomic pending->completed
* @param callable $notifyApplied fn(int $id): void
*/
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied ): string {
$r = (object) $row;
if ( 'pending' !== (string) $r->status ) {
return self::DUPLICATE;
}
if ( 'COMPLETED' !== $paypalStatus || '' === $captureId ) {
return self::PENDING;
}
if ( ! $amount || $amount->minor !== (int) $r->total_minor || $amount->currency !== (string) $r->currency ) {
return self::PENDING;
}
if ( $markCompleted( (int) $r->id, $captureId ) ) {
$notifyApplied( (int) $r->id );
return self::COMPLETED;
}
return self::DUPLICATE;
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ use StreamGoals\Core\Settings;
/** PayPal REST v1/v2 client. All HTTP goes through an injected HttpTransport. */
final class Client {
public const WEBHOOK_EVENTS = array( 'PAYMENT.CAPTURE.COMPLETED', 'PAYMENT.CAPTURE.REFUNDED', 'PAYMENT.CAPTURE.REVERSED' );
public const WEBHOOK_EVENTS = array( 'PAYMENT.CAPTURE.COMPLETED' );
public function __construct(
private HttpTransport $http,
-14
View File
@@ -84,25 +84,11 @@ final class DonationStore {
return 1 === $n;
}
/** Atomic completed -> refunded|reversed. */
public static function mark_reversed( int $id, string $status ): bool {
global $wpdb;
if ( ! in_array( $status, array( 'refunded', 'reversed' ), true ) ) {
return false;
}
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET status = %s WHERE id = %d AND status = 'completed'", $status, $id ) );
return 1 === $n;
}
/** Hand a freshly completed donation to the rules engine (if present). Never throws. */
public static function notify_applied( int $id ): void {
self::call_engine( 'applyDonation', $id );
}
public static function notify_reversed( int $id ): void {
self::call_engine( 'reverseDonation', $id );
}
private static function call_engine( string $method, int $id ): void {
$row = self::find( $id );
if ( ! $row ) {
+6
View File
@@ -5,6 +5,7 @@ namespace StreamGoals\PayPal;
use StreamGoals\Core\FeeCalculator;
use StreamGoals\Core\Money;
use StreamGoals\Core\ProfanityFilter;
/**
* Pure validation + total computation for a new donation order. The server is the
@@ -57,6 +58,11 @@ final class OrderValidator {
$name = ''; // never persist the name of an anonymous donor
}
// Mask profanity before anything is stored (same-length masking, so length checks above still hold).
$filter = new ProfanityFilter( $settings );
$name = $filter->filter( $name );
$message = $filter->filter( $message );
return array(
'goal_id' => (int) $goal['id'],
'currency' => $currency,
-9
View File
@@ -21,15 +21,6 @@ final class WebhookEvent {
$r = is_array( $event['resource'] ?? null ) ? $event['resource'] : array();
$type = (string) ( $event['event_type'] ?? '' );
$capId = (string) ( $r['id'] ?? '' );
// REFUNDED/REVERSED resources are refund objects whose "up" link points at the capture.
if ( 'PAYMENT.CAPTURE.COMPLETED' !== $type ) {
foreach ( (array) ( $r['links'] ?? array() ) as $l ) {
if ( is_array( $l ) && 'up' === ( $l['rel'] ?? '' ) && preg_match( '#/captures/([A-Za-z0-9\-_]+)$#', (string) ( $l['href'] ?? '' ), $m ) ) {
$capId = $m[1];
break;
}
}
}
$amount = null;
if ( isset( $r['amount']['value'], $r['amount']['currency_code'] ) ) {
try {
+12 -10
View File
@@ -5,6 +5,7 @@ namespace StreamGoals\Rest;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\OrderValidator;
@@ -112,18 +113,19 @@ final class DonateController {
return new \WP_Error( 'sg_paypal', __( 'The payment could not be completed. You have not been charged.', 'streamgoals-donate' ), array( 'status' => 502 ) );
}
if ( 'COMPLETED' !== $cap['status'] || '' === $cap['capture_id'] ) {
// e.g. PENDING (e-check/review). The COMPLETED webhook will finalize it.
$res = CaptureFinalizer::finalize(
$row,
(string) $cap['status'],
(string) $cap['capture_id'],
$cap['amount'],
array( DonationStore::class, 'mark_completed' ),
array( DonationStore::class, 'notify_applied' )
);
if ( CaptureFinalizer::PENDING === $res ) {
// PENDING capture (e-check/review) or amount mismatch: stay pending; the COMPLETED webhook finalizes it.
error_log( 'StreamGoals: capture for donation ' . $row->id . ' not finalized (status ' . $cap['status'] . '); awaiting webhook' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return new \WP_REST_Response( array( 'status' => 'processing' ), 202 );
}
$amt = $cap['amount'];
if ( ! $amt || $amt->minor !== (int) $row->total_minor || $amt->currency !== $row->currency ) {
error_log( 'StreamGoals: captured amount mismatch for donation ' . $row->id ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return new \WP_REST_Response( array( 'status' => 'processing' ), 202 );
}
if ( DonationStore::mark_completed( (int) $row->id, $cap['capture_id'] ) ) {
DonationStore::notify_applied( (int) $row->id );
}
return rest_ensure_response( array( 'status' => 'completed' ) );
}
+15 -36
View File
@@ -4,6 +4,7 @@ declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\WebhookEvent;
@@ -55,14 +56,10 @@ final class WebhookController {
return rest_ensure_response( array( 'result' => $result ) );
}
/** Only PAYMENT.CAPTURE.COMPLETED is acted on; every other event is acknowledged (200) so PayPal stops retrying. */
private static function process( WebhookEvent $ev ): string {
switch ( $ev->type ) {
case 'PAYMENT.CAPTURE.COMPLETED':
return self::completed( $ev );
case 'PAYMENT.CAPTURE.REFUNDED':
return self::reversed( $ev, 'refunded' );
case 'PAYMENT.CAPTURE.REVERSED':
return self::reversed( $ev, 'reversed' );
if ( 'PAYMENT.CAPTURE.COMPLETED' === $ev->type ) {
return self::completed( $ev );
}
return 'ignored';
}
@@ -86,36 +83,18 @@ final class WebhookController {
if ( ! $row || '' === $ev->captureId ) {
return 'ignored';
}
if ( 'pending' !== $row->status ) {
return 'duplicate'; // already completed via the capture endpoint (or refunded)
}
if ( ! $ev->amount || $ev->amount->minor !== (int) $row->total_minor || $ev->amount->currency !== $row->currency ) {
error_log( 'StreamGoals: webhook amount mismatch for donation ' . $row->id ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
$res = CaptureFinalizer::finalize(
$row,
'COMPLETED',
$ev->captureId,
$ev->amount,
array( DonationStore::class, 'mark_completed' ),
array( DonationStore::class, 'notify_applied' )
);
if ( CaptureFinalizer::PENDING === $res ) {
error_log( 'StreamGoals: webhook capture does not match donation ' . $row->id . '; left pending' ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return 'ignored';
}
if ( DonationStore::mark_completed( (int) $row->id, $ev->captureId ) ) {
DonationStore::notify_applied( (int) $row->id );
return 'completed';
}
return 'duplicate';
}
private static function reversed( WebhookEvent $ev, string $status ): string {
$row = self::locate( $ev );
if ( ! $row ) {
return 'ignored';
}
if ( 'completed' !== $row->status ) {
return 'duplicate';
}
// A partial refund does not undo the whole donation; only full refunds/reversals do.
if ( 'refunded' === $status && $ev->amount && $ev->amount->minor < (int) $row->total_minor ) {
return 'partial_refund_ignored';
}
if ( DonationStore::mark_reversed( (int) $row->id, $status ) ) {
DonationStore::notify_reversed( (int) $row->id );
return $status;
}
return 'duplicate';
return $res;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Money;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\WebhookEvent;
final class PayPalCaptureFinalizerTest extends TestCase {
/** In-memory donation with an atomic pending->completed transition. */
private function store( string $status = 'pending' ): object {
return new class( $status ) {
public array $row;
public int $applied = 0;
public function __construct( string $status ) {
$this->row = array( 'id' => 7, 'status' => $status, 'total_minor' => 500, 'currency' => 'USD', 'paypal_capture_id' => '' );
}
public function mark( int $id, string $cap ): bool {
if ( 'pending' !== $this->row['status'] ) {
return false;
}
$this->row['status'] = 'completed';
$this->row['paypal_capture_id'] = $cap;
return true;
}
public function notify( int $id ): void {
$this->applied++;
}
};
}
private function run_finalize( object $s, string $status, string $cap, ?Money $amt ): string {
return CaptureFinalizer::finalize( $s->row, $status, $cap, $amt, array( $s, 'mark' ), array( $s, 'notify' ) );
}
public function test_pending_capture_status_stays_pending(): void {
$s = $this->store();
$this->assertSame( 'pending', $this->run_finalize( $s, 'PENDING', 'CAP1', new Money( 500, 'USD' ) ) );
$this->assertSame( 'pending', $s->row['status'] );
$this->assertSame( 0, $s->applied );
}
public function test_amount_or_currency_mismatch_or_missing_id_stays_pending(): void {
foreach ( array( array( 'CAP1', new Money( 499, 'USD' ) ), array( 'CAP1', new Money( 500, 'EUR' ) ), array( 'CAP1', null ), array( '', new Money( 500, 'USD' ) ) ) as [ $cap, $amt ] ) {
$s = $this->store();
$this->assertSame( 'pending', $this->run_finalize( $s, 'COMPLETED', $cap, $amt ) );
$this->assertSame( 'pending', $s->row['status'] );
$this->assertSame( 0, $s->applied );
}
}
public function test_completed_webhook_finalizes_pending_donation_exactly_once(): void {
$s = $this->store();
// Capture endpoint saw PENDING first...
$this->assertSame( 'pending', $this->run_finalize( $s, 'PENDING', '', null ) );
// ...then the COMPLETED webhook arrives, and is replayed twice.
$ev = WebhookEvent::fromArray( array(
'id' => 'E1', 'event_type' => 'PAYMENT.CAPTURE.COMPLETED',
'resource' => array( 'id' => 'CAP1', 'custom_id' => '7', 'amount' => array( 'value' => '5.00', 'currency_code' => 'USD' ) ),
) );
$this->assertSame( 'completed', $this->run_finalize( $s, 'COMPLETED', $ev->captureId, $ev->amount ) );
$this->assertSame( 'duplicate', $this->run_finalize( $s, 'COMPLETED', $ev->captureId, $ev->amount ) );
$this->assertSame( 'duplicate', $this->run_finalize( $s, 'COMPLETED', $ev->captureId, $ev->amount ) );
$this->assertSame( 'completed', $s->row['status'] );
$this->assertSame( 'CAP1', $s->row['paypal_capture_id'] );
$this->assertSame( 1, $s->applied );
}
public function test_lost_race_does_not_apply_twice(): void {
$s = $this->store();
$lost = CaptureFinalizer::finalize( $s->row, 'COMPLETED', 'CAP1', new Money( 500, 'USD' ), static fn(): bool => false, array( $s, 'notify' ) );
$this->assertSame( 'duplicate', $lost );
$this->assertSame( 0, $s->applied );
}
public function test_non_pending_rows_are_never_touched(): void {
foreach ( array( 'completed', 'refunded', 'reversed' ) as $st ) {
$s = $this->store( $st );
$this->assertSame( 'duplicate', $this->run_finalize( $s, 'COMPLETED', 'CAP1', new Money( 500, 'USD' ) ) );
$this->assertSame( $st, $s->row['status'] );
$this->assertSame( 0, $s->applied );
}
}
public function test_refund_events_are_not_registered_or_parsed_specially(): void {
$this->assertSame( array( 'PAYMENT.CAPTURE.COMPLETED' ), \StreamGoals\PayPal\Client::WEBHOOK_EVENTS );
$ev = WebhookEvent::fromArray( array( 'id' => 'E2', 'event_type' => 'PAYMENT.CAPTURE.REFUNDED', 'resource' => array( 'id' => 'REF1' ) ) );
$this->assertSame( 'PAYMENT.CAPTURE.REFUNDED', $ev->type ); // controller returns 'ignored' (HTTP 200) for it
}
}
+2 -12
View File
@@ -160,13 +160,13 @@ final class PayPalClientTest extends TestCase {
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
}
public function test_create_webhook_registers_three_events(): void {
public function test_create_webhook_registers_only_completed_event(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'WH77' ) ) );
$this->assertSame( 'WH77', $c->createWebhook( 'https://x.test/wp-json/streamgoals/v1/webhook' ) );
$body = json_decode( $this->http->calls[1]['body'], true );
$names = array_column( $body['event_types'], 'name' );
$this->assertSame( array( 'PAYMENT.CAPTURE.COMPLETED', 'PAYMENT.CAPTURE.REFUNDED', 'PAYMENT.CAPTURE.REVERSED' ), $names );
$this->assertSame( array( 'PAYMENT.CAPTURE.COMPLETED' ), $names );
}
public function test_test_connection_messages(): void {
@@ -197,15 +197,5 @@ final class PayPalClientTest extends TestCase {
$this->assertSame( '7', $done->customId );
$this->assertSame( 'ORD', $done->orderId );
$this->assertSame( 500, $done->amount->minor );
$ref = WebhookEvent::fromArray( array(
'id' => 'E2', 'event_type' => 'PAYMENT.CAPTURE.REFUNDED',
'resource' => array( 'id' => 'REF1', 'links' => array(
array( 'rel' => 'self', 'href' => 'https://api/v2/payments/refunds/REF1' ),
array( 'rel' => 'up', 'href' => 'https://api/v2/payments/captures/CAP1' ),
) ),
) );
$this->assertSame( 'CAP1', $ref->captureId );
$this->assertNull( $ref->amount );
}
}
+112
View File
@@ -0,0 +1,112 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\ProfanityFilter;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\Core\FeeCalculator;
final class ProfanityFilterTest extends TestCase {
private function f( array $o = array() ): ProfanityFilter {
return new ProfanityFilter( array_merge( Settings::defaults(), $o ) );
}
public function test_builtin_masks_with_equal_length_case_insensitive(): void {
$this->assertSame( 'what the **** is this', $this->f()->filter( 'what the shit is this' ) );
$this->assertSame( 'what the **** is this', $this->f()->filter( 'what the SHiT is this' ) );
}
public function test_whole_word_only_scunthorpe(): void {
$f = $this->f( array( 'profanity_words' => "ass\ncock" ) );
foreach ( array( 'Scunthorpe', 'class', 'assist', 'Cockburn', 'bassist', 'passage', 'shitake' ) as $w ) {
$this->assertSame( $w, $f->filter( $w ), $w );
}
$this->assertSame( 'a *** b', $f->filter( 'a ass b' ) );
$this->assertSame( '***, ***!', $f->filter( 'ass, ass!' ) );
}
public function test_leetspeak(): void {
$f = $this->f();
$this->assertSame( '****', $f->filter( 'sh1t' ) );
$this->assertSame( '****', $f->filter( '$h!t' ) );
$f2 = $this->f( array( 'profanity_words' => 'bad' ) );
$this->assertSame( '***', $f2->filter( 'b@d' ) );
$this->assertSame( '***', $f2->filter( 'B4D' ) );
$f3 = $this->f( array( 'profanity_words' => 'fool' ) );
$this->assertSame( '****', $f3->filter( 'f00l' ) );
}
public function test_pure_numbers_and_trailing_punctuation_untouched(): void {
$f = $this->f( array( 'profanity_words' => "ass\nsose" ) );
$this->assertSame( '455 and 5053', $f->filter( '455 and 5053' ) ); // "ass"/"sose" via leet, but no letters
$this->assertSame( 'wow! great!!', $f->filter( 'wow! great!!' ) );
$this->assertSame( 'hello!! ***!!', $f->filter( 'hello!! ass!!' ) );
}
public function test_unicode(): void {
$f = $this->f( array( 'profanity_words' => "scheiße\nмат\nÄRGER" ) );
$this->assertSame( 'oh ******* no', $f->filter( 'oh Scheiße no' ) );
$this->assertSame( 'это ***', $f->filter( 'это МАТ' ) );
$this->assertSame( '*****!', $f->filter( 'ärger!' ) );
$this->assertSame( 'матрос', $f->filter( 'матрос' ) );
$this->assertSame( '😀 *** 😀', $f->filter( '😀 мат 😀' ) );
}
public function test_streamer_words_parsing(): void {
$raw = "# comment\n\n foo \r\nBAR\n#baz\ntwo words\n" . str_repeat( 'x', 41 ) . "\nfoo\n";
$this->assertSame( array( 'foo', 'BAR' ), ProfanityFilter::parseWords( $raw ) );
$f = $this->f( array( 'profanity_use_builtin' => false, 'profanity_words' => $raw ) );
$this->assertSame( '*** *** baz words', $f->filter( 'foo bar baz words' ) );
}
public function test_word_count_cap(): void {
$raw = implode( "\n", array_map( static fn( $i ) => 'w' . $i, range( 1, 2000 ) ) );
$this->assertLessThanOrEqual( ProfanityFilter::MAX_WORDS, count( ProfanityFilter::parseWords( $raw ) ) );
}
public function test_empty_list_and_builtin_off(): void {
$f = $this->f( array( 'profanity_use_builtin' => false, 'profanity_words' => '' ) );
$this->assertFalse( $f->isEnabled() );
$this->assertSame( 'shit happens', $f->filter( 'shit happens' ) );
$f = $this->f( array( 'profanity_use_builtin' => false, 'profanity_words' => 'zzz' ) );
$this->assertSame( 'shit ***', $f->filter( 'shit zzz' ) );
}
public function test_master_switch_off(): void {
$f = $this->f( array( 'profanity_filter' => false, 'profanity_words' => 'foo' ) );
$this->assertSame( 'shit foo', $f->filter( 'shit foo' ) );
$f = $this->f( array( 'profanity_filter' => '0' ) );
$this->assertSame( 'shit', $f->filter( 'shit' ) );
}
public function test_never_throws_on_odd_input(): void {
$f = $this->f();
$this->assertSame( '', $f->filter( '' ) );
$bad = "ok \xC3\x28 shit \xFF";
$out = $f->filter( $bad );
$this->assertIsString( $out );
$this->assertStringContainsString( '****', $out );
$this->assertIsString( $f->filter( str_repeat( 'a', 100000 ) ) );
$this->assertSame( '\\ $ @ ! ? ^ (', $f->filter( '\\ $ @ ! ? ^ (' ) );
$weird = new ProfanityFilter( array( 'profanity_words' => array( 'x' ), 'profanity_filter' => null ) );
$this->assertIsString( $weird->filter( 'x' ) );
$this->assertIsString( ( new ProfanityFilter( array() ) )->filter( 'shit' ) );
}
public function test_validator_filters_name_and_message_before_storing(): void {
$goal = array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
$s = array_merge( Settings::defaults(), array( 'profanity_words' => 'jerk' ) );
$v = OrderValidator::validate( array( 'amount' => '10.00', 'display_name' => 'Big Jerk', 'message' => 'you shit, class act' ), $goal, $s, new FeeCalculator( 349, 49 ), 1800000000 );
$this->assertSame( 'Big ****', $v['donor_name'] );
$this->assertSame( 'you ****, class act', $v['message'] );
$s['profanity_filter'] = false;
$v = OrderValidator::validate( array( 'amount' => '10.00', 'display_name' => 'Big Jerk', 'message' => 'shit' ), $goal, $s, new FeeCalculator( 349, 49 ), 1800000000 );
$this->assertSame( 'Big Jerk', $v['donor_name'] );
$this->assertSame( 'shit', $v['message'] );
}
}