Files
eventLabs/includes/class-clubs.php
josh 1b5c8a1ff5
All checks were successful
WordPress release / release (push) Successful in 6s
Add sub-club selection to the WordPress event editor
2026-11-12 15:10:53 -05:00

210 lines
8.3 KiB
PHP

<?php
namespace BurnEvents;
use RuntimeException;
use WP_REST_Request;
use WP_Term;
defined( 'ABSPATH' ) || exit;
final class Clubs {
public const EVENT_META = '_eventlabs_sub_club';
private const TAXONOMY = 'eventlabs_club_directory';
private const DETAILS = '_eventlabs_club_details';
private const BACKFILL = 'eventlabs_club_backfill';
public static function register(): void {
register_taxonomy( self::TAXONOMY, [], [
'public' => false, 'show_ui' => false, 'show_in_rest' => false, 'rewrite' => false, 'query_var' => false,
] );
register_post_meta( Events::EVENT, self::EVENT_META, [ 'type' => 'string', 'single' => true, 'default' => '', 'show_in_rest' => false ] );
}
public static function register_api(): void {
$base = '/burnworks/workspaces/(?P<workspace_id>' . BurnWorks::UUID . ')/clubs';
register_rest_route( Api::NAMESPACE, $base, [
'methods' => 'GET', 'callback' => [ self::class, 'listing' ], 'permission_callback' => [ Api::class, 'permission' ],
] );
register_rest_route( Api::NAMESPACE, $base . '/(?P<club_id>' . BurnWorks::UUID . ')', [
'methods' => 'PUT', 'callback' => [ self::class, 'put' ], 'permission_callback' => [ Api::class, 'permission' ],
] );
}
public static function schema(): array {
return [
'type' => 'object', 'required' => [ 'name', 'kind' ], 'additionalProperties' => false,
'properties' => [
'name' => [ 'type' => 'string', 'minLength' => 1, 'maxLength' => 120 ],
'kind' => [ 'type' => 'string', 'enum' => [ 'organization', 'subclub' ] ],
'status' => [ 'type' => 'string', 'enum' => [ 'active', 'archived' ] ],
'workspace_name' => [ 'type' => 'string', 'maxLength' => 120 ],
],
];
}
public static function put( WP_REST_Request $request ) {
$input = $request->get_json_params();
$schema = self::schema();
$valid = rest_validate_value_from_schema( $input, $schema, 'body' );
if ( is_wp_error( $valid ) ) {
$valid->add_data( [ 'status' => 400 ] );
return $valid;
}
$params = $request->get_url_params();
$scope = strtolower( $params['workspace_id'] . ':' . $params['club_id'] );
$name = sanitize_text_field( $input['name'] );
if ( '' === $name ) {
return Api::error( 'club_name', __( 'Enter a club name.', 'burn-events' ), 400 );
}
try {
$term = self::ensure( $scope );
$previous = self::record( $term );
$details = [
'name' => $name, 'kind' => $input['kind'], 'status' => $input['status'] ?? $previous['status'],
'workspace_name' => sanitize_text_field( $input['workspace_name'] ?? $previous['workspace_name'] ),
];
$saved = update_term_meta( $term->term_id, self::DETAILS, wp_slash( $details ) );
if ( is_wp_error( $saved ) || $details !== get_term_meta( $term->term_id, self::DETAILS, true ) ) {
throw new RuntimeException( 'Club details write failed.' );
}
return Api::response( self::record( $term ) );
} catch ( \Throwable $error ) {
return Api::error( 'club_write', __( 'The club could not be saved.', 'burn-events' ), 500 );
}
}
public static function listing( WP_REST_Request $request ): \WP_REST_Response {
$workspace = strtolower( $request->get_url_params()['workspace_id'] );
$items = array_values( array_filter( self::directory(), static fn( array $record ): bool => $workspace === $record['workspace_id'] ) );
return Api::response( [ 'items' => $items ] );
}
public static function event( int $id ): ?array {
$term = self::find( (string) get_post_meta( $id, self::EVENT_META, true ) );
return $term ? self::record( $term ) : null;
}
public static function assign( int $id, string $scope, bool $discover = false ): void {
$scope = strtolower( $scope );
if ( '' !== $scope ) {
if ( ! preg_match( '/^' . BurnWorks::UUID . ':' . BurnWorks::UUID . '$/D', $scope ) ) {
throw new \InvalidArgumentException( __( 'Use a burnWorks workspace and club ID for the sub-club.', 'burn-events' ) );
}
if ( $discover ) {
self::ensure( $scope );
} elseif ( ! self::find( $scope ) ) {
throw new \InvalidArgumentException( __( 'Sync this club from burnWorks before assigning it.', 'burn-events' ) );
}
}
Events::write_meta( $id, self::EVENT_META, $scope );
}
private static function slug( string $scope ): string {
return str_replace( ':', '_', $scope );
}
private static function find( string $scope ): ?WP_Term {
$term = $scope ? get_term_by( 'slug', self::slug( $scope ), self::TAXONOMY ) : null;
return $term instanceof WP_Term ? $term : null;
}
private static function ensure( string $scope ): WP_Term {
$term = self::find( $scope );
if ( $term ) {
return $term;
}
wp_insert_term( $scope, self::TAXONOMY, [ 'slug' => self::slug( $scope ) ] );
return self::find( $scope ) ?? throw new RuntimeException( 'Club directory write failed.' );
}
private static function record( WP_Term $term ): array {
[ $workspace, $club ] = explode( '_', $term->slug, 2 );
$details = (array) get_term_meta( $term->term_id, self::DETAILS, true );
return [ 'workspace_id' => $workspace, 'club_id' => $club, 'scope' => $workspace . ':' . $club ] + $details + [
'name' => sprintf( __( 'Club %s', 'burn-events' ), substr( $club, 0, 8 ) ),
'kind' => 'unknown', 'status' => 'active', 'workspace_name' => '',
];
}
private static function directory(): array {
$terms = get_terms( [ 'taxonomy' => self::TAXONOMY, 'hide_empty' => false ] );
return is_array( $terms ) ? array_map( [ self::class, 'record' ], $terms ) : [];
}
public static function options(): array {
$directory = self::directory();
$names = $workspaces = $clubs = [];
foreach ( $directory as $club ) {
if ( $club['workspace_name'] ) {
$names[ $club['workspace_id'] ] = $club['workspace_name'];
}
}
foreach ( $directory as $club ) {
$workspace = $names[ $club['workspace_id'] ] ?? sprintf( __( 'Workspace %s', 'burn-events' ), substr( $club['workspace_id'], 0, 8 ) );
$workspaces[ $club['workspace_id'] ] = sprintf( __( '%s (all clubs)', 'burn-events' ), $workspace );
$label = $workspace . ' / ' . $club['name'];
$clubs[ $club['scope'] ] = 'archived' === $club['status'] ? sprintf( __( '%s (archived)', 'burn-events' ), $label ) : $label;
}
natcasesort( $workspaces );
natcasesort( $clubs );
return [ '' => __( 'All events', 'burn-events' ) ] + $workspaces + $clubs;
}
public static function editor_options(): array {
$options = [];
foreach ( self::directory() as $club ) {
if ( 'archived' !== $club['status'] ) {
$prefix = $club['workspace_name'] ?: sprintf( __( 'Workspace %s', 'burn-events' ), substr( $club['workspace_id'], 0, 8 ) );
$options[ $club['scope'] ] = $prefix . ' / ' . $club['name'];
}
}
natcasesort( $options );
return $options;
}
public static function condition( string $scope ): string {
global $wpdb;
$scope = strtolower( $scope );
if ( ! preg_match( '/^' . BurnWorks::UUID . '(?::' . BurnWorks::UUID . ')?$/D', $scope ) ) {
return '1=0';
}
$exact = str_contains( $scope, ':' );
$operator = $exact ? '=' : 'LIKE';
$value = $exact ? $scope : $wpdb->esc_like( $scope . ':' ) . '%';
return $wpdb->prepare( "EXISTS (SELECT 1 FROM $wpdb->postmeta c WHERE c.post_id = p.ID AND c.meta_key = %s AND c.meta_value $operator %s)", self::EVENT_META, $value );
}
public static function backfill(): void {
global $wpdb;
$cursor = get_option( self::BACKFILL, 0 );
if ( 'done' === $cursor ) {
return;
}
$ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT p.ID FROM $wpdb->posts p JOIN $wpdb->postmeta m ON m.post_id = p.ID AND m.meta_key = %s WHERE p.post_type = %s AND p.ID > %d ORDER BY p.ID LIMIT 50", BurnWorks::META, Events::EVENT, (int) $cursor ) );
if ( $wpdb->last_error ) {
return;
}
foreach ( $ids as $id ) {
try {
Events::transaction( static function () use ( $id ): void {
if ( ! Events::lock_post( (int) $id ) || get_post_meta( $id, self::EVENT_META, true ) ) {
return;
}
$record = BurnWorks::snapshot( (int) $id );
if ( isset( $record['workspace_id'], $record['club_id'] ) ) {
self::assign( (int) $id, $record['workspace_id'] . ':' . $record['club_id'], true );
}
} );
} catch ( \InvalidArgumentException $error ) {
// Ignore snapshots without a valid club identity.
} catch ( \Throwable $error ) {
return;
} finally {
wp_cache_delete( $id, 'post_meta' );
}
}
update_option( self::BACKFILL, count( $ids ) < 50 ? 'done' : (string) end( $ids ), false );
}
}