Add Registration Questions domain (per-offering intake forms)
CI / Coding Standards (pull_request) Successful in 51s
CI / PHPStan (pull_request) Successful in 1m0s
CI / Tests (PHP 8.1) (pull_request) Successful in 46s
CI / Tests (PHP 8.2) (pull_request) Successful in 48s
CI / Tests (PHP 8.3) (pull_request) Successful in 47s
CI / No Debug Code (pull_request) Successful in 3s
CI / Coding Standards (pull_request) Successful in 51s
CI / PHPStan (pull_request) Successful in 1m0s
CI / Tests (PHP 8.1) (pull_request) Successful in 46s
CI / Tests (PHP 8.2) (pull_request) Successful in 48s
CI / Tests (PHP 8.3) (pull_request) Successful in 47s
CI / No Debug Code (pull_request) Successful in 3s
Implements #5: studio admin / instructors author intake questions scoped per offering; answers are stored against a lesson or group enrolment via a polymorphic registration reference. - src/Registration/: Question + Answer value objects, QuestionRepository and AnswerRepository, QuestionEndpoint (REST), QuestionController + templates/admin/questions.php (Offerings -> Questions submenu) - us_questions and us_question_answers tables in Schema.php - REST: public GET /offerings/{id}/questions; POST/PATCH/DELETE /questions gated by manage_questions + offering ownership (owner or studio admin) - Field types text/textarea/select/checkbox; select options stored as JSON - Wiring in Plugin, RestRegistrar, AdminMenu AnswerRepository is built now and consumed by the booking/enrolment flow in #3/#4. Tests: tests/Unit/Registration/ (19 tests). composer test (63 total), cs, and PHPStan level 6 all pass. Refs #5 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+15
-1
@@ -10,17 +10,21 @@ use Unsupervised\Schedular\Booking\BookingRepository;
|
||||
use Unsupervised\Schedular\Booking\LessonController;
|
||||
use Unsupervised\Schedular\Offering\OfferingController;
|
||||
use Unsupervised\Schedular\Offering\OfferingRepository;
|
||||
use Unsupervised\Schedular\Registration\QuestionController;
|
||||
use Unsupervised\Schedular\Registration\QuestionRepository;
|
||||
|
||||
class AdminMenu {
|
||||
|
||||
private AvailabilityController $availabilityController;
|
||||
private LessonController $lessonController;
|
||||
private OfferingController $offeringController;
|
||||
private QuestionController $questionController;
|
||||
|
||||
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings ) {
|
||||
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions ) {
|
||||
$this->availabilityController = new AvailabilityController( $availability );
|
||||
$this->lessonController = new LessonController( $bookings );
|
||||
$this->offeringController = new OfferingController( $offerings );
|
||||
$this->questionController = new QuestionController( $questions, $offerings );
|
||||
}
|
||||
|
||||
public function register(): void {
|
||||
@@ -61,6 +65,16 @@ class AdminMenu {
|
||||
33
|
||||
);
|
||||
|
||||
// Studio admin / instructor: manage per-offering intake questions.
|
||||
add_submenu_page(
|
||||
'us-offerings',
|
||||
__( 'Questions', 'unsupervised-schedular' ),
|
||||
__( 'Questions', 'unsupervised-schedular' ),
|
||||
RoleManager::CAP_MANAGE_QUESTIONS,
|
||||
'us-questions',
|
||||
[ $this->questionController, 'renderPage' ]
|
||||
);
|
||||
|
||||
// Instructor: view their upcoming lessons.
|
||||
add_menu_page(
|
||||
__( 'My Lessons', 'unsupervised-schedular' ),
|
||||
|
||||
+4
-2
@@ -7,6 +7,7 @@ use Unsupervised\Schedular\Auth\RoleManager;
|
||||
use Unsupervised\Schedular\Availability\AvailabilityRepository;
|
||||
use Unsupervised\Schedular\Booking\BookingRepository;
|
||||
use Unsupervised\Schedular\Offering\OfferingRepository;
|
||||
use Unsupervised\Schedular\Registration\QuestionRepository;
|
||||
|
||||
class Plugin {
|
||||
|
||||
@@ -17,10 +18,11 @@ class Plugin {
|
||||
$availability = new AvailabilityRepository( $wpdb );
|
||||
$bookings = new BookingRepository( $wpdb );
|
||||
$offerings = new OfferingRepository( $wpdb );
|
||||
$questions = new QuestionRepository( $wpdb );
|
||||
|
||||
( new RoleManager() )->register();
|
||||
( new AdminMenu( $availability, $bookings, $offerings ) )->register();
|
||||
( new RestRegistrar( $availability, $bookings, $offerings ) )->register();
|
||||
( new AdminMenu( $availability, $bookings, $offerings, $questions ) )->register();
|
||||
( new RestRegistrar( $availability, $bookings, $offerings, $questions ) )->register();
|
||||
( new ShortcodeRegistrar() )->register();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
class Answer {
|
||||
|
||||
public const REG_LESSON = 'lesson';
|
||||
public const REG_ENROLLMENT = 'enrollment';
|
||||
|
||||
/**
|
||||
* Polymorphic registration targets an answer can attach to.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const VALID_REGISTRATION_TYPES = [ self::REG_LESSON, self::REG_ENROLLMENT ];
|
||||
|
||||
public function __construct(
|
||||
public readonly int $questionId,
|
||||
public readonly string $registrationType,
|
||||
public readonly int $registrationId,
|
||||
public readonly int $studentId,
|
||||
public readonly ?string $answerValue = null,
|
||||
public readonly ?int $id = null,
|
||||
) {}
|
||||
|
||||
public static function fromRow( object $row ): self {
|
||||
return new self(
|
||||
questionId: (int) $row->question_id,
|
||||
registrationType: $row->registration_type,
|
||||
registrationId: (int) $row->registration_id,
|
||||
studentId: (int) $row->student_id,
|
||||
answerValue: $row->answer_value,
|
||||
id: (int) $row->id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a plain array representation of the answer.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array {
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'question_id' => $this->questionId,
|
||||
'registration_type' => $this->registrationType,
|
||||
'registration_id' => $this->registrationId,
|
||||
'student_id' => $this->studentId,
|
||||
'answer_value' => $this->answerValue,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
class AnswerRepository {
|
||||
|
||||
private string $table;
|
||||
|
||||
public function __construct( private \wpdb $db ) {
|
||||
$this->table = $db->prefix . 'us_question_answers';
|
||||
}
|
||||
|
||||
public function insert( Answer $answer ): int {
|
||||
$this->db->insert(
|
||||
$this->table,
|
||||
[
|
||||
'question_id' => $answer->questionId,
|
||||
'registration_type' => $answer->registrationType,
|
||||
'registration_id' => $answer->registrationId,
|
||||
'student_id' => $answer->studentId,
|
||||
'answer_value' => $answer->answerValue,
|
||||
'created_at' => current_time( 'mysql' ),
|
||||
],
|
||||
[ '%d', '%s', '%d', '%d', '%s', '%s' ]
|
||||
);
|
||||
|
||||
return $this->db->insert_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a batch of answers for a single registration.
|
||||
*
|
||||
* @param list<Answer> $answers
|
||||
* @return list<int> Inserted answer IDs.
|
||||
*/
|
||||
public function insertMany( array $answers ): array {
|
||||
return array_map( fn( Answer $answer ): int => $this->insert( $answer ), $answers );
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all answers attached to a registration (lesson or enrolment).
|
||||
*
|
||||
* @return list<Answer>
|
||||
*/
|
||||
public function findByRegistration( string $registrationType, int $registrationId ): array {
|
||||
$rows = $this->db->get_results(
|
||||
$this->db->prepare(
|
||||
"SELECT * FROM {$this->table} WHERE registration_type = %s AND registration_id = %d ORDER BY id ASC",
|
||||
$registrationType,
|
||||
$registrationId
|
||||
)
|
||||
);
|
||||
|
||||
return array_map( Answer::fromRow( ... ), $rows ?? [] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
class Question {
|
||||
|
||||
public const FIELD_TEXT = 'text';
|
||||
public const FIELD_TEXTAREA = 'textarea';
|
||||
public const FIELD_SELECT = 'select';
|
||||
public const FIELD_CHECKBOX = 'checkbox';
|
||||
|
||||
/**
|
||||
* All valid field types.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const VALID_FIELD_TYPES = [
|
||||
self::FIELD_TEXT,
|
||||
self::FIELD_TEXTAREA,
|
||||
self::FIELD_SELECT,
|
||||
self::FIELD_CHECKBOX,
|
||||
];
|
||||
|
||||
/**
|
||||
* Build an intake question value object.
|
||||
*
|
||||
* @param list<string>|null $options Choices for a `select` field.
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $offeringId,
|
||||
public readonly string $label,
|
||||
public readonly string $fieldType = self::FIELD_TEXT,
|
||||
public readonly ?array $options = null,
|
||||
public readonly bool $isRequired = false,
|
||||
public readonly int $sortOrder = 0,
|
||||
public readonly bool $isActive = true,
|
||||
public readonly ?int $id = null,
|
||||
) {}
|
||||
|
||||
public static function fromRow( object $row ): self {
|
||||
$options = null;
|
||||
if ( null !== $row->options && '' !== $row->options ) {
|
||||
$decoded = json_decode( (string) $row->options, true );
|
||||
$options = is_array( $decoded ) ? array_values( array_map( 'strval', $decoded ) ) : null;
|
||||
}
|
||||
|
||||
return new self(
|
||||
offeringId: (int) $row->offering_id,
|
||||
label: $row->label,
|
||||
fieldType: $row->field_type,
|
||||
options: $options,
|
||||
isRequired: (bool) $row->is_required,
|
||||
sortOrder: (int) $row->sort_order,
|
||||
isActive: (bool) $row->is_active,
|
||||
id: (int) $row->id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a plain array representation of the question.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array {
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'offering_id' => $this->offeringId,
|
||||
'label' => $this->label,
|
||||
'field_type' => $this->fieldType,
|
||||
'options' => $this->options,
|
||||
'is_required' => $this->isRequired,
|
||||
'sort_order' => $this->sortOrder,
|
||||
'is_active' => $this->isActive,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
use Unsupervised\Schedular\Auth\RoleManager;
|
||||
use Unsupervised\Schedular\Offering\Offering;
|
||||
use Unsupervised\Schedular\Offering\OfferingRepository;
|
||||
|
||||
class QuestionController {
|
||||
|
||||
public function __construct(
|
||||
private QuestionRepository $questions,
|
||||
private OfferingRepository $offerings,
|
||||
) {}
|
||||
|
||||
public function renderPage(): void {
|
||||
if ( ! current_user_can( RoleManager::CAP_MANAGE_QUESTIONS ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to manage questions.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
$userId = get_current_user_id();
|
||||
$manageAll = current_user_can( RoleManager::CAP_MANAGE_INSTRUCTORS );
|
||||
|
||||
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only offering selector.
|
||||
$offeringId = absint( $_GET['offering_id'] ?? 0 );
|
||||
$offeringList = $manageAll ? $this->offerings->findAll() : $this->offerings->findAll( $userId );
|
||||
$selectedOffering = $offeringId > 0 ? $this->offerings->findById( $offeringId ) : null;
|
||||
|
||||
if ( null !== $selectedOffering && ! $this->canManageOffering( $selectedOffering, $userId, $manageAll ) ) {
|
||||
$selectedOffering = null;
|
||||
}
|
||||
|
||||
$questions = null;
|
||||
if ( null !== $selectedOffering ) {
|
||||
if ( isset( $_POST['usc_action'] ) && check_admin_referer( 'usc_question_action' ) ) {
|
||||
$this->handleFormAction( $selectedOffering );
|
||||
}
|
||||
|
||||
$questions = $this->questions->findByOffering( (int) $selectedOffering->id );
|
||||
}
|
||||
|
||||
include USC_PLUGIN_DIR . 'templates/admin/questions.php';
|
||||
}
|
||||
|
||||
private function handleFormAction( Offering $offering ): void {
|
||||
// Nonce is verified by the caller (renderPage) before this method runs.
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing
|
||||
$action = sanitize_key( wp_unslash( $_POST['usc_action'] ?? '' ) );
|
||||
|
||||
if ( 'add' === $action ) {
|
||||
$this->addQuestion( (int) $offering->id );
|
||||
}
|
||||
|
||||
if ( 'delete' === $action ) {
|
||||
$questionId = absint( $_POST['question_id'] ?? 0 );
|
||||
if ( $questionId > 0 ) {
|
||||
$question = $this->questions->findById( $questionId );
|
||||
if ( $question && $question->offeringId === (int) $offering->id ) {
|
||||
$this->questions->delete( $questionId );
|
||||
}
|
||||
}
|
||||
}
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing
|
||||
}
|
||||
|
||||
private function addQuestion( int $offeringId ): void {
|
||||
// phpcs:disable WordPress.Security.NonceVerification.Missing
|
||||
$label = sanitize_text_field( wp_unslash( $_POST['label'] ?? '' ) );
|
||||
$fieldType = sanitize_key( wp_unslash( $_POST['field_type'] ?? Question::FIELD_TEXT ) );
|
||||
|
||||
if ( '' === $label || ! in_array( $fieldType, Question::VALID_FIELD_TYPES, true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->questions->insert(
|
||||
new Question(
|
||||
offeringId: $offeringId,
|
||||
label: $label,
|
||||
fieldType: $fieldType,
|
||||
options: $this->parseOptions( sanitize_textarea_field( wp_unslash( $_POST['options'] ?? '' ) ) ),
|
||||
isRequired: isset( $_POST['is_required'] ),
|
||||
sortOrder: absint( $_POST['sort_order'] ?? 0 ),
|
||||
)
|
||||
);
|
||||
// phpcs:enable WordPress.Security.NonceVerification.Missing
|
||||
}
|
||||
|
||||
private function canManageOffering( Offering $offering, int $userId, bool $manageAll ): bool {
|
||||
return $manageAll || $offering->instructorId === $userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a newline-separated textarea into a list of option strings.
|
||||
*
|
||||
* @return list<string>|null
|
||||
*/
|
||||
private function parseOptions( string $raw ): ?array {
|
||||
$lines = preg_split( '/\r\n|\r|\n/', $raw );
|
||||
$options = array_values(
|
||||
array_filter(
|
||||
array_map(
|
||||
static fn( string $line ): string => sanitize_text_field( trim( $line ) ),
|
||||
false === $lines ? [] : $lines
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
return [] === $options ? null : $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
use Unsupervised\Schedular\Auth\RoleManager;
|
||||
use Unsupervised\Schedular\Offering\OfferingRepository;
|
||||
|
||||
class QuestionEndpoint {
|
||||
|
||||
public function __construct(
|
||||
private QuestionRepository $questions,
|
||||
private OfferingRepository $offerings,
|
||||
) {}
|
||||
|
||||
public function registerRoutes( string $route_namespace ): void {
|
||||
register_rest_route(
|
||||
$route_namespace,
|
||||
'/offerings/(?P<id>\d+)/questions',
|
||||
[
|
||||
[
|
||||
'methods' => \WP_REST_Server::READABLE,
|
||||
'callback' => [ $this, 'index' ],
|
||||
'permission_callback' => '__return_true',
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
register_rest_route(
|
||||
$route_namespace,
|
||||
'/questions',
|
||||
[
|
||||
[
|
||||
'methods' => \WP_REST_Server::CREATABLE,
|
||||
'callback' => [ $this, 'create' ],
|
||||
'permission_callback' => [ $this, 'canManage' ],
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
register_rest_route(
|
||||
$route_namespace,
|
||||
'/questions/(?P<id>\d+)',
|
||||
[
|
||||
[
|
||||
'methods' => \WP_REST_Server::EDITABLE,
|
||||
'callback' => [ $this, 'update' ],
|
||||
'permission_callback' => [ $this, 'canManage' ],
|
||||
],
|
||||
[
|
||||
'methods' => \WP_REST_Server::DELETABLE,
|
||||
'callback' => [ $this, 'delete' ],
|
||||
'permission_callback' => [ $this, 'canManage' ],
|
||||
],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function index( \WP_REST_Request $request ): \WP_REST_Response {
|
||||
$questions = $this->questions->findByOffering( absint( $request->get_param( 'id' ) ), activeOnly: true );
|
||||
|
||||
return new \WP_REST_Response( array_map( fn( Question $q ) => $q->toArray(), $questions ), 200 );
|
||||
}
|
||||
|
||||
public function create( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error {
|
||||
$offeringId = absint( $request->get_param( 'offering_id' ) );
|
||||
$ownerCheck = $this->requireOfferingOwner( $offeringId );
|
||||
if ( $ownerCheck instanceof \WP_Error ) {
|
||||
return $ownerCheck;
|
||||
}
|
||||
|
||||
$label = sanitize_text_field( (string) $request->get_param( 'label' ) );
|
||||
if ( '' === $label ) {
|
||||
return $this->invalid( __( 'A question label is required.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
$fieldType = (string) ( $request->get_param( 'field_type' ) ?? Question::FIELD_TEXT );
|
||||
if ( ! in_array( $fieldType, Question::VALID_FIELD_TYPES, true ) ) {
|
||||
return $this->invalid( __( 'Invalid field type.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
$question = new Question(
|
||||
offeringId: $offeringId,
|
||||
label: $label,
|
||||
fieldType: $fieldType,
|
||||
options: $this->sanitizeOptions( $request->get_param( 'options' ) ),
|
||||
isRequired: (bool) $request->get_param( 'is_required' ),
|
||||
sortOrder: (int) $request->get_param( 'sort_order' ),
|
||||
isActive: null === $request->get_param( 'is_active' ) ? true : (bool) $request->get_param( 'is_active' ),
|
||||
);
|
||||
|
||||
$id = $this->questions->insert( $question );
|
||||
|
||||
return new \WP_REST_Response( [ 'id' => $id ], 201 );
|
||||
}
|
||||
|
||||
public function update( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error {
|
||||
$id = absint( $request->get_param( 'id' ) );
|
||||
$existing = $this->questions->findById( $id );
|
||||
|
||||
if ( null === $existing ) {
|
||||
return new \WP_Error( 'not_found', __( 'Question not found.', 'unsupervised-schedular' ), [ 'status' => 404 ] );
|
||||
}
|
||||
|
||||
$ownerCheck = $this->requireOfferingOwner( $existing->offeringId );
|
||||
if ( $ownerCheck instanceof \WP_Error ) {
|
||||
return $ownerCheck;
|
||||
}
|
||||
|
||||
$fieldType = $request->has_param( 'field_type' ) ? (string) $request->get_param( 'field_type' ) : $existing->fieldType;
|
||||
if ( ! in_array( $fieldType, Question::VALID_FIELD_TYPES, true ) ) {
|
||||
return $this->invalid( __( 'Invalid field type.', 'unsupervised-schedular' ) );
|
||||
}
|
||||
|
||||
$question = new Question(
|
||||
offeringId: $existing->offeringId,
|
||||
label: $request->has_param( 'label' ) ? sanitize_text_field( (string) $request->get_param( 'label' ) ) : $existing->label,
|
||||
fieldType: $fieldType,
|
||||
options: $request->has_param( 'options' ) ? $this->sanitizeOptions( $request->get_param( 'options' ) ) : $existing->options,
|
||||
isRequired: $request->has_param( 'is_required' ) ? (bool) $request->get_param( 'is_required' ) : $existing->isRequired,
|
||||
sortOrder: $request->has_param( 'sort_order' ) ? (int) $request->get_param( 'sort_order' ) : $existing->sortOrder,
|
||||
isActive: $request->has_param( 'is_active' ) ? (bool) $request->get_param( 'is_active' ) : $existing->isActive,
|
||||
id: $id,
|
||||
);
|
||||
|
||||
$this->questions->update( $id, $question );
|
||||
|
||||
return new \WP_REST_Response( $question->toArray(), 200 );
|
||||
}
|
||||
|
||||
public function delete( \WP_REST_Request $request ): \WP_REST_Response|\WP_Error {
|
||||
$id = absint( $request->get_param( 'id' ) );
|
||||
$existing = $this->questions->findById( $id );
|
||||
|
||||
if ( null === $existing ) {
|
||||
return new \WP_Error( 'not_found', __( 'Question not found.', 'unsupervised-schedular' ), [ 'status' => 404 ] );
|
||||
}
|
||||
|
||||
$ownerCheck = $this->requireOfferingOwner( $existing->offeringId );
|
||||
if ( $ownerCheck instanceof \WP_Error ) {
|
||||
return $ownerCheck;
|
||||
}
|
||||
|
||||
$this->questions->delete( $id );
|
||||
|
||||
return new \WP_REST_Response( null, 204 );
|
||||
}
|
||||
|
||||
public function canManage(): bool {
|
||||
return is_user_logged_in() && current_user_can( RoleManager::CAP_MANAGE_QUESTIONS );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the offering exists and the caller owns it (or is a studio admin).
|
||||
*/
|
||||
private function requireOfferingOwner( int $offeringId ): ?\WP_Error {
|
||||
$offering = $this->offerings->findById( $offeringId );
|
||||
|
||||
if ( null === $offering ) {
|
||||
return new \WP_Error( 'not_found', __( 'Offering not found.', 'unsupervised-schedular' ), [ 'status' => 404 ] );
|
||||
}
|
||||
|
||||
$ownsOrManagesAll = get_current_user_id() === $offering->instructorId
|
||||
|| current_user_can( RoleManager::CAP_MANAGE_INSTRUCTORS );
|
||||
|
||||
if ( ! $ownsOrManagesAll ) {
|
||||
return new \WP_Error( 'forbidden', __( 'You cannot manage questions for this offering.', 'unsupervised-schedular' ), [ 'status' => 403 ] );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a submitted options array into a clean list of strings.
|
||||
*
|
||||
* @return list<string>|null
|
||||
*/
|
||||
private function sanitizeOptions( mixed $value ): ?array {
|
||||
if ( ! is_array( $value ) || [] === $value ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$options = array_values(
|
||||
array_filter(
|
||||
array_map(
|
||||
static fn( $option ): string => sanitize_text_field( (string) $option ),
|
||||
$value
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
return [] === $options ? null : $options;
|
||||
}
|
||||
|
||||
private function invalid( string $message ): \WP_Error {
|
||||
return new \WP_Error( 'invalid_question', $message, [ 'status' => 400 ] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Registration;
|
||||
|
||||
class QuestionRepository {
|
||||
|
||||
private string $table;
|
||||
|
||||
public function __construct( private \wpdb $db ) {
|
||||
$this->table = $db->prefix . 'us_questions';
|
||||
}
|
||||
|
||||
public function insert( Question $question ): int {
|
||||
$this->db->insert(
|
||||
$this->table,
|
||||
$this->columns( $question ) + [ 'created_at' => current_time( 'mysql' ) ],
|
||||
[ '%d', '%s', '%s', '%s', '%d', '%d', '%d', '%s' ]
|
||||
);
|
||||
|
||||
return $this->db->insert_id;
|
||||
}
|
||||
|
||||
public function update( int $id, Question $question ): bool {
|
||||
return false !== $this->db->update(
|
||||
$this->table,
|
||||
$this->columns( $question ),
|
||||
[ 'id' => $id ],
|
||||
[ '%d', '%s', '%s', '%s', '%d', '%d', '%d' ],
|
||||
[ '%d' ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Column values shared by insert and update (excludes created_at).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function columns( Question $question ): array {
|
||||
return [
|
||||
'offering_id' => $question->offeringId,
|
||||
'label' => $question->label,
|
||||
'field_type' => $question->fieldType,
|
||||
'options' => null === $question->options ? null : (string) wp_json_encode( $question->options ),
|
||||
'is_required' => $question->isRequired ? 1 : 0,
|
||||
'sort_order' => $question->sortOrder,
|
||||
'is_active' => $question->isActive ? 1 : 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Find questions for an offering, ordered for display.
|
||||
*
|
||||
* @return list<Question>
|
||||
*/
|
||||
public function findByOffering( int $offeringId, bool $activeOnly = false ): array {
|
||||
$sql = "SELECT * FROM {$this->table} WHERE offering_id = %d";
|
||||
$params = [ $offeringId ];
|
||||
|
||||
if ( $activeOnly ) {
|
||||
$sql .= ' AND is_active = %d';
|
||||
$params[] = 1;
|
||||
}
|
||||
|
||||
$sql .= ' ORDER BY sort_order ASC, id ASC';
|
||||
|
||||
$rows = $this->db->get_results( $this->db->prepare( $sql, $params ) );
|
||||
|
||||
return array_map( Question::fromRow( ... ), $rows ?? [] );
|
||||
}
|
||||
|
||||
public function findById( int $id ): ?Question {
|
||||
$row = $this->db->get_row(
|
||||
$this->db->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id )
|
||||
);
|
||||
|
||||
return $row ? Question::fromRow( $row ) : null;
|
||||
}
|
||||
|
||||
public function delete( int $id ): bool {
|
||||
return (bool) $this->db->delete(
|
||||
$this->table,
|
||||
[ 'id' => $id ],
|
||||
[ '%d' ]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use Unsupervised\Schedular\Booking\BookingEndpoint;
|
||||
use Unsupervised\Schedular\Booking\BookingRepository;
|
||||
use Unsupervised\Schedular\Offering\OfferingEndpoint;
|
||||
use Unsupervised\Schedular\Offering\OfferingRepository;
|
||||
use Unsupervised\Schedular\Registration\QuestionEndpoint;
|
||||
use Unsupervised\Schedular\Registration\QuestionRepository;
|
||||
|
||||
class RestRegistrar {
|
||||
|
||||
@@ -17,11 +19,13 @@ class RestRegistrar {
|
||||
private AvailabilityEndpoint $availabilityEndpoint;
|
||||
private BookingEndpoint $bookingEndpoint;
|
||||
private OfferingEndpoint $offeringEndpoint;
|
||||
private QuestionEndpoint $questionEndpoint;
|
||||
|
||||
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings ) {
|
||||
public function __construct( AvailabilityRepository $availability, BookingRepository $bookings, OfferingRepository $offerings, QuestionRepository $questions ) {
|
||||
$this->availabilityEndpoint = new AvailabilityEndpoint( $availability );
|
||||
$this->bookingEndpoint = new BookingEndpoint( $availability, $bookings );
|
||||
$this->offeringEndpoint = new OfferingEndpoint( $offerings );
|
||||
$this->questionEndpoint = new QuestionEndpoint( $questions, $offerings );
|
||||
}
|
||||
|
||||
public function register(): void {
|
||||
@@ -32,5 +36,6 @@ class RestRegistrar {
|
||||
$this->availabilityEndpoint->registerRoutes( self::NAMESPACE );
|
||||
$this->bookingEndpoint->registerRoutes( self::NAMESPACE );
|
||||
$this->offeringEndpoint->registerRoutes( self::NAMESPACE );
|
||||
$this->questionEndpoint->registerRoutes( self::NAMESPACE );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,35 @@ class Schema {
|
||||
KEY kind (kind),
|
||||
KEY is_active (is_active)
|
||||
) {$charset};",
|
||||
|
||||
"CREATE TABLE {$prefix}us_questions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
offering_id BIGINT UNSIGNED NOT NULL,
|
||||
label VARCHAR(255) NOT NULL,
|
||||
field_type VARCHAR(20) NOT NULL DEFAULT 'text',
|
||||
options TEXT,
|
||||
is_required TINYINT(1) NOT NULL DEFAULT 0,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
is_active TINYINT(1) NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY offering_id (offering_id),
|
||||
KEY is_active (is_active)
|
||||
) {$charset};",
|
||||
|
||||
"CREATE TABLE {$prefix}us_question_answers (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
question_id BIGINT UNSIGNED NOT NULL,
|
||||
registration_type VARCHAR(20) NOT NULL,
|
||||
registration_id BIGINT UNSIGNED NOT NULL,
|
||||
student_id BIGINT UNSIGNED NOT NULL,
|
||||
answer_value TEXT,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY question_id (question_id),
|
||||
KEY registration (registration_type, registration_id),
|
||||
KEY student_id (student_id)
|
||||
) {$charset};",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Unsupervised\Schedular\Registration\Question;
|
||||
|
||||
if (! defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<\Unsupervised\Schedular\Offering\Offering> $offeringList
|
||||
* @var \Unsupervised\Schedular\Offering\Offering|null $selectedOffering
|
||||
* @var list<\Unsupervised\Schedular\Registration\Question>|null $questions
|
||||
*/
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e('Registration Questions', 'unsupervised-schedular'); ?></h1>
|
||||
|
||||
<form method="get">
|
||||
<input type="hidden" name="page" value="us-questions">
|
||||
<label for="offering_id"><?php esc_html_e('Offering', 'unsupervised-schedular'); ?></label>
|
||||
<select name="offering_id" id="offering_id" onchange="this.form.submit()">
|
||||
<option value="0"><?php esc_html_e('— Select an offering —', 'unsupervised-schedular'); ?></option>
|
||||
<?php foreach ($offeringList as $offering) : ?>
|
||||
<option value="<?php echo esc_attr((string) $offering->id); ?>" <?php selected($selectedOffering && $selectedOffering->id === $offering->id); ?>>
|
||||
<?php echo esc_html($offering->title); ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</form>
|
||||
|
||||
<?php if (null === $selectedOffering) : ?>
|
||||
<p><?php esc_html_e('Choose an offering to manage its intake questions.', 'unsupervised-schedular'); ?></p>
|
||||
<?php else : ?>
|
||||
<h2><?php echo esc_html(sprintf(/* translators: %s: offering title */ __('Questions for "%s"', 'unsupervised-schedular'), $selectedOffering->title)); ?></h2>
|
||||
|
||||
<h3><?php esc_html_e('Add Question', 'unsupervised-schedular'); ?></h3>
|
||||
<form method="post">
|
||||
<?php wp_nonce_field('usc_question_action'); ?>
|
||||
<input type="hidden" name="usc_action" value="add">
|
||||
<table class="form-table">
|
||||
<tr>
|
||||
<th><label for="label"><?php esc_html_e('Question', 'unsupervised-schedular'); ?></label></th>
|
||||
<td><input type="text" name="label" id="label" class="regular-text" required></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="field_type"><?php esc_html_e('Field type', 'unsupervised-schedular'); ?></label></th>
|
||||
<td>
|
||||
<select name="field_type" id="field_type">
|
||||
<option value="<?php echo esc_attr(Question::FIELD_TEXT); ?>"><?php esc_html_e('Text', 'unsupervised-schedular'); ?></option>
|
||||
<option value="<?php echo esc_attr(Question::FIELD_TEXTAREA); ?>"><?php esc_html_e('Paragraph', 'unsupervised-schedular'); ?></option>
|
||||
<option value="<?php echo esc_attr(Question::FIELD_SELECT); ?>"><?php esc_html_e('Dropdown', 'unsupervised-schedular'); ?></option>
|
||||
<option value="<?php echo esc_attr(Question::FIELD_CHECKBOX); ?>"><?php esc_html_e('Checkbox', 'unsupervised-schedular'); ?></option>
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="options"><?php esc_html_e('Options', 'unsupervised-schedular'); ?></label></th>
|
||||
<td>
|
||||
<textarea name="options" id="options" rows="4" class="large-text" placeholder="<?php esc_attr_e('One choice per line (dropdown only)', 'unsupervised-schedular'); ?>"></textarea>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><label for="sort_order"><?php esc_html_e('Sort order', 'unsupervised-schedular'); ?></label></th>
|
||||
<td><input type="number" name="sort_order" id="sort_order" min="0" step="1" value="0"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><?php esc_html_e('Required', 'unsupervised-schedular'); ?></th>
|
||||
<td><label><input type="checkbox" name="is_required" value="1"> <?php esc_html_e('Registrant must answer', 'unsupervised-schedular'); ?></label></td>
|
||||
</tr>
|
||||
</table>
|
||||
<?php submit_button(esc_html__('Add Question', 'unsupervised-schedular')); ?>
|
||||
</form>
|
||||
|
||||
<h3><?php esc_html_e('Current Questions', 'unsupervised-schedular'); ?></h3>
|
||||
<?php if (empty($questions)) : ?>
|
||||
<p><?php esc_html_e('No questions configured for this offering.', 'unsupervised-schedular'); ?></p>
|
||||
<?php else : ?>
|
||||
<table class="wp-list-table widefat fixed striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?php esc_html_e('Order', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Question', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Type', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Required', 'unsupervised-schedular'); ?></th>
|
||||
<th><?php esc_html_e('Actions', 'unsupervised-schedular'); ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($questions as $question) : ?>
|
||||
<tr>
|
||||
<td><?php echo esc_html((string) $question->sortOrder); ?></td>
|
||||
<td><?php echo esc_html($question->label); ?></td>
|
||||
<td><?php echo esc_html($question->fieldType); ?></td>
|
||||
<td><?php echo $question->isRequired ? esc_html__('Yes', 'unsupervised-schedular') : esc_html__('No', 'unsupervised-schedular'); ?></td>
|
||||
<td>
|
||||
<form method="post" style="display:inline;">
|
||||
<?php wp_nonce_field('usc_question_action'); ?>
|
||||
<input type="hidden" name="usc_action" value="delete">
|
||||
<input type="hidden" name="question_id" value="<?php echo esc_attr((string) $question->id); ?>">
|
||||
<button type="submit" class="button button-small button-link-delete">
|
||||
<?php esc_html_e('Delete', 'unsupervised-schedular'); ?>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Registration;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Registration\Answer;
|
||||
use Unsupervised\Schedular\Registration\AnswerRepository;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class AnswerRepositoryTest extends TestCase
|
||||
{
|
||||
private \wpdb $db;
|
||||
private AnswerRepository $repo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->db = Mockery::mock(\wpdb::class);
|
||||
$this->db->prefix = 'wp_';
|
||||
$this->repo = new AnswerRepository($this->db);
|
||||
}
|
||||
|
||||
public function testInsertCallsWpdbInsertAndReturnsId(): void
|
||||
{
|
||||
Functions\expect('current_time')->with('mysql')->andReturn('2026-04-01 12:00:00');
|
||||
|
||||
$this->db->shouldReceive('insert')
|
||||
->once()
|
||||
->with(
|
||||
'wp_us_question_answers',
|
||||
Mockery::on(static function (array $data): bool {
|
||||
return $data['question_id'] === 3
|
||||
&& $data['registration_type'] === Answer::REG_LESSON
|
||||
&& $data['registration_id'] === 12
|
||||
&& $data['student_id'] === 5
|
||||
&& $data['answer_value'] === 'Beginner';
|
||||
}),
|
||||
['%d', '%s', '%d', '%d', '%s', '%s']
|
||||
);
|
||||
|
||||
$this->db->insert_id = 77;
|
||||
|
||||
$answer = new Answer(3, Answer::REG_LESSON, 12, 5, 'Beginner');
|
||||
|
||||
self::assertSame(77, $this->repo->insert($answer));
|
||||
}
|
||||
|
||||
public function testInsertManyReturnsAllIds(): void
|
||||
{
|
||||
Functions\when('current_time')->justReturn('2026-04-01 12:00:00');
|
||||
|
||||
$ids = [101, 102];
|
||||
$this->db->shouldReceive('insert')
|
||||
->twice()
|
||||
->andReturnUsing(function () use (&$ids): void {
|
||||
$this->db->insert_id = array_shift($ids);
|
||||
});
|
||||
|
||||
$answers = [
|
||||
new Answer(3, Answer::REG_LESSON, 12, 5, 'A'),
|
||||
new Answer(4, Answer::REG_LESSON, 12, 5, 'B'),
|
||||
];
|
||||
|
||||
$result = $this->repo->insertMany($answers);
|
||||
|
||||
self::assertSame([101, 102], $result);
|
||||
}
|
||||
|
||||
public function testFindByRegistrationPreparesQueryAndMaps(): void
|
||||
{
|
||||
$row = (object) [
|
||||
'id' => '1',
|
||||
'question_id' => '3',
|
||||
'registration_type' => Answer::REG_LESSON,
|
||||
'registration_id' => '12',
|
||||
'student_id' => '5',
|
||||
'answer_value' => 'Beginner',
|
||||
];
|
||||
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::pattern('/registration_type = %s AND registration_id = %d/'),
|
||||
Answer::REG_LESSON,
|
||||
12
|
||||
)
|
||||
->andReturn('SELECT ...');
|
||||
|
||||
$this->db->shouldReceive('get_results')->andReturn([$row]);
|
||||
|
||||
$answers = $this->repo->findByRegistration(Answer::REG_LESSON, 12);
|
||||
|
||||
self::assertCount(1, $answers);
|
||||
self::assertInstanceOf(Answer::class, $answers[0]);
|
||||
self::assertSame(3, $answers[0]->questionId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Registration;
|
||||
|
||||
use Unsupervised\Schedular\Registration\Answer;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class AnswerTest extends TestCase
|
||||
{
|
||||
public function testConstructorAndProperties(): void
|
||||
{
|
||||
$answer = new Answer(3, Answer::REG_LESSON, 12, 5, 'Beginner', 99);
|
||||
|
||||
self::assertSame(3, $answer->questionId);
|
||||
self::assertSame(Answer::REG_LESSON, $answer->registrationType);
|
||||
self::assertSame(12, $answer->registrationId);
|
||||
self::assertSame(5, $answer->studentId);
|
||||
self::assertSame('Beginner', $answer->answerValue);
|
||||
self::assertSame(99, $answer->id);
|
||||
}
|
||||
|
||||
public function testFromRowMapsCorrectly(): void
|
||||
{
|
||||
$row = (object) [
|
||||
'id' => '99',
|
||||
'question_id' => '3',
|
||||
'registration_type' => Answer::REG_ENROLLMENT,
|
||||
'registration_id' => '12',
|
||||
'student_id' => '5',
|
||||
'answer_value' => '1',
|
||||
];
|
||||
|
||||
$answer = Answer::fromRow($row);
|
||||
|
||||
self::assertSame(99, $answer->id);
|
||||
self::assertSame(3, $answer->questionId);
|
||||
self::assertSame(Answer::REG_ENROLLMENT, $answer->registrationType);
|
||||
self::assertSame(12, $answer->registrationId);
|
||||
}
|
||||
|
||||
public function testToArrayContainsExpectedKeys(): void
|
||||
{
|
||||
$answer = new Answer(3, Answer::REG_LESSON, 12, 5);
|
||||
$arr = $answer->toArray();
|
||||
|
||||
foreach (['id', 'question_id', 'registration_type', 'registration_id', 'student_id', 'answer_value'] as $key) {
|
||||
self::assertArrayHasKey($key, $arr);
|
||||
}
|
||||
}
|
||||
|
||||
public function testValidRegistrationTypeConstants(): void
|
||||
{
|
||||
self::assertContains(Answer::REG_LESSON, Answer::VALID_REGISTRATION_TYPES);
|
||||
self::assertContains(Answer::REG_ENROLLMENT, Answer::VALID_REGISTRATION_TYPES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Registration;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
use Mockery;
|
||||
use Unsupervised\Schedular\Registration\Question;
|
||||
use Unsupervised\Schedular\Registration\QuestionRepository;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class QuestionRepositoryTest extends TestCase
|
||||
{
|
||||
private \wpdb $db;
|
||||
private QuestionRepository $repo;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->db = Mockery::mock(\wpdb::class);
|
||||
$this->db->prefix = 'wp_';
|
||||
$this->repo = new QuestionRepository($this->db);
|
||||
}
|
||||
|
||||
public function testInsertWithNullOptionsStoresNull(): void
|
||||
{
|
||||
Functions\expect('current_time')->with('mysql')->andReturn('2026-04-01 12:00:00');
|
||||
|
||||
$this->db->shouldReceive('insert')
|
||||
->once()
|
||||
->with(
|
||||
'wp_us_questions',
|
||||
Mockery::on(static function (array $data): bool {
|
||||
return $data['offering_id'] === 7
|
||||
&& $data['label'] === 'Your level?'
|
||||
&& $data['field_type'] === Question::FIELD_TEXT
|
||||
&& $data['options'] === null
|
||||
&& $data['is_required'] === 0
|
||||
&& $data['created_at'] === '2026-04-01 12:00:00';
|
||||
}),
|
||||
Mockery::type('array')
|
||||
);
|
||||
|
||||
$this->db->insert_id = 21;
|
||||
|
||||
$question = new Question(7, 'Your level?');
|
||||
|
||||
self::assertSame(21, $this->repo->insert($question));
|
||||
}
|
||||
|
||||
public function testInsertEncodesOptionsAsJson(): void
|
||||
{
|
||||
Functions\expect('current_time')->andReturn('2026-04-01 12:00:00');
|
||||
Functions\expect('wp_json_encode')
|
||||
->once()
|
||||
->with(['Beginner', 'Advanced'])
|
||||
->andReturn('["Beginner","Advanced"]');
|
||||
|
||||
$this->db->shouldReceive('insert')
|
||||
->once()
|
||||
->with(
|
||||
'wp_us_questions',
|
||||
Mockery::on(static fn (array $data): bool => $data['options'] === '["Beginner","Advanced"]'),
|
||||
Mockery::type('array')
|
||||
);
|
||||
|
||||
$this->db->insert_id = 22;
|
||||
|
||||
$question = new Question(
|
||||
offeringId: 7,
|
||||
label: 'Pick a level',
|
||||
fieldType: Question::FIELD_SELECT,
|
||||
options: ['Beginner', 'Advanced'],
|
||||
);
|
||||
|
||||
self::assertSame(22, $this->repo->insert($question));
|
||||
}
|
||||
|
||||
public function testUpdateReturnsTrueOnSuccess(): void
|
||||
{
|
||||
$this->db->shouldReceive('update')
|
||||
->once()
|
||||
->with(
|
||||
'wp_us_questions',
|
||||
Mockery::on(static fn (array $data): bool => $data['label'] === 'Renamed' && $data['is_required'] === 1),
|
||||
['id' => 5],
|
||||
Mockery::type('array'),
|
||||
['%d']
|
||||
)
|
||||
->andReturn(1);
|
||||
|
||||
$question = new Question(7, 'Renamed', isRequired: true, id: 5);
|
||||
|
||||
self::assertTrue($this->repo->update(5, $question));
|
||||
}
|
||||
|
||||
public function testFindByOfferingActiveOnlyPreparesQuery(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')
|
||||
->once()
|
||||
->with(
|
||||
Mockery::pattern('/offering_id = %d AND is_active = %d/'),
|
||||
Mockery::on(static fn (array $p): bool => $p === [7, 1])
|
||||
)
|
||||
->andReturn('SELECT ...');
|
||||
|
||||
$this->db->shouldReceive('get_results')->andReturn([]);
|
||||
|
||||
self::assertSame([], $this->repo->findByOffering(7, activeOnly: true));
|
||||
}
|
||||
|
||||
public function testFindByOfferingReturnsQuestions(): void
|
||||
{
|
||||
$row = (object) [
|
||||
'id' => '3',
|
||||
'offering_id' => '7',
|
||||
'label' => 'Q',
|
||||
'field_type' => Question::FIELD_TEXT,
|
||||
'options' => null,
|
||||
'is_required' => '0',
|
||||
'sort_order' => '0',
|
||||
'is_active' => '1',
|
||||
];
|
||||
|
||||
$this->db->shouldReceive('prepare')->andReturn('SELECT ...');
|
||||
$this->db->shouldReceive('get_results')->andReturn([$row]);
|
||||
|
||||
$questions = $this->repo->findByOffering(7);
|
||||
|
||||
self::assertCount(1, $questions);
|
||||
self::assertInstanceOf(Question::class, $questions[0]);
|
||||
}
|
||||
|
||||
public function testFindByIdReturnsNullWhenNotFound(): void
|
||||
{
|
||||
$this->db->shouldReceive('prepare')->andReturn('SELECT ...');
|
||||
$this->db->shouldReceive('get_row')->andReturn(null);
|
||||
|
||||
self::assertNull($this->repo->findById(99));
|
||||
}
|
||||
|
||||
public function testDeleteCallsWpdbDelete(): void
|
||||
{
|
||||
$this->db->shouldReceive('delete')
|
||||
->once()
|
||||
->with('wp_us_questions', ['id' => 4], ['%d'])
|
||||
->andReturn(1);
|
||||
|
||||
self::assertTrue($this->repo->delete(4));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Unsupervised\Schedular\Tests\Unit\Registration;
|
||||
|
||||
use Unsupervised\Schedular\Registration\Question;
|
||||
use Unsupervised\Schedular\Tests\Unit\TestCase;
|
||||
|
||||
class QuestionTest extends TestCase
|
||||
{
|
||||
public function testConstructorAndDefaults(): void
|
||||
{
|
||||
$question = new Question(7, 'Your level?');
|
||||
|
||||
self::assertSame(7, $question->offeringId);
|
||||
self::assertSame('Your level?', $question->label);
|
||||
self::assertSame(Question::FIELD_TEXT, $question->fieldType);
|
||||
self::assertNull($question->options);
|
||||
self::assertFalse($question->isRequired);
|
||||
self::assertSame(0, $question->sortOrder);
|
||||
self::assertTrue($question->isActive);
|
||||
self::assertNull($question->id);
|
||||
}
|
||||
|
||||
public function testFromRowDecodesOptionsJson(): void
|
||||
{
|
||||
$row = (object) [
|
||||
'id' => '3',
|
||||
'offering_id' => '7',
|
||||
'label' => 'Pick a level',
|
||||
'field_type' => Question::FIELD_SELECT,
|
||||
'options' => '["Beginner","Advanced"]',
|
||||
'is_required' => '1',
|
||||
'sort_order' => '2',
|
||||
'is_active' => '1',
|
||||
];
|
||||
|
||||
$question = Question::fromRow($row);
|
||||
|
||||
self::assertSame(3, $question->id);
|
||||
self::assertSame(Question::FIELD_SELECT, $question->fieldType);
|
||||
self::assertSame(['Beginner', 'Advanced'], $question->options);
|
||||
self::assertTrue($question->isRequired);
|
||||
self::assertSame(2, $question->sortOrder);
|
||||
}
|
||||
|
||||
public function testFromRowHandlesNullOptions(): void
|
||||
{
|
||||
$row = (object) [
|
||||
'id' => '4',
|
||||
'offering_id' => '7',
|
||||
'label' => 'Notes',
|
||||
'field_type' => Question::FIELD_TEXTAREA,
|
||||
'options' => null,
|
||||
'is_required' => '0',
|
||||
'sort_order' => '0',
|
||||
'is_active' => '0',
|
||||
];
|
||||
|
||||
$question = Question::fromRow($row);
|
||||
|
||||
self::assertNull($question->options);
|
||||
self::assertFalse($question->isActive);
|
||||
}
|
||||
|
||||
public function testToArrayContainsExpectedKeys(): void
|
||||
{
|
||||
$question = new Question(7, 'Label', Question::FIELD_TEXT, id: 9);
|
||||
$arr = $question->toArray();
|
||||
|
||||
foreach (['id', 'offering_id', 'label', 'field_type', 'options', 'is_required', 'sort_order', 'is_active'] as $key) {
|
||||
self::assertArrayHasKey($key, $arr);
|
||||
}
|
||||
}
|
||||
|
||||
public function testValidFieldTypeConstants(): void
|
||||
{
|
||||
self::assertContains(Question::FIELD_TEXT, Question::VALID_FIELD_TYPES);
|
||||
self::assertContains(Question::FIELD_TEXTAREA, Question::VALID_FIELD_TYPES);
|
||||
self::assertContains(Question::FIELD_SELECT, Question::VALID_FIELD_TYPES);
|
||||
self::assertContains(Question::FIELD_CHECKBOX, Question::VALID_FIELD_TYPES);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user