58 lines
2.4 KiB
PHP
58 lines
2.4 KiB
PHP
<?php
|
|||
|
|
declare( strict_types=1 );
|
||
|
|
|
||
|
|
namespace StreamGoals\Admin;
|
||
|
|
|
||
|
|
use StreamGoals\Actions\Matcher;
|
||
|
|
|
||
|
|
/** Pure validation/sanitizing for the rewards form. */
|
||
|
|
final class ActionInput {
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param int[] $validGoalIds Existing goal ids (0 = all goals is always allowed).
|
||
|
|
* @return array{data:?array,error:?string}
|
||
|
|
*/
|
||
|
|
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, ?int $defaultSort = null ): array {
|
||
|
|
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
|
||
|
|
$title = Input::text( $post['title'] ?? '', 200 );
|
||
|
|
if ( '' === $title ) {
|
||
|
|
return $fail( 'Please give the reward a title, for example "Eat a bean".' );
|
||
|
|
}
|
||
|
|
if ( self::len( $title ) > 120 ) {
|
||
|
|
return $fail( 'The title can be at most 120 characters.' );
|
||
|
|
}
|
||
|
|
$desc = Input::text( $post['description'] ?? '', 400 );
|
||
|
|
if ( self::len( $desc ) > 255 ) {
|
||
|
|
return $fail( 'The description can be at most 255 characters.' );
|
||
|
|
}
|
||
|
|
$amount = Input::amountToMinor( $post['amount'] ?? '', $currency );
|
||
|
|
if ( null === $amount || $amount <= 0 ) {
|
||
|
|
return $fail( 'Please enter an amount greater than zero, for example 5.00.' );
|
||
|
|
}
|
||
|
|
if ( $amount < $minMinor ) {
|
||
|
|
return $fail( 'The amount must be at least the minimum donation (' . Format::money( $minMinor, $currency ) . ').' );
|
||
|
|
}
|
||
|
|
$mode = is_scalar( $post['mode'] ?? null ) ? (string) $post['mode'] : '';
|
||
|
|
if ( ! in_array( $mode, array( Matcher::EXACT, Matcher::EVERY ), true ) ) {
|
||
|
|
return $fail( 'Please choose when the reward triggers.' );
|
||
|
|
}
|
||
|
|
$goalRaw = $post['goal_id'] ?? '0';
|
||
|
|
$goal = Input::int( $goalRaw, 0, PHP_INT_MAX >> 1 );
|
||
|
|
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
|
||
|
|
return $fail( 'Please choose all goals or one of your goals.' );
|
||
|
|
}
|
||
|
|
$sortRaw = $post['sort'] ?? '';
|
||
|
|
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? ( $defaultSort ?? 0 ) : Input::int( $sortRaw, 0, 99999 );
|
||
|
|
if ( null === $sort ) {
|
||
|
|
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||
|
|
}
|
||
|
|
return array(
|
||
|
|
'data' => array( 'goal_id' => $goal, 'title' => $title, 'description' => $desc, 'amount_minor' => $amount, 'mode' => $mode, 'sort' => $sort ),
|
||
|
|
'error' => null,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static function len( string $s ): int {
|
||
|
|
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
|
||
|
|
}
|
||
|
|
}
|