diff --git a/includes/Admin.php b/includes/Admin.php index 82a3c628e..3da32d8b2 100644 --- a/includes/Admin.php +++ b/includes/Admin.php @@ -1,6 +1,11 @@ $field_args Array of field args. * * * : https://cmb2.io/docs/field-parameters#-default_cb * * @return mixed */ -function commonsbooking_filter_from_cmb2( $field_args ) { +function commonsbooking_filter_from_cmb2( array $field_args ) { // Only return default value if we don't have a post ID (in the 'post' query variable) if ( isset( $_GET['post'] ) ) { // No default value. @@ -260,14 +265,14 @@ function cmb2_set_checkbox_default_for_new_post() { /** * Recursive sanitation for text or array * - * @param array|string $data + * @param array|string $data * @param string $sanitizeFunction name of the sanitziation function, default = sanitize_text_field. You can use any method that accepts a string as parameter * * See more wordpress sanitization functions: https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/ * - * @return array|string + * @return array|string */ -function commonsbooking_sanitizeArrayorString( $data, $sanitizeFunction = 'sanitize_text_field' ) { +function commonsbooking_sanitizeArrayorString( array|string $data, string $sanitizeFunction = 'sanitize_text_field' ): array|string { if ( is_array( $data ) ) { foreach ( $data as $key => $value ) { $data[ $key ] = commonsbooking_sanitizeArrayorString( $value, $sanitizeFunction ); diff --git a/includes/Public.php b/includes/Public.php index 196680c54..63a0fd9e8 100644 --- a/includes/Public.php +++ b/includes/Public.php @@ -7,7 +7,12 @@ use CommonsBooking\View\View; -function commonsbooking_public() { +/** + * Enqueue scripts and styles for public-facing pages. + * + * @return void + */ +function commonsbooking_public(): void { wp_enqueue_style( 'cb-styles-public', @@ -143,8 +148,13 @@ function commonsbooking_public() { add_action( 'wp_ajax_cb_map_geo_search', array( MapData::class, 'geo_search' ) ); add_action( 'wp_ajax_nopriv_cb_map_geo_search', array( MapData::class, 'geo_search' ) ); -// Query vars -function commonsbooking_query_vars( $qvars ) { +/** + * Register custom query vars for CommonsBooking. + * + * @param string[] $qvars Existing query vars. + * @return string[] + */ +function commonsbooking_query_vars( array $qvars ): array { $qvars[] = 'cb-location'; $qvars[] = 'cb-item'; $qvars[] = 'cb-type'; diff --git a/includes/Shortcodes.php b/includes/Shortcodes.php index a4a750439..22b094c26 100644 --- a/includes/Shortcodes.php +++ b/includes/Shortcodes.php @@ -1,6 +1,12 @@ |string $atts Shortcode attributes. + * @return string + */ +function commonsbooking_tag( array|string $atts ): string { $atts = shortcode_atts( array( 'tag' => '', @@ -9,7 +15,7 @@ function commonsbooking_tag( $atts ) { 'cb' ); - echo commonsbooking_sanitizeHTML( commonsbooking_parse_shortcode( $atts['tag'] ) ); + return commonsbooking_sanitizeHTML( commonsbooking_parse_shortcode( $atts['tag'] ) ); } add_shortcode( 'cb', 'commonsbooking_tag' ); diff --git a/includes/TemplateParser.php b/includes/TemplateParser.php index 9e52a4a22..1470f6811 100644 --- a/includes/TemplateParser.php +++ b/includes/TemplateParser.php @@ -6,12 +6,12 @@ * Parses templates and extracts the template tags used in e-mail templates: {{xxx:yyyy}} * * @param string $template - * @param array $objects + * @param array $objects * @param callable $sanitizeFunction The callable used to remove unwanted tags/characters (use default 'commonsbooking_sanitizeHTML' or 'sanitize_text_field') * * @return mixed */ -function commonsbooking_parse_template( string $template = '', $objects = [], $sanitizeFunction = 'commonsbooking_sanitizeHTML' ) { +function commonsbooking_parse_template( string $template = '', array $objects = [], $sanitizeFunction = 'commonsbooking_sanitizeHTML' ) { $template = preg_replace_callback( '/\{{.*?\}}/', function ( $match ) use ( $objects, $sanitizeFunction ) { @@ -40,7 +40,13 @@ function ( $match ) use ( $objects, $sanitizeFunction ) { } } -function commonsbooking_parse_shortcode( $tag ) { +/** + * Parses a single shortcode tag. + * + * @param string $tag + * @return mixed + */ +function commonsbooking_parse_shortcode( string $tag ) { $tag = (array) $tag; return commonsbooking_parse_template_callback( $tag ); } @@ -52,7 +58,7 @@ function commonsbooking_parse_shortcode( $tag ) { * Example: {{[this comes before: ]item:post_title[this comes after]}} * * @param mixed $match - * @param array $objects + * @param array $objects * @param callable $sanitizeFunction The callable used to remove unwanted tags/characters * * @return false|mixed diff --git a/includes/Users.php b/includes/Users.php index c3220544b..4f42448dd 100644 --- a/includes/Users.php +++ b/includes/Users.php @@ -7,12 +7,12 @@ /** * Checks if current user is allowed to edit custom post. * - * @param $post + * @param \WP_Post|int $post * * @return bool * @throws Exception */ -function commonsbooking_isCurrentUserAllowedToEdit( $post ): bool { +function commonsbooking_isCurrentUserAllowedToEdit( \WP_Post|int $post ): bool { if ( ! is_user_logged_in() ) { return false; } @@ -24,13 +24,13 @@ function commonsbooking_isCurrentUserAllowedToEdit( $post ): bool { /** * Checks if user is allowed to edit custom post. * - * @param $post - * @param $user + * @param \WP_Post|int $post + * @param WP_User $user * * @return bool * @throws Exception */ -function commonsbooking_isUserAllowedToEdit( $post, WP_User $user ): bool { +function commonsbooking_isUserAllowedToEdit( \WP_Post|int $post, WP_User $user ): bool { if ( ! Plugin::isPostCustomPostType( $post ) ) { return false; @@ -52,9 +52,10 @@ function commonsbooking_isUserAllowedToEdit( $post, WP_User $user ): bool { /** * Validates if current user is allowed to edit current post in admin. * - * @param $current_screen + * @param \WP_Screen $current_screen + * @return void */ -function commonsbooking_validate_user_on_edit( $current_screen ) { +function commonsbooking_validate_user_on_edit( \WP_Screen $current_screen ): void { if ( $current_screen->base == 'post' && in_array( $current_screen->id, Plugin::getCustomPostTypesLabels() ) ) { if ( array_key_exists( 'action', $_GET ) && $_GET['action'] == 'edit' ) { $post = get_post( intval( $_GET['post'] ) ); @@ -127,14 +128,25 @@ function ( $posts, $query ) { add_filter( 'views_edit-' . $custom_post_type, 'commonsbooking_custom_view_count', 10, 1 ); } -// Filter function for fix of counts in admin lists for custom post types. -function commonsbooking_custom_view_count( $views ) { +/** + * Filter function for fix of counts in admin lists for custom post types. + * + * @param array $views + * @return array + */ +function commonsbooking_custom_view_count( array $views ): array { global $current_screen; return commonsbooking_fix_view_counts( str_replace( 'edit-', '', $current_screen->id ), $views ); } -// fixes counts for custom posts countings in admin list -function commonsbooking_fix_view_counts( $postType, $views ) { +/** + * Fixes counts for custom posts countings in admin list. + * + * @param string $postType + * @param array $views + * @return array + */ +function commonsbooking_fix_view_counts( string $postType, array $views ): array { // admin is allowed to see all posts if ( commonsbooking_isCurrentUserAdmin() ) { return $views; @@ -165,8 +177,12 @@ function commonsbooking_fix_view_counts( $postType, $views ) { return array_intersect_key( $views, $counts ); } -// Check if current user has admin role -function commonsbooking_isCurrentUserAdmin() { +/** + * Check if current user has admin role. + * + * @return bool + */ +function commonsbooking_isCurrentUserAdmin(): bool { if ( ! is_user_logged_in() ) { return false; } $user = wp_get_current_user(); @@ -225,8 +241,12 @@ function commonsbooking_isUserCBManager( \WP_User $user ): bool { return apply_filters( 'commonsbooking_isCurrentUserCBManager', $isManager, $user ); } -// Check if current user has subscriber role -function commonsbooking_isCurrentUserSubscriber() { +/** + * Check if current user has subscriber role. + * + * @return bool + */ +function commonsbooking_isCurrentUserSubscriber(): bool { $user = wp_get_current_user(); $isSubscriber = in_array( 'subscriber', $user->roles ); @@ -340,12 +360,12 @@ function commonsbooking_isUserAllowedToSee( $post, WP_User $user ): bool { * * Used by Service\iCalendar for authentication. * - * @param $user_id - * @param $user_hash + * @param int|string $user_id + * @param string $user_hash * * @return bool */ -function commonsbooking_isUIDHashComboCorrect( $user_id, $user_hash ): bool { +function commonsbooking_isUIDHashComboCorrect( int|string $user_id, string $user_hash ): bool { if ( wp_hash( $user_id ) == $user_hash ) { return true; } else { diff --git a/phpstan.neon b/phpstan.neon index 913034c5c..863cae154 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -13,7 +13,7 @@ parameters: - commonsbooking.php - src/ - includes/ - level: 5 + level: 6 ignoreErrors: - '#Constant (COMMONSBOOKING.*|WP_DEBUG_LOG) not found.#' # - '#Instantiated class (CommonsBooking.*CB_Data) not found.#' diff --git a/src/API/AvailabilityRoute.php b/src/API/AvailabilityRoute.php index 026256be6..9df470a01 100644 --- a/src/API/AvailabilityRoute.php +++ b/src/API/AvailabilityRoute.php @@ -38,9 +38,9 @@ class AvailabilityRoute extends BaseRoute { /** * This retrieves bookable timeframes and the different items assigned, with their respective availability. * - * @param bool $id The id of a {@see \CommonsBooking\Wordpress\CustomPostType\Item::post_type} post to search for + * @param bool|int $id The id of a {@see \CommonsBooking\Wordpress\CustomPostType\Item::post_type} post to search for * - * @return array + * @return array * @throws Exception */ public function getItemData( $id = false ): array { @@ -57,11 +57,11 @@ public function getItemData( $id = false ): array { /** * Get one item from the collection * - * @param $request WP_REST_Request + * @param WP_REST_Request> $request * * @return WP_REST_Response|WP_Error */ - public function get_item( $request ) { + public function get_item( WP_REST_Request $request ) { // get parameters from request $params = $request->get_params(); $data = new stdClass(); @@ -76,11 +76,11 @@ public function get_item( $request ) { /** * Get a collection of items * - * @param $request WP_REST_Request full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_REST_Response */ - public function get_items( $request ) { + public function get_items( WP_REST_Request $request ) { $data = new stdClass(); $data->availability = []; diff --git a/src/API/BaseRoute.php b/src/API/BaseRoute.php index 5e13be79d..4e171fe0d 100644 --- a/src/API/BaseRoute.php +++ b/src/API/BaseRoute.php @@ -35,12 +35,13 @@ class BaseRoute extends WP_REST_Controller { // the location of the .schema.json files locally const SCHEMA_PATH = COMMONSBOOKING_PLUGIN_DIR . 'includes/commons-api-json-schema/'; + /** @var string */ protected $schemaUrl; /** * Register the routes for the objects of the controller. */ - public function register_routes() { + public function register_routes(): void { $version = '1'; $namespace = COMMONSBOOKING_PLUGIN_SLUG . '/v' . $version; register_rest_route( @@ -96,7 +97,7 @@ public function register_routes() { * * @param object $data instance of stdclass or object to validate. */ - public function validateData( $data ) { + public function validateData( $data ): void { $validator = new Validator(); // Opis does not fetch remote $ref targets in getSchemaJson() main schema. @@ -158,8 +159,8 @@ private function getSchemaJson(): string { /** * Adds schema-fields for output to current route (needed for /.../schema endpoint) * - * @param array $schema Assoc array of schema json object. - * @return array + * @param array $schema Assoc array of schema json object. + * @return array */ public function add_additional_fields_schema( $schema ): array { $schemaArray = json_decode( $this->getSchemaJson(), true ); @@ -170,11 +171,11 @@ public function add_additional_fields_schema( $schema ): array { /** * Escapes JSON String for output. * - * @param $string + * @param string $string * - * @return false|string + * @return string */ - public function escapeJsonString( $string ) { + public function escapeJsonString( string $string ): string { return substr( wp_json_encode( $string ), 1, - 1 ) ? : ''; } diff --git a/src/API/GBFS/BaseRoute.php b/src/API/GBFS/BaseRoute.php index f44c3ecfc..1259ecc05 100644 --- a/src/API/GBFS/BaseRoute.php +++ b/src/API/GBFS/BaseRoute.php @@ -21,11 +21,11 @@ class BaseRoute extends \CommonsBooking\API\BaseRoute { /** * Returns Rest Response with items. * - * @param WP_REST_Request $request + * @param WP_REST_Request> $request * * @return WP_REST_Response */ - public function get_items( $request ): WP_REST_Response { + public function get_items( WP_REST_Request $request ): WP_REST_Response { $response = new stdClass(); $response->data = new stdClass(); $response->data->stations = $this->getItemData( $request ); @@ -43,11 +43,11 @@ public function get_items( $request ): WP_REST_Response { /** * Returns item data array. * - * @param $request + * @param WP_REST_Request> $request * - * @return array + * @return array */ - public function getItemData( $request ): array { + public function getItemData( WP_REST_Request $request ): array { $data = []; $locations = Location::get(); diff --git a/src/API/GBFS/Discovery.php b/src/API/GBFS/Discovery.php index 0a31b16e9..e4aea0fae 100644 --- a/src/API/GBFS/Discovery.php +++ b/src/API/GBFS/Discovery.php @@ -53,7 +53,7 @@ public function get_items( $request ): WP_REST_Response { return new WP_REST_Response( $response, 200 ); } - private function get_feed( $name ): stdClass { + private function get_feed( string $name ): stdClass { $feed = new stdClass(); $feed->name = $name; $feed->url = get_rest_url() . 'commonsbooking/v1/' . $name . '.json'; diff --git a/src/API/GBFS/StationInformation.php b/src/API/GBFS/StationInformation.php index 807cffaee..dd03a0a03 100644 --- a/src/API/GBFS/StationInformation.php +++ b/src/API/GBFS/StationInformation.php @@ -26,8 +26,8 @@ class StationInformation extends BaseRoute { protected $schemaUrl = COMMONSBOOKING_PLUGIN_DIR . 'includes/gbfs-json-schema/station_information.json'; /** - * @param $item Location - * @param $request + * @param Location $item + * @param WP_REST_Request> $request * * @return WP_REST_Response * @throws \CommonsBooking\Geocoder\Exception\Exception diff --git a/src/API/GBFS/StationStatus.php b/src/API/GBFS/StationStatus.php index 85221c454..dc5b3524b 100644 --- a/src/API/GBFS/StationStatus.php +++ b/src/API/GBFS/StationStatus.php @@ -29,7 +29,7 @@ class StationStatus extends BaseRoute { /** * @param Location $item - * @param $request + * @param WP_REST_Request> $request * * @return WP_REST_Response * @throws \Exception @@ -58,7 +58,7 @@ public function prepare_item_for_response( $item, $request ): WP_REST_Response { * @return int * @throws \Exception */ - private function getItemCountAtLocation( $locationId ): int { + private function getItemCountAtLocation( int $locationId ): int { $items = Item::getByLocation( $locationId, true ); $nowDT = Wordpress::getUTCDateTimeByTimestamp( current_time( 'timestamp' ) ); $availableCounter = 0; diff --git a/src/API/GBFS/SystemInformation.php b/src/API/GBFS/SystemInformation.php index 7eb4e4ad1..e4a4bce6b 100644 --- a/src/API/GBFS/SystemInformation.php +++ b/src/API/GBFS/SystemInformation.php @@ -22,7 +22,10 @@ class SystemInformation extends \CommonsBooking\API\BaseRoute { */ protected $schemaUrl = COMMONSBOOKING_PLUGIN_DIR . 'includes/gbfs-json-schema/system_information.json'; - public function get_items( $request ): WP_REST_Response { + /** + * @param WP_REST_Request> $request + */ + public function get_items( \WP_REST_Request $request ): WP_REST_Response { $tz = timezone_name_get( wp_timezone() ); if ( preg_match( '/^(\+|\-)0?(\d+)/', $tz, $matches ) ) { $tz = 'Etc/GMT' . $matches[1] . $matches[2]; diff --git a/src/API/ItemsRoute.php b/src/API/ItemsRoute.php index d8aa3b8c0..c34dd4723 100644 --- a/src/API/ItemsRoute.php +++ b/src/API/ItemsRoute.php @@ -33,11 +33,11 @@ class ItemsRoute extends BaseRoute { /** * Returns raw data collection. * - * @param $request + * @param WP_REST_Request> $request * * @return stdClass */ - public function getItemData( $request ): stdClass { + public function getItemData( WP_REST_Request $request ): stdClass { $data = new stdClass(); $data->items = []; @@ -61,11 +61,11 @@ public function getItemData( $request ): stdClass { /** * Get a collection of items * - * @param $request - Full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_Error|WP_REST_Response */ - public function get_items( $request ) { + public function get_items( WP_REST_Request $request ) { // get parameters from request $params = $request->get_params(); @@ -104,23 +104,23 @@ public function get_items( $request ) { /** * Get one item from the collection * - * @param WP_REST_Request $request Full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_REST_Response */ - public function get_item( $request ): WP_REST_Response { + public function get_item( WP_REST_Request $request ): WP_REST_Response { $data = $this->getItemData( $request ); return $this->respond_with_validation( $data ); } /** - * @param mixed $item - * @param WP_REST_Request $request + * @param mixed $item + * @param WP_REST_Request> $request * * @return WP_REST_Response */ - public function prepare_item_for_response( $item, $request ): WP_REST_Response { + public function prepare_item_for_response( $item, WP_REST_Request $request ): WP_REST_Response { $preparedItem = new stdClass(); $preparedItem->id = $item->ID . ''; $preparedItem->name = $item->post_title; diff --git a/src/API/LocationsRoute.php b/src/API/LocationsRoute.php index c429278f0..8d4ea8c9e 100644 --- a/src/API/LocationsRoute.php +++ b/src/API/LocationsRoute.php @@ -37,29 +37,33 @@ class LocationsRoute extends BaseRoute { /** * Get one item from the collection * - * @param WP_REST_Request $request Full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_Error|WP_REST_Response */ - public function get_item( $request ) { + public function get_item( WP_REST_Request $request ) { return $this->get_items( $request ); } /** * Get a collection of items * - * @param WP_REST_Request $request Full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_Error|WP_REST_Response */ - public function get_items( $request ) { + public function get_items( WP_REST_Request $request ) { $data = new stdClass(); $data->locations = $this->getItemData( $request ); return $this->respond_with_validation( $data ); } - public function getItemData( $request ) { + /** + * @param WP_REST_Request> $request + * @return stdClass + */ + public function getItemData( WP_REST_Request $request ): stdClass { $data = new stdClass(); $data->type = 'FeatureCollection'; @@ -91,13 +95,13 @@ public function getItemData( $request ) { } /** - * @param $item Location - * @param $request + * @param Location $item + * @param WP_REST_Request> $request * * @return WP_REST_Response * @throws \CommonsBooking\Geocoder\Exception\Exception */ - public function prepare_item_for_response( $item, $request ): WP_REST_Response { + public function prepare_item_for_response( $item, WP_REST_Request $request ): WP_REST_Response { $preparedItem = new stdClass(); $preparedItem->type = 'Feature'; $preparedItem->properties = new stdClass(); diff --git a/src/API/OwnersRoute.php b/src/API/OwnersRoute.php index 0876d9ea5..e7603e162 100644 --- a/src/API/OwnersRoute.php +++ b/src/API/OwnersRoute.php @@ -38,11 +38,11 @@ class OwnersRoute extends BaseRoute { /** * Returns raw data collection. * - * @param $request + * @param WP_REST_Request> $request * - * @return array + * @return array */ - public function getItemData( $request ): array { + public function getItemData( WP_REST_Request $request ): array { $data = []; foreach ( UserRepository::getOwners() as $owner ) { @@ -53,12 +53,12 @@ public function getItemData( $request ): array { } /** - * @param WP_User $owner - * @param WP_REST_Request $request + * @param WP_User $owner + * @param WP_REST_Request> $request * * @return WP_REST_Response */ - public function prepare_item_for_response( $owner, $request ): WP_REST_Response { + public function prepare_item_for_response( $owner, WP_REST_Request $request ): WP_REST_Response { $ownerObject = new stdClass(); $ownerObject->id = '' . $owner->ID; $ownerObject->name = get_user_meta( $owner->ID, 'first_name', true ) . ' ' . get_user_meta( $owner->ID, 'last_name', true ); @@ -85,8 +85,10 @@ public function prepare_item_for_response( $owner, $request ): WP_REST_Response /** * Get a single item + * + * @param WP_REST_Request> $request */ - public function get_item( $request ): WP_REST_Response { + public function get_item( WP_REST_Request $request ): WP_REST_Response { // get parameters from request $params = $request->get_params(); $owner = get_user_by( 'id', $params['id'] ); @@ -99,11 +101,11 @@ public function get_item( $request ): WP_REST_Response { /** * Get a collection of items * - * @param WP_REST_Request $request Full data about the request. + * @param WP_REST_Request> $request Full data about the request. * * @return WP_Error|WP_REST_Response */ - public function get_items( $request ) { + public function get_items( WP_REST_Request $request ) { $data = new stdClass(); $data->owners = $this->getItemData( $request ); @@ -112,8 +114,11 @@ public function get_items( $request ) { /** * TODO investigate why we overwrite this method + * + * @param WP_REST_Response $itemdata + * @return WP_REST_Response */ - public function prepare_response_for_collection( $itemdata ) { - return $itemdata; // @phpstan-ignore return.type + public function prepare_response_for_collection( $itemdata ): WP_REST_Response { + return $itemdata; } } diff --git a/src/API/ProjectsRoute.php b/src/API/ProjectsRoute.php index 6f1866357..62b344341 100644 --- a/src/API/ProjectsRoute.php +++ b/src/API/ProjectsRoute.php @@ -30,15 +30,19 @@ class ProjectsRoute extends BaseRoute { /** * Get one item from the collection + * + * @param WP_REST_Request> $request */ - public function get_item( $request ) { + public function get_item( \WP_REST_Request $request ) { return $this->get_items( $request ); } /** * Get a collection of projects + * + * @param WP_REST_Request> $request */ - public function get_items( $request ): WP_REST_Response { + public function get_items( \WP_REST_Request $request ): WP_REST_Response { $data = new stdClass(); $data->projects = $this->getItemData(); diff --git a/src/API/Share.php b/src/API/Share.php index 25f41d255..a4238dd60 100644 --- a/src/API/Share.php +++ b/src/API/Share.php @@ -12,26 +12,31 @@ */ class Share { + /** @var string */ private $name; + /** @var bool */ private $enabled; + /** @var string */ private $pushUrl; + /** @var string */ private $key; + /** @var string */ private $owner; /** * Shares constructor. * - * @param $name - * @param $enabled - * @param $pushUrl - * @param $key - * @param $owner + * @param string $name + * @param string $enabled + * @param string $pushUrl + * @param string $key + * @param string $owner */ - public function __construct( $name, $enabled, $pushUrl, $key, $owner ) { + public function __construct( string $name, string $enabled, string $pushUrl, string $key, string $owner ) { $this->name = $name; $this->enabled = $enabled === 'on'; $this->pushUrl = $pushUrl; diff --git a/src/CB/CB.php b/src/CB/CB.php index 0cc8bb932..ccefea708 100644 --- a/src/CB/CB.php +++ b/src/CB/CB.php @@ -12,7 +12,7 @@ class CB { - protected static $INTERNAL_DATE_FORMAT = 'd.m.Y'; + protected static string $INTERNAL_DATE_FORMAT = 'd.m.Y'; public static function getInternalDateFormat(): string { return static::$INTERNAL_DATE_FORMAT; @@ -123,7 +123,7 @@ private static function getPostId( string $key ): ?int { * @return string|null * @throws Exception */ - public static function lookUp( string $key, string $property, $post, $args, $sanitizeFunction ): ?string { + public static function lookUp( string $key, string $property, mixed $post, mixed $args, callable $sanitizeFunction ): ?string { // in any case we need the post object, otherwise we cannot return anything if ( ! $post ) { return null; @@ -152,7 +152,7 @@ public static function lookUp( string $key, string $property, $post, $args, $san * * @return mixed|null */ - private static function getPostProperty( $post, $property, $args ) { + private static function getPostProperty( mixed $post, string $property, mixed $args ): mixed { $result = null; $postId = is_int( $post ) ? $post : $post->ID; @@ -187,7 +187,7 @@ private static function getPostProperty( $post, $property, $args ) { * @return int|mixed|null * @throws Exception */ - private static function getUserProperty( $post, string $property, $args ) { + private static function getUserProperty( \WP_Post|\WP_User $post, string $property, mixed $args ): mixed { $result = null; $cb_user = self::getUserFromObject( $post ); @@ -213,7 +213,7 @@ private static function getUserProperty( $post, string $property, $args ) { * @return false|WP_User * @throws Exception */ - private static function getUserFromObject( $object ) { + private static function getUserFromObject( mixed $object ): \WP_User|false { // Check if $post is of type WP_Post, then we're using Author as User if ( $object instanceof WP_Post ) { $userID = intval( $object->post_author ); diff --git a/src/CB/CB1UserFields.php b/src/CB/CB1UserFields.php index ab13df649..58566e37d 100644 --- a/src/CB/CB1UserFields.php +++ b/src/CB/CB1UserFields.php @@ -19,7 +19,7 @@ class CB1UserFields { */ private array $registration_fields; /** - * @var array|array[] + * @var array> */ private array $extra_profile_fields; /** @@ -27,7 +27,7 @@ class CB1UserFields { */ private array $registration_fields_required; // @phpstan-ignore property.onlyWritten /** - * @var array|array[] + * @var array> */ private array $user_fields; /** @@ -116,7 +116,7 @@ public function __construct() { /** * Get the additional User fields * - * @return array + * @return array> * @since 0.6. */ public function get_extra_profile_fields(): array { @@ -131,7 +131,7 @@ public function get_extra_profile_fields(): array { * @return object */ - public function registration_add_fields() { + public function registration_add_fields(): void { foreach ( $this->user_fields as $field ) { $row = ( ! empty( $_POST[ $field['field_name'] ] ) ) ? sanitize_text_field( trim( $_POST[ $field['field_name'] ] ) ) : ''; @@ -195,7 +195,7 @@ public function get_termsservices_string(): string { return $string; } - public function registration_set_errors( $errors, $username, $email ) { + public function registration_set_errors( \WP_Error $errors, string $username, string $email ): \WP_Error { foreach ( $this->user_fields as $field ) { if ( $field['type'] == 'checkbox' ) { @@ -212,7 +212,7 @@ public function registration_set_errors( $errors, $username, $email ) { return $errors; } - public function registration_add_meta( $user_id ) { + public function registration_add_meta( int $user_id ): void { foreach ( $this->user_fields as $field ) { if ( ! empty( $_POST[ $field['field_name'] ] ) ) { @@ -229,7 +229,7 @@ public function registration_add_meta( $user_id ) { * @since 2.10 deprecated (cb_object_to_array is unspecified) * @since 0.6 */ - public function set_basic_user_vars( $user_id ) { + public function set_basic_user_vars( int $user_id ): void { $user_basic = get_user_by( 'id', $user_id ); $user_meta = get_user_meta( $user_id ); @@ -250,7 +250,7 @@ public function set_basic_user_vars( $user_id ) { * * @since 0.5.3 */ - public function add_user_vars( $key, $value ) { + public function add_user_vars( string $key, mixed $value ): void { $this->user_vars[ $key ] = $value; } @@ -260,7 +260,7 @@ public function add_user_vars( $key, $value ) { * * @since 0.2 */ - public function show_extra_profile_fields( $user ) { + public function show_extra_profile_fields( \WP_User $user ): void { ?> @@ -306,7 +306,7 @@ class="regular-text"/>
* * @since 0.2 */ - public function save_extra_profile_fields( $user_id ) { + public function save_extra_profile_fields( int $user_id ): void { if ( current_user_can( 'edit_user', $user_id ) ) { $phone = sanitize_text_field( $_POST['phone'] ); $address = sanitize_text_field( $_POST['address'] ); diff --git a/src/Helper/API.php b/src/Helper/API.php index e678fb476..06949a583 100644 --- a/src/Helper/API.php +++ b/src/Helper/API.php @@ -12,7 +12,7 @@ class API { /** * Triggers requests to all shares with push url. */ - public static function triggerPushUrls() { + public static function triggerPushUrls(): void { $apiShares = ApiShares::getAll(); foreach ( $apiShares as $apiShare ) { @@ -27,7 +27,7 @@ public static function triggerPushUrls() { * * @param Share $share */ - public static function triggerPushUrl( Share $share ) { + public static function triggerPushUrl( Share $share ): void { $requestData = [ 'API_KEY' => $share->getKey(), 'OWNER' => $share->getOwner(), diff --git a/src/Helper/Helper.php b/src/Helper/Helper.php index d8f57cb72..fbc8ebf50 100644 --- a/src/Helper/Helper.php +++ b/src/Helper/Helper.php @@ -80,11 +80,11 @@ public static function getLastFullHourTimestamp() { /** * Returns timestamp of last full day, needed to get more cache hits. * - * @param $timestamp + * @param int|null $timestamp * - * @return int|mixed|null + * @return int */ - public static function getLastFullDayTimestamp( $timestamp = null ) { + public static function getLastFullDayTimestamp( ?int $timestamp = null ): int { if ( $timestamp === null ) { $timestamp = current_time( 'timestamp' ); } @@ -95,13 +95,13 @@ public static function getLastFullDayTimestamp( $timestamp = null ) { /** * Returns CB custom post type if possible. * - * @param $post - * @param $type + * @param mixed $post + * @param string $type * * @return Booking|Item|Location|mixed * @throws \Exception */ - public static function castToCBCustomType( $post, $type ) { + public static function castToCBCustomType( mixed $post, string $type ): mixed { if ( $type == \CommonsBooking\Wordpress\CustomPostType\Booking::$postType ) { $post = new Booking( $post->ID ); } @@ -121,9 +121,9 @@ public static function castToCBCustomType( $post, $type ) { * NOTE: When performance issues arise, this operation can be implemented * faster with an interval tree data structure * - * @param array $array_of_ranges Array of one or more ranges. + * @param array> $array_of_ranges Array of one or more ranges. * - * @return array - Array of overlapping ranges. + * @return array> Array of overlapping ranges. */ public static function mergeRangesToBookableDates( array $array_of_ranges ): array { $interval_open = function ( $interval_value ): bool { diff --git a/src/Helper/Wordpress.php b/src/Helper/Wordpress.php index 43256ccde..cb328323f 100644 --- a/src/Helper/Wordpress.php +++ b/src/Helper/Wordpress.php @@ -13,7 +13,7 @@ class Wordpress { /** - * @return array + * @return array */ public static function getPageListTitle(): array { $pages = get_pages(); @@ -31,11 +31,11 @@ public static function getPageListTitle(): array { /** * Flatten array and return it. * - * @param $posts + * @param object[] $posts * - * @return array|array[]|null[]|\WP_Post[] + * @return array */ - public static function flattenWpdbResult( $posts ): array { + public static function flattenWpdbResult( array $posts ): array { return array_map( function ( $post ) { return get_post( $post->ID ); @@ -45,22 +45,22 @@ function ( $post ) { } /** - * @param $dateString + * @param string $dateString * - * @return bool|false + * @return bool */ - public static function isValidDateString( $dateString ): bool { + public static function isValidDateString( string $dateString ): bool { return preg_match( '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/i', $dateString ) === 1; } /** * Returns array with IDs. * - * @param $posts + * @param object[] $posts * - * @return array + * @return int[] */ - public static function getPostIdArray( $posts ): array { + public static function getPostIdArray( array $posts ): array { return array_map( function ( $post ) { return intval( $post->ID ); @@ -73,11 +73,11 @@ function ( $post ) { * Returns all post ids which are in relation to $postId. * Why? Needed to get tags for cache invalidation. * - * @param $postId + * @param int $postId * - * @return array|string[] + * @return string[] */ - public static function getRelatedPostIds( $postId ): array { + public static function getRelatedPostIds( int $postId ): array { $postIds = []; $post = get_post( $postId ); @@ -108,12 +108,12 @@ public static function getRelatedPostIds( $postId ): array { /** * Returns all post ids in relation to $postId. * - * @param $postId + * @param int $postId * - * @return mixed + * @return int[] * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ - public static function getRelatedPostsIdsForLocation( $postId ) { + public static function getRelatedPostsIdsForLocation( int $postId ): array { $timeframes = \CommonsBooking\Repository\Timeframe::get( [ $postId ] ); $restrictions = \CommonsBooking\Repository\Restriction::get( [ $postId ] ); return array_merge( @@ -127,12 +127,12 @@ public static function getRelatedPostsIdsForLocation( $postId ) { * Returns all post ids in relation to $postId. * CAREFUL: This will not get the location that the item is in relation to. * - * @param $postId + * @param int $postId * - * @return array + * @return int[] * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ - public static function getRelatedPostsIdsForItem( $postId ): array { + public static function getRelatedPostsIdsForItem( int $postId ): array { $timeframes = \CommonsBooking\Repository\Timeframe::get( [], [ $postId ] ); $restrictions = \CommonsBooking\Repository\Restriction::get( [], [ $postId ] ); return array_merge( @@ -145,12 +145,12 @@ public static function getRelatedPostsIdsForItem( $postId ): array { /** * Returns all post ids in relation to $postId. * - * @param $postId + * @param int $postId * - * @return array + * @return int[] * @throws \Exception */ - public static function getRelatedPostsIdsForTimeframe( $postId ): array { + public static function getRelatedPostsIdsForTimeframe( int $postId ): array { $timeframe = new Timeframe( $postId ); $ids = [ $postId ]; return array_merge( $ids, $timeframe->getItemIDs(), $timeframe->getLocationIDs() ); @@ -159,12 +159,12 @@ public static function getRelatedPostsIdsForTimeframe( $postId ): array { /** * Returns all post ids in relation to $postId. * - * @param $postId + * @param int $postId * - * @return array + * @return int[] * @throws \Exception */ - public static function getRelatedPostsIdsForBooking( $postId ): array { + public static function getRelatedPostsIdsForBooking( int $postId ): array { $booking = new \CommonsBooking\Model\Booking( $postId ); $ids = [ $postId ]; @@ -184,12 +184,12 @@ public static function getRelatedPostsIdsForBooking( $postId ): array { /** * Returns all post ids in relation to $postId. * - * @param $postId + * @param int $postId * - * @return array + * @return int[] * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ - public static function getRelatedPostsIdsForRestriction( $postId ): array { + public static function getRelatedPostsIdsForRestriction( int $postId ): array { $restriction = new \CommonsBooking\Model\Restriction( $postId ); // Restriction itself @@ -217,13 +217,13 @@ public static function getRelatedPostsIdsForRestriction( $postId ): array { /** * Returns a list of cache tags related to $posts, $items and $locations. * - * @param $posts - * @param array $items - * @param array $locations + * @param array $posts + * @param array $items + * @param array $locations * - * @return array + * @return array */ - public static function getTags( $posts, array $items = [], array $locations = [] ): array { + public static function getTags( array $posts, array $items = [], array $locations = [] ): array { $itemsAndLocations = self::getLocationAndItemIdsFromPosts( $posts ); if ( ! count( $items ) && ! count( $locations ) ) { @@ -247,9 +247,9 @@ public static function getTags( $posts, array $items = [], array $locations = [] * The only posts that have items / locations assinged are timeframes and bookings. * Any other posts are skipped. * - * @param $posts + * @param array $posts * - * @return array + * @return int[] */ public static function getLocationAndItemIdsFromPosts( array $posts ): array { $itemsAndLocations = []; @@ -313,14 +313,14 @@ public static function convertTimestampToUTCDatetime( $timestamp ) { return $dto; } - public static function getUTCDateTime( $datetime = 'now' ): DateTime { + public static function getUTCDateTime( string $datetime = 'now' ): DateTime { $dto = new DateTime( $datetime ); $dto->setTimezone( new \DateTimeZone( 'UTC' ) ); return $dto; } - public static function getLocalDateTime( $timestamp ): DateTime { + public static function getLocalDateTime( int $timestamp ): DateTime { $dto = new DateTime(); $dto->setTimestamp( $timestamp diff --git a/src/Map/BaseShortcode.php b/src/Map/BaseShortcode.php index 65a982fbe..b5241dca1 100644 --- a/src/Map/BaseShortcode.php +++ b/src/Map/BaseShortcode.php @@ -14,7 +14,7 @@ final public function __construct() { } /** * The shortcode handler - load all the needed assets and render the map container * - * @param array $atts attributes for parametrization. + * @param array $atts attributes for parametrization. * @param string $content content to display, if shortcode implementation allows to. **/ public static function execute( array $atts, string $content = '' ): string { @@ -40,7 +40,15 @@ public static function execute( array $atts, string $content = '' ): string { $instance->inject_script( $cb_map_id ); return $instance->create_container( $cb_map_id, $attrs, $options, $content ); } - abstract protected function parse_attributes( $atts ); - abstract protected function inject_script( $cb_map_id ); - abstract protected function create_container( $cb_map_id, $attrs, $options, $content ); + /** + * @param array $atts + * @return array + */ + abstract protected function parse_attributes( array $atts ): array; + abstract protected function inject_script( int $cb_map_id ): void; + /** + * @param array $attrs + * @param array $options + */ + abstract protected function create_container( int $cb_map_id, array $attrs, array $options, string $content ): string; } diff --git a/src/Map/LocationMapAdmin.php b/src/Map/LocationMapAdmin.php index 366acb298..012525b2f 100644 --- a/src/Map/LocationMapAdmin.php +++ b/src/Map/LocationMapAdmin.php @@ -9,7 +9,7 @@ class LocationMapAdmin { /** * load the location administration map */ - public function load_location_map_admin() { + public function load_location_map_admin(): void { if ( COMMONSBOOKING_PLUGIN_DIR ) { // render map add_action( 'cmb2_render_cb_map', array( Map::class, 'render_cb_map' ), 10, 5 ); diff --git a/src/Map/MapData.php b/src/Map/MapData.php index b59c31d0b..a1190f4ee 100644 --- a/src/Map/MapData.php +++ b/src/Map/MapData.php @@ -6,7 +6,7 @@ use CommonsBooking\Model\Map; class MapData { - public static function geo_search() { + public static function geo_search(): void { if ( isset( $_POST['query'] ) && $_POST['cb_map_id'] ) { $map = new Map( $_POST['cb_map_id'] ); @@ -74,7 +74,7 @@ public static function geo_search() { /** * the ajax request handler for locations **/ - public static function get_locations() { + public static function get_locations(): void { // handle local/import map if ( isset( $_POST['cb_map_id'] ) ) { check_ajax_referer( 'cb_map_locations', 'nonce' ); @@ -126,9 +126,10 @@ public static function get_locations() { /** * Returns configured item terms * - * @return array + * @param array $settings + * @return array */ - public static function getItemCategoryTerms( $settings ): array { + public static function getItemCategoryTerms( array $settings ): array { $terms = []; foreach ( $settings['filter_cb_item_categories'] as $categoryGroup ) { @@ -144,8 +145,10 @@ public static function getItemCategoryTerms( $settings ): array { /** * get the settings for the frontend of the map with given id + * + * @return array **/ - public static function get_settings( $cb_map_id ): array { + public static function get_settings( int $cb_map_id ): array { $map = new Map( $cb_map_id ); $date_min = Wordpress::getUTCDateTime(); $date_min = $date_min->format( 'Y-m-d' ); diff --git a/src/Map/MapFilter.php b/src/Map/MapFilter.php index 7c3f5e5a4..8f2a9be61 100644 --- a/src/Map/MapFilter.php +++ b/src/Map/MapFilter.php @@ -4,7 +4,11 @@ class MapFilter { - protected static function check_item_terms_against_categories( $item_terms, $category_groups ): bool { + /** + * @param array $item_terms + * @param array $category_groups + */ + protected static function check_item_terms_against_categories( array $item_terms, array $category_groups ): bool { $valid_groups_count = 0; foreach ( $category_groups as $group ) { diff --git a/src/Map/MapItemAvailable.php b/src/Map/MapItemAvailable.php index f0144dee5..10c057adf 100644 --- a/src/Map/MapItemAvailable.php +++ b/src/Map/MapItemAvailable.php @@ -44,14 +44,14 @@ class MapItemAvailable { const OUT_OF_TIMEFRAME = 'no-timeframe'; /** - * @param $locations - * @param $date_start - * @param $date_end + * @param array $locations + * @param string $date_start + * @param string $date_end * - * @return mixed + * @return array * @throws Exception */ - public static function create_items_availabilities( $locations, $date_start, $date_end ) { + public static function create_items_availabilities( array $locations, string $date_start, string $date_end ): array { $startDay = new Day( $date_start ); $endDay = new Day( $date_end ); @@ -104,12 +104,12 @@ public static function create_items_availabilities( $locations, $date_start, $da * This logic should resemble the logic in the @see \CommonsBooking\View\Calendar::processSlot() method because * otherwise days would be mapped differently throughout the plugin. * - * @param $calendarData - * @param $availabilities + * @param array $calendarData + * @param array> $availabilities * - * @return mixed + * @return array> */ - protected static function markDaysInTimeframe( $calendarData, $availabilities ) { + protected static function markDaysInTimeframe( array $calendarData, array $availabilities ): array { // mark days which are inside a timeframe foreach ( $availabilities as &$availability ) { if ( array_key_exists( $availability['date'], $calendarData['days'] ) ) { diff --git a/src/Map/MapShortcode.php b/src/Map/MapShortcode.php index a034da6d1..d8b21a28f 100644 --- a/src/Map/MapShortcode.php +++ b/src/Map/MapShortcode.php @@ -8,18 +8,23 @@ * Shortcode for the legacy map with the old non-responsive standard leaflet style. */ class MapShortcode extends BaseShortcode { - protected function create_container( $cb_map_id, $attrs, $options, $content ) { + /** + * @param array $attrs + * @param array $options + */ + protected function create_container( int $cb_map_id, array $attrs, array $options, string $content ): string { $map = new Map( $cb_map_id ); $map_height = $map->getMeta( 'map_height' ); - return '
'; + return '
'; } - protected function parse_attributes( $atts ) { + /** @return array */ + protected function parse_attributes( array $atts ): array { return shortcode_atts( array( 'id' => 0 ), $atts ); } - protected function inject_script( $cb_map_id ) { + protected function inject_script( int $cb_map_id ): void { wp_add_inline_script( 'cb-map-shortcode', 'jQuery(document).ready(function ($) { @@ -37,7 +42,8 @@ protected function inject_script( $cb_map_id ) { /** * get the translations for the frontend **/ - private function get_translation( $cb_map_id ): array { + /** @return array */ + private function get_translation( int $cb_map_id ): array { $map = new Map( $cb_map_id ); $label_location_opening_hours = $map->getMeta( 'label_location_opening_hours' ); $label_location_contact = $map->getMeta( 'label_location_contact' ); diff --git a/src/Map/SearchShortcode.php b/src/Map/SearchShortcode.php index 566f020d7..64f54f525 100644 --- a/src/Map/SearchShortcode.php +++ b/src/Map/SearchShortcode.php @@ -6,9 +6,11 @@ * Short code for a multi-widget with map, search and table capabilities. */ class SearchShortcode extends BaseShortcode { - protected $processed_map_ids = []; + /** @var int[] */ + protected array $processed_map_ids = []; - protected function parse_attributes( $atts ) { + /** @return array */ + protected function parse_attributes( array $atts ): array { return shortcode_atts( [ 'id' => null, @@ -18,12 +20,16 @@ protected function parse_attributes( $atts ) { ); } - protected function inject_script( $cb_map_id ) { + protected function inject_script( int $cb_map_id ): void { wp_enqueue_style( 'cb-commons-search' ); wp_enqueue_script( 'cb-commons-search' ); } - protected function create_container( $cb_map_id, $attrs, $options, $content ) { + /** + * @param array $attrs + * @param array $options + */ + protected function create_container( int $cb_map_id, array $attrs, array $options, string $content ): string { // Ensure that the api and config object are only created once per page and per map if ( ! in_array( $cb_map_id, $this->processed_map_ids ) ) { $settings = MapData::get_settings( $cb_map_id ); @@ -73,7 +79,12 @@ protected function create_container( $cb_map_id, $attrs, $options, $content ) { } } -function pop_key( &$array, $key ) { +/** + * @param array $array + * @param string $key + * @return mixed + */ +function pop_key( array &$array, string $key ): mixed { $value = $array[ $key ]; unset( $array[ $key ] ); return $value; diff --git a/src/Messages/BookingCodesMessage.php b/src/Messages/BookingCodesMessage.php index 4a461e06f..2e90cfb02 100644 --- a/src/Messages/BookingCodesMessage.php +++ b/src/Messages/BookingCodesMessage.php @@ -20,7 +20,8 @@ */ class BookingCodesMessage extends Message { - protected $validActions = [ 'codes' ]; + /** @var string[] */ + protected array $validActions = [ 'codes' ]; protected $to; private ?int $tsFrom; private ?int $tsTo; @@ -44,22 +45,22 @@ public function __construct( int $postId, string $action, int $tsFrom, int $tsTo /** * prepares Message and sends by E-mail - * - * @return bool true if message was sent, false otherwise. If the message is not sent, an error is raised. */ - public function sendMessage(): bool { + public function sendMessage(): void { $timeframeId = (int) $this->getPostId(); $timeframe = new Timeframe( $timeframeId ); if ( ! $this->prepareReceivers( $timeframe ) ) { - return $this->raiseError( + $this->raiseError( __( 'Unable to send Emails. No location email(s) configured, check location', 'commonsbooking' ) ); + return; } $bookingCodes = BookingCodes::getCodes( $timeframeId, $this->tsFrom, $this->tsTo ); if ( empty( $bookingCodes ) ) { - return $this->raiseError( __( 'Could not find booking codes for this timeframe/period', 'commonsbooking' ) ); + $this->raiseError( __( 'Could not find booking codes for this timeframe/period', 'commonsbooking' ) ); + return; } $bookingTable = \CommonsBooking\View\BookingCodes::renderTableFor( 'email', $bookingCodes ); @@ -136,8 +137,6 @@ public function sendMessage(): bool { } remove_action( 'commonsbooking_mail_sent', array( $this, 'updateEmailSent' ), 5 ); - - return true; } /** @@ -149,7 +148,7 @@ public function sendMessage(): bool { * * @return void */ - public function updateEmailSent( $action, $result ) { + public function updateEmailSent( string $action, mixed $result ): void { if ( $this->action != $action ) { return; } @@ -162,7 +161,7 @@ public function updateEmailSent( $action, $result ) { /** * filter commonsbooking_mail_to for adding multiple to email addresses * - * @return array + * @return array */ public function addMultiTo(): array { $to = array(); @@ -201,7 +200,7 @@ protected function prepareReceivers( Timeframe $timeframe ): bool { * * @param BookingCode[] $bookingCodes List of BookingCode objects * - * @return array + * @return array */ protected function getIcalAttachment( array $bookingCodes ): array { $calendar = new iCalendar(); diff --git a/src/Messages/BookingMessage.php b/src/Messages/BookingMessage.php index cdddd044a..e79b36ea2 100644 --- a/src/Messages/BookingMessage.php +++ b/src/Messages/BookingMessage.php @@ -18,9 +18,9 @@ class BookingMessage extends Message { * * @var string[] */ - protected $validActions = [ 'confirmed', 'canceled' ]; + protected array $validActions = [ 'confirmed', 'canceled' ]; - public function sendMessage() { + public function sendMessage(): void { /** @var \CommonsBooking\Model\Booking $booking */ $booking = Booking::getPostById( $this->getPostId() ); diff --git a/src/Messages/BookingReminderMessage.php b/src/Messages/BookingReminderMessage.php index 9c14d665c..50fc06b1e 100644 --- a/src/Messages/BookingReminderMessage.php +++ b/src/Messages/BookingReminderMessage.php @@ -14,17 +14,15 @@ */ class BookingReminderMessage extends Message { - /** - * @var array|string[] - */ - protected $validActions = [ 'pre-booking-reminder', 'post-booking-notice' ]; + /** @var string[] */ + protected array $validActions = [ 'pre-booking-reminder', 'post-booking-notice' ]; /** * Sends reminder message. * * @throws \Exception */ - public function sendMessage() { + public function sendMessage(): void { /** @var \CommonsBooking\Model\Booking $booking */ $booking = Booking::getPostById( $this->getPostId() ); $booking_user = get_userdata( (int) $this->getPost()->post_author ); diff --git a/src/Messages/LocationBookingReminderMessage.php b/src/Messages/LocationBookingReminderMessage.php index 98c499313..7396c8bae 100644 --- a/src/Messages/LocationBookingReminderMessage.php +++ b/src/Messages/LocationBookingReminderMessage.php @@ -16,15 +16,13 @@ */ class LocationBookingReminderMessage extends Message { - /** - * @var array|string[] - */ - protected $validActions = [ 'booking-start-location-reminder', 'booking-end-location-reminder' ]; + /** @var string[] */ + protected array $validActions = [ 'booking-start-location-reminder', 'booking-end-location-reminder' ]; /** * Sends reminder message. */ - public function sendMessage() { + public function sendMessage(): void { /** @var \CommonsBooking\Model\Booking $booking */ $booking = Booking::getPostById( $this->getPostId() ); $booking_user = get_userdata( (int) $this->getPost()->post_author ); diff --git a/src/Messages/Message.php b/src/Messages/Message.php index a2ae571d5..fb908b6aa 100644 --- a/src/Messages/Message.php +++ b/src/Messages/Message.php @@ -15,16 +15,16 @@ abstract class Message { /** * The actions that are valid for this message. Usually a string. * - * @var array + * @var string[] */ - protected $validActions = []; + protected array $validActions = []; /** * The action that is used for this message. Needs to be contained in $validActions * * @var string */ - protected $action; + protected string $action; /** * The post that this message is about @@ -69,9 +69,9 @@ abstract class Message { * 'type' => File MIME type (if left unspecified, PHPMailer will try to work it out from the file name) * 'disposition' => Disposition to use (defaults to 'attachment') * - * @var array + * @var array */ - protected $attachment = []; + protected array $attachment = []; /** * @var int */ @@ -81,7 +81,7 @@ abstract class Message { * @param $postId * @param $action */ - public function __construct( $postId, $action ) { + public function __construct( int $postId, string $action ) { $this->postId = $postId; global $post; @@ -90,7 +90,7 @@ public function __construct( $postId, $action ) { $this->action = $action; } - public function getAction() { + public function getAction(): string { return $this->action; } @@ -114,7 +114,8 @@ public function getTo() { return apply_filters( 'commonsbooking_mail_to', $recipient, $messageAction ); } - public function getHeaders() { + /** @return string[]|null */ + public function getHeaders(): ?array { return $this->headers; } @@ -161,7 +162,7 @@ public function getBody() { /** * Return array of attachment * - * @return array + * @return array */ public function getAttachment(): array { $attachment = $this->attachment; @@ -186,7 +187,7 @@ public function getAttachment(): array { * @param string $from_headers From-Header (From:xxx) * @param string|null $bcc_adresses comma separated string with e-mail adresses * @param object[] $objects objects used in parse template function - * @param array|null $attachment + * @param array|null $attachment */ protected function prepareMail( MessageRecipient $recipientUser, @@ -260,7 +261,7 @@ public function sendNotificationMail() { do_action( 'commonsbooking_mail_sent', $this->getAction(), $result ); } - abstract public function sendMessage(); + abstract public function sendMessage(): void; /** * Only send mail if action is valid @@ -292,18 +293,18 @@ public function getPostId() { } /** - * @param array $address_array + * @param string[] $address_array * * @return void */ - protected function add_bcc( array $address_array ) { + protected function add_bcc( array $address_array ): void { // sanitize emails $address_array = array_filter( array_map( 'sanitize_email', $address_array ) ); $this->headers[] = sprintf( 'BCC:%s', implode( ',', $address_array ) ); } /** - * @return array + * @return string[] */ public function getValidActions(): array { return $this->validActions; @@ -323,7 +324,11 @@ public function getValidActions(): array { * * @see https://gist.github.com/thomasfw/5df1a041fd8f9c939ef9d88d887ce023/ */ - public function addStringAttachments( $atts ) { + /** + * @param array $atts + * @return array + */ + public function addStringAttachments( array $atts ): array { $attachment_arrays = []; if ( ! empty( $atts['attachments'] ) ) { $attachments = $atts['attachments']; diff --git a/src/Messages/RestrictionMessage.php b/src/Messages/RestrictionMessage.php index b1a43ba98..75cad4d2b 100644 --- a/src/Messages/RestrictionMessage.php +++ b/src/Messages/RestrictionMessage.php @@ -14,17 +14,16 @@ */ class RestrictionMessage extends Message { - protected $user; + protected \WP_User $user; - protected $restriction; + protected Restriction $restriction; - protected $action; - - protected $booking; + protected Booking $booking; protected bool $firstMessage; - protected $validActions = [ + /** @var string[] */ + protected array $validActions = [ Restriction::TYPE_REPAIR, Restriction::TYPE_HINT, ]; @@ -35,7 +34,7 @@ class RestrictionMessage extends Message { * @param $booking Booking * @param $action */ - public function __construct( $restriction, $user, Booking $booking, $action, bool $firstMessage = false ) { + public function __construct( Restriction $restriction, \WP_User $user, Booking $booking, string $action, bool $firstMessage = false ) { $this->restriction = $restriction; $this->user = $user; $this->booking = $booking; @@ -46,7 +45,7 @@ public function __construct( $restriction, $user, Booking $booking, $action, boo /** * Sends mails related to restriction type and state. */ - public function sendMessage() { + public function sendMessage(): void { if ( $this->getRestriction()->isActive() ) { if ( $this->getRestriction()->getType() == Restriction::TYPE_HINT ) { // send hint mail @@ -66,7 +65,7 @@ public function sendMessage() { /** * Sends hint mail. */ - protected function sendHintMail() { + protected function sendHintMail(): void { $body = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-hint-body' ); $subject = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-hint-subject', 'sanitize_text_field' ); @@ -81,7 +80,7 @@ protected function sendHintMail() { /** * Sends repair mail. */ - protected function sendRepairMail() { + protected function sendRepairMail(): void { $body = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-repair-body' ); $subject = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-repair-subject', 'sanitize_text_field' ); @@ -96,7 +95,7 @@ protected function sendRepairMail() { /** * Sends mail, when restriction is canceled (not active). */ - protected function sendRestrictionCancelationMail() { + protected function sendRestrictionCancelationMail(): void { $body = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-restriction-cancelled-body' ); $subject = Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-restriction-cancelled-subject', 'sanitize_text_field' ); @@ -116,7 +115,7 @@ protected function sendRestrictionCancelationMail() { * * @throws \Exception */ - protected function prepareRestrictionMail( $body, $subject ) { + protected function prepareRestrictionMail( string $body, string $subject ): void { $fromHeader = 'From: ' . Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-from-name', 'sanitize_text_field' ) . ' <' . Settings::getOption( 'commonsbooking_options_restrictions', 'restrictions-from-email' ) . '>'; $restriction = $this->getRestriction(); diff --git a/src/Migration/Booking.php b/src/Migration/Booking.php index 48947c2d9..7085dbaa4 100644 --- a/src/Migration/Booking.php +++ b/src/Migration/Booking.php @@ -8,8 +8,10 @@ class Booking { /** * Changes post type of booking timeframes to cb_booking. + * + * @return int[] */ - public static function migrate() { + public static function migrate(): array { $bookings = Timeframe::getPostIdsByType( [ diff --git a/src/Migration/Migration.php b/src/Migration/Migration.php index fef012036..f5a253fdf 100644 --- a/src/Migration/Migration.php +++ b/src/Migration/Migration.php @@ -264,7 +264,7 @@ public static function migrateLocation( WP_Post $location ): bool { * * @param mixed $text * - * @return array + * @return array */ public static function fetchEmails( $text ): array { $words = str_word_count( $text, 1, '.@-_' ); @@ -278,11 +278,11 @@ function ( $word ) { } /** - * @param $meta + * @param array> $meta * - * @return array + * @return array */ - private static function getFlatPostMeta( $meta ): array { + private static function getFlatPostMeta( array $meta ): array { return array_map( function ( $item ) { return $item[0]; @@ -291,7 +291,12 @@ function ( $item ) { ); } - private static function removeArrayItemsByKeys( $array, $keys ) { + /** + * @param array $array + * @param string[] $keys + * @return array + */ + private static function removeArrayItemsByKeys( array $array, array $keys ): array { foreach ( $keys as $ignoredMetaField ) { if ( array_key_exists( $ignoredMetaField, $array ) ) { unset( $array[ $ignoredMetaField ] ); @@ -302,15 +307,14 @@ private static function removeArrayItemsByKeys( $array, $keys ) { } /** - * @param $id - * @param $type + * @param int $id + * @param string $type + * @param int|null $timeframe_type * - * @param null $timeframe_type - * - * @return mixed + * @return \WP_Post|null * @throws Exception */ - public static function getExistingPost( $id, $type, $timeframe_type = null ) { + public static function getExistingPost( int $id, string $type, ?int $timeframe_type = null ): ?\WP_Post { $args = array( 'meta_key' => COMMONSBOOKING_METABOX_PREFIX . 'cb1_post_post_ID', 'meta_value' => $id, @@ -356,14 +360,14 @@ public static function getExistingPost( $id, $type, $timeframe_type = null ) { } /** - * @param $existingPost - * @param $postData array Post data - * @param $postMeta array Post meta + * @param \WP_Post|null $existingPost + * @param array $postData Post data + * @param array $postMeta Post meta * * @return bool * @throws \CommonsBooking\Geocoder\Exception\Exception */ - protected static function savePostData( $existingPost, array $postData, array $postMeta ): bool { + protected static function savePostData( ?\WP_Post $existingPost, array $postData, array $postMeta ): bool { $includeGeoData = array_key_exists( 'geodata', $_POST ) && sanitize_text_field( $_POST['geodata'] ) == 'true'; @@ -470,12 +474,12 @@ public static function migrateItem( WP_Post $item ): bool { } /** - * @param $timeframe + * @param array $timeframe * * @return bool * @throws \CommonsBooking\Geocoder\Exception\Exception */ - public static function migrateTimeframe( $timeframe ): bool { + public static function migrateTimeframe( array $timeframe ): bool { $cbItem = self::getExistingPost( $timeframe['item_id'], Item::$postType ); $cbLocation = self::getExistingPost( $timeframe['location_id'], Location::$postType ); $weekdays = ''; @@ -522,13 +526,13 @@ public static function migrateTimeframe( $timeframe ): bool { } /** - * @param $booking + * @param array $booking * * @return bool * @throws \CommonsBooking\Geocoder\Exception\Exception * @throws Exception */ - public static function migrateBooking( $booking ): bool { + public static function migrateBooking( array $booking ): bool { $user = get_user_by( 'id', $booking['user_id'] ); $cbItem = self::getExistingPost( $booking['item_id'], Item::$postType ); $cbLocation = self::getExistingPost( $booking['location_id'], Location::$postType ); @@ -573,11 +577,11 @@ public static function migrateBooking( $booking ): bool { /** * Migrates CB1 Booking Code to CB2. * - * @param $bookingCode + * @param array $bookingCode * * @return mixed */ - public static function migrateBookingCode( $bookingCode ) { + public static function migrateBookingCode( array $bookingCode ) { $cb2ItemId = CB1::getCB2ItemId( $bookingCode['item_id'] ); $date = $bookingCode['booking_date']; $code = $bookingCode['bookingcode']; @@ -606,7 +610,7 @@ public static function migrateUserAgreementUrl() { /** * Migrates some of the CB1 Options that can be transfered to CB2 */ - public static function migrateCB1Options() { + public static function migrateCB1Options(): void { // migrate Booking-Codes $cb1_bookingcodes = Settings::getOption( 'commons-booking-settings-codes', 'commons-booking_codes_pool' ); Settings::updateOption( 'commonsbooking_options_bookingcodes', 'bookingcodes', $cb1_bookingcodes ); @@ -627,7 +631,7 @@ public static function migrateCB1Options() { * * @return void */ - public static function migrateTaxonomy( $cb1Taxonomy ) { + public static function migrateTaxonomy( object $cb1Taxonomy ): void { if ( $cb2PostId = CB1::getCB2PostIdByCB1Id( $cb1Taxonomy->object_id ) ) { $terms = wp_get_object_terms( $cb1Taxonomy->object_id, $cb1Taxonomy->taxonomy ); $term = array(); diff --git a/src/Model/BookablePost.php b/src/Model/BookablePost.php index 6fd9e27bf..1a5f5e652 100644 --- a/src/Model/BookablePost.php +++ b/src/Model/BookablePost.php @@ -20,10 +20,10 @@ class BookablePost extends CustomPost { * * @uses Timeframe::getBookableForCurrentUser() * - * @param bool $asModel - Whether to return the timeframes as model (CommonsBooking\Model\Timeframe) or as array of WP_Post - * @param array $locations - If called from Item, this array should contain the location IDs to filter the timeframes - * @param array $items - If called from Location, this array should contain the item IDs to filter the timeframes - * @param string|null $date - A datestring to get only the timeframes that are bookable on a specific date + * @param bool $asModel - Whether to return the timeframes as model (CommonsBooking\Model\Timeframe) or as array of WP_Post + * @param array $locations - If called from Item, this array should contain the location IDs to filter the timeframes + * @param array $items - If called from Location, this array should contain the item IDs to filter the timeframes + * @param string|null $date - A datestring to get only the timeframes that are bookable on a specific date * * @return \CommonsBooking\Model\Timeframe[]|\WP_Post[] - An array of Timeframe models or WP_Post, an empty array if no bookable timeframes were found * @throws Exception diff --git a/src/Model/Booking.php b/src/Model/Booking.php index 8a5a4411c..75c278873 100755 --- a/src/Model/Booking.php +++ b/src/Model/Booking.php @@ -117,7 +117,7 @@ public function cancel(): void { /** * Send mail to booking user, that it was canceled. */ - protected function sendCancellationMail() { + protected function sendCancellationMail(): void { $booking_msg = new BookingMessage( $this->getPost()->ID, 'canceled' ); $booking_msg->triggerMail(); } @@ -162,8 +162,8 @@ public function showBookingCodes(): bool { * @throws Exception */ public function getBookableTimeFrame(): ?\CommonsBooking\Model\Timeframe { - $locationId = $this->getMeta( \CommonsBooking\Model\Timeframe::META_LOCATION_ID ); - $itemId = $this->getMeta( \CommonsBooking\Model\Timeframe::META_ITEM_ID ); + $locationId = (int) $this->getMeta( \CommonsBooking\Model\Timeframe::META_LOCATION_ID ); + $itemId = (int) $this->getMeta( \CommonsBooking\Model\Timeframe::META_ITEM_ID ); $response = Timeframe::getBookable( [ $locationId ], @@ -186,7 +186,7 @@ public function getBookableTimeFrame(): ?\CommonsBooking\Model\Timeframe { * * @throws Exception */ - public function assignBookableTimeframeFields() { + public function assignBookableTimeframeFields(): void { $timeframe = $this->getBookableTimeFrame(); if ( $timeframe ) { $neededMetaFields = [ @@ -273,7 +273,7 @@ private function adjacent( bool $previous = true ): ?Booking { * * @since 2.9.0 * - * @return array|null + * @return array|null * @throws Exception */ public function getAdjacentBookings(): ?array { @@ -288,7 +288,7 @@ public function getAdjacentBookings(): ?array { * @since 2.9.0 * * @param WP_User $user - * @return array + * @return array */ public function getBookingChain( WP_User $user ): array { $bookingChain = []; @@ -321,11 +321,11 @@ public function getBookingChain( WP_User $user ): array { * Returns time from repetition-[start/end] field in format H:i. * We need this meta-field in order to display the pick-up and return time to the user. * - * @param $fieldName + * @param string $fieldName * * @return string */ - private function sanitizeTimeField( $fieldName ): string { + private function sanitizeTimeField( string $fieldName ): string { $time = Wordpress::getUTCDateTime(); $fieldValue = $this->getStartDate(); if ( $fieldName === 'end-time' ) { @@ -747,7 +747,7 @@ public function isPast(): bool { * * @since 2.9.0 * - * @param int|array|string $term + * @param int|array|string $term * @return bool */ public function termsApply( $term ): bool { @@ -974,9 +974,9 @@ public static function getTotalDuration( array $bookings ): int { * * @since 2.9.0 * - * @param Booking[] $bookings The booking to check - * @param array|false $terms The terms that the bookings are filtered against - * @return array|null + * @param Booking[] $bookings The booking to check + * @param array|false $terms The terms that the bookings are filtered against + * @return array|null */ public static function filterTermsApply( array $bookings, $terms ): ?array { if ( ! empty( $terms ) ) { @@ -1000,9 +1000,9 @@ public static function filterTermsApply( array $bookings, $terms ): ?array { * * @since 2.9.0 * - * @param array $bookings - * @param WP_User $user - * @return array|null + * @param array $bookings + * @param WP_User $user + * @return array|null */ public static function filterForUser( array $bookings, WP_User $user ): ?array { return array_filter( diff --git a/src/Model/BookingCode.php b/src/Model/BookingCode.php index da9adeb13..7db40e62b 100644 --- a/src/Model/BookingCode.php +++ b/src/Model/BookingCode.php @@ -43,11 +43,11 @@ class BookingCode { /** * BookingCode constructor. * - * @param $date - * @param $item - * @param $code + * @param string $date + * @param int $item + * @param string $code */ - public function __construct( $date, $item, $code ) { + public function __construct( string $date, int $item, string $code ) { $this->date = $date; $this->item = $item; $this->code = $code; @@ -67,7 +67,7 @@ public function getItem(): int { return $this->item; } - public function getItemName() { + public function getItemName(): string { $post = get_post( $this->getItem() ); return $post->post_title; diff --git a/src/Model/Calendar.php b/src/Model/Calendar.php index 806b52feb..3bbe0360f 100644 --- a/src/Model/Calendar.php +++ b/src/Model/Calendar.php @@ -34,7 +34,7 @@ class Calendar { protected array $locations; /** - * @var array + * @var array */ protected $types; @@ -48,11 +48,11 @@ class Calendar { /** * Calendar constructor. * - * @param Day $startDate - * @param Day $endDate - * @param int[] $locations - * @param int[] $items - * @param array $types + * @param Day $startDate + * @param Day $endDate + * @param int[] $locations + * @param int[] $items + * @param array $types */ public function __construct( Day $startDate, Day $endDate, array $locations = [], array $items = [], array $types = [] ) { // check, that it spans at least two days @@ -82,7 +82,7 @@ public function __construct( Day $startDate, Day $endDate, array $locations = [] * * Uses cache and expires at midnight on a daily basis. * - * @return array + * @return array */ public function getWeeks(): array { $startDate = strtotime( $this->startDate->getDate() ) + 1; @@ -102,8 +102,8 @@ public function getWeeks(): array { } else { $weeks = array(); while ( $startDate <= $endDate ) { - $dayOfYear = date( 'z', $startDate ); - $year = date( 'Y', $startDate ); + $dayOfYear = (int) date( 'z', $startDate ); + $year = (int) date( 'Y', $startDate ); $weeks[] = new Week( $year, $dayOfYear, @@ -129,7 +129,7 @@ public function getWeeks(): array { * Because we process the calendar by weeks, at least two days are needed to get a valid calendar. * The calendar does not consider the individual boundaries set by $startDate and $endDate but will always return a full week. * - * @return array + * @return array * @throws \Exception */ public function getAvailabilitySlots(): array { diff --git a/src/Model/CustomPost.php b/src/Model/CustomPost.php index ec47fd928..055a511d6 100644 --- a/src/Model/CustomPost.php +++ b/src/Model/CustomPost.php @@ -54,11 +54,11 @@ public function __construct( $post ) { /** * Returns field value, even if it's a meta field. * - * @param $fieldName + * @param string $fieldName * * @return mixed */ - public function getFieldValue( $fieldName ) { + public function getFieldValue( string $fieldName ) { $fieldName = trim( $fieldName ); $fieldValue = $this->{$fieldName}; @@ -74,9 +74,9 @@ public function getFieldValue( $fieldName ) { * * @param string $field key of post_meta field for this post * - * @return string|array The value of the meta field. An empty string if the field doesn't exist. + * @return string|array The value of the meta field. An empty string if the field doesn't exist. */ - public function getMeta( $field ) { + public function getMeta( string $field ) { return get_post_meta( $this->post->ID, $field, true ); } @@ -99,11 +99,11 @@ public function getMetaInt( string $key ): ?int { * When getting a value from a Model Object, we can use this magic method to get the value from the WP_Post object instead. * This, for example, allows us to use $booking->post_title instead of $booking->post->post_title. * - * @param $name + * @param string $name * - * @return array|mixed|void + * @return array|mixed|void */ - public function __get( $name ) { + public function __get( string $name ) { if ( $this->post == null ) { return; } @@ -116,13 +116,13 @@ public function __get( $name ) { /** * Enables that we can call methods of \CustomPost as template tags. * - * @param string $name of the member function - * @param array $arguments given to the template tag. + * @param string $name of the member function + * @param array $arguments given to the template tag. * - * @return array|mixed|void + * @return array|mixed|void * @throws \ReflectionException if called template tag is not a registered method */ - public function __call( $name, $arguments ) { + public function __call( string $name, array $arguments ) { if ( method_exists( $this->post, $name ) ) { $reflectionMethod = new ReflectionMethod( $this->post, $name ); diff --git a/src/Model/Day.php b/src/Model/Day.php index 72d0ec13f..041f91403 100644 --- a/src/Model/Day.php +++ b/src/Model/Day.php @@ -23,17 +23,17 @@ class Day { protected $date; /** - * @var array + * @var array */ protected $locations; /** - * @var array + * @var array */ protected $items; /** - * @var array|mixed + * @var array */ protected $types; @@ -45,11 +45,11 @@ class Day { /** * Day constructor. * - * @param string $date - * @param array $locations - * @param array $items - * @param array $types - * @param array $possibleTimeframes + * @param string $date + * @param array $locations + * @param array $items + * @param array $types + * @param array $possibleTimeframes */ public function __construct( string $date, array $locations = [], array $items = [], array $types = [], array $possibleTimeframes = [] ) { $this->date = $date; @@ -151,7 +151,7 @@ public function getTimeframes(): array { /** * Returns array with restrictions. * - * @return array + * @return array * @throws Exception */ public function getRestrictions(): array { @@ -169,7 +169,7 @@ public function getRestrictions(): array { * Returns grid for the day defined by the timeframes. * * @see Day::getTimeframeSlots() - * @return array + * @return array> * @throws Exception */ public function getGrid(): array { @@ -253,9 +253,9 @@ protected function getRestrictionStartSlot( int $grid, Restriction $restriction /** * Returns end-slot id. * - * @param array $slots - * @param int $grid - * @param \CommonsBooking\Model\Timeframe $timeframe + * @param array> $slots + * @param int $grid + * @param \CommonsBooking\Model\Timeframe $timeframe * * @return float|int * @throws Exception @@ -287,9 +287,9 @@ protected function getEndSlot( array $slots, int $grid, \CommonsBooking\Model\Ti /** * Returns end slot for restriction. * - * @param array $slots - * @param int $grid - * @param Restriction $restriction + * @param array> $slots + * @param int $grid + * @param Restriction $restriction * * @return float|int * @throws Exception @@ -407,11 +407,12 @@ public function filterTimeframe( \CommonsBooking\Model\Timeframe $timeframe ): b /** * Maps timeframes to timeslots. * - * @param array $slots untyped structure of timeframe slot information + * @param array> $slots untyped structure of timeframe slot information * + * @return void * @throws Exception */ - protected function mapTimeFrames( array &$slots ) { + protected function mapTimeFrames( array &$slots ): void { $grid = 24 / count( $slots ); // Iterate through timeframes and fill slots @@ -440,11 +441,12 @@ protected function mapTimeFrames( array &$slots ) { /** * Overwrites restricted slots * - * @param array $slots + * @param array> $slots * + * @return void * @throws Exception */ - protected function mapRestrictions( array &$slots ) { + protected function mapRestrictions( array &$slots ): void { $grid = 24 / count( $slots ); // Iterate through timeframes and fill slots @@ -487,9 +489,11 @@ public function getEndTimestamp(): int { /** * Remove empty and merge connected slots. * - * @param array $slots Given an array of assocs in hourly slot resolution. + * @param array> $slots Given an array of assocs in hourly slot resolution. + * + * @return void */ - protected function sanitizeSlots( array &$slots ) { + protected function sanitizeSlots( array &$slots ): void { $this->removeEmptySlots( $slots ); // merge multiple slots if they are of same type @@ -523,9 +527,11 @@ protected function sanitizeSlots( array &$slots ) { /** * remove slots without timeframes * - * @param $slots + * @param array> $slots + * + * @return void */ - protected function removeEmptySlots( &$slots ) { + protected function removeEmptySlots( array &$slots ): void { // remove slots without timeframes foreach ( $slots as $slotNr => $slot ) { if ( ! array_key_exists( 'timeframe', $slot ) || ! ( $slot['timeframe'] instanceof WP_Post ) ) { @@ -541,7 +547,7 @@ protected function removeEmptySlots( &$slots ) { * Implementation note: An hourly resolution is used, but as a last step, the hourly slots are merged into * the representation that is configured in the timeframes. * - * @return array + * @return array> * @throws Exception */ protected function getTimeframeSlots(): array { @@ -582,24 +588,24 @@ protected function getTimeframeSlots(): array { /** * Returns timestamp when $slotNr starts. * - * @param $slotsPerDay - * @param $slotNr + * @param int $slotsPerDay + * @param int $slotNr * * @return false|float|int */ - protected function getSlotTimestampStart( $slotsPerDay, $slotNr ) { + protected function getSlotTimestampStart( int $slotsPerDay, int $slotNr ) { return strtotime( $this->getDate() ) + ( $slotNr * ( ( 24 / $slotsPerDay ) * 3600 ) ); } /** * Returns timestamp when $slotNr ends. * - * @param $slotsPerDay - * @param $slotNr + * @param int $slotsPerDay + * @param int $slotNr * * @return false|float|int */ - protected function getSlotTimestampEnd( $slotsPerDay, $slotNr ) { + protected function getSlotTimestampEnd( int $slotsPerDay, int $slotNr ) { return strtotime( $this->getDate() ) + ( ( $slotNr + 1 ) * ( ( 24 / $slotsPerDay ) * 3600 ) ) - 1; } } diff --git a/src/Model/Item.php b/src/Model/Item.php index 25aeae158..87d7e69a0 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -18,14 +18,14 @@ class Item extends BookablePost { /** * Returns all bookable timeframes for a specific location. * - * @param $locationId + * @param int $locationId * * @param bool $asModel * - * @return array + * @return array|\WP_Post[] * @throws Exception */ - public function getBookableTimeframesByLocation( $locationId, bool $asModel = false ): array { + public function getBookableTimeframesByLocation( int $locationId, bool $asModel = false ): array { return Timeframe::getBookableForCurrentUser( [ $locationId ], [ $this->ID ], @@ -70,7 +70,7 @@ public function getAdmins() { * * This function is not used anywhere yet. * - * @return array + * @return array * @throws Exception */ public function getRestrictions(): array { diff --git a/src/Model/Location.php b/src/Model/Location.php index bc178aaf3..e5102ea0a 100644 --- a/src/Model/Location.php +++ b/src/Model/Location.php @@ -25,7 +25,7 @@ class Location extends BookablePost { * @param mixed $itemId * @param bool $asModel * - * @return array + * @return array|\WP_Post[] * @throws \Exception */ public function getBookableTimeframesByItem( $itemId, bool $asModel = false ): array { @@ -187,7 +187,7 @@ public function formattedPickupInstructionsOneLine() { * Calls the geocoder to update the geo coordinates of the location. * Caution: Do not call this function without a one-second delay between calls. Do not overload the geocoder. */ - public function updateGeoLocation() { + public function updateGeoLocation(): void { $street = $this->getMeta( COMMONSBOOKING_METABOX_PREFIX . 'location_street' ); $postCode = $this->getMeta( COMMONSBOOKING_METABOX_PREFIX . 'location_postcode' ); $city = $this->getMeta( COMMONSBOOKING_METABOX_PREFIX . 'location_city' ); diff --git a/src/Model/Map.php b/src/Model/Map.php index e48253f64..cd0269419 100644 --- a/src/Model/Map.php +++ b/src/Model/Map.php @@ -19,9 +19,9 @@ class Map extends CustomPost { * attaches start / enddate of the bookable timeframe to the item * Fetches location & item metadata to be displayed on the map * - * @param $mapItemTerms array of term ids + * @param array $mapItemTerms array of term ids * - * @return array with postIDs as keys for an array with location data relevant for this map + * @return array> with postIDs as keys for an array with location data relevant for this map * @throws Exception */ public function get_locations( array $mapItemTerms ): array { @@ -168,12 +168,12 @@ function ( $item ) { /** * recursive clean up of location data entries * - * @param $value - * @param $linebreak_replacement + * @param mixed $value + * @param string $linebreak_replacement * * @return mixed|string|string[]|null */ - public static function cleanup_location_data_entry( $value, $linebreak_replacement ) { + public static function cleanup_location_data_entry( $value, string $linebreak_replacement ) { if ( is_string( $value ) ) { $value = wp_strip_all_tags( $value ); // strip all tags @@ -193,12 +193,12 @@ public static function cleanup_location_data_entry( $value, $linebreak_replaceme /** * clean up the location data * - * @param $locations - * @param $linebreak_replacement + * @param array> $locations + * @param string $linebreak_replacement * - * @return mixed + * @return array> */ - public static function cleanup_location_data( $locations, $linebreak_replacement ) { + public static function cleanup_location_data( array $locations, string $linebreak_replacement ) { foreach ( $locations as &$location ) { $location = self::cleanup_location_data_entry( $location, $linebreak_replacement ); } diff --git a/src/Model/Restriction.php b/src/Model/Restriction.php index 80bd7cfbd..db3025237 100644 --- a/src/Model/Restriction.php +++ b/src/Model/Restriction.php @@ -81,8 +81,10 @@ class Restriction extends CustomPost { const NO_END_TIMESTAMP = 3000000000; + /** @var bool|null */ protected $active; + /** @var bool|null */ protected $canceled; /** @@ -287,7 +289,7 @@ public function getLocationId() { * Apply restriction workflow. * Will cancel the bookings if restriction is active and type is total breakdown. */ - public function apply() { + public function apply(): void { // Check if this is an active restriction if ( $this->isActive() ) { $bookings = \CommonsBooking\Repository\Booking::getByRestriction( $this ); @@ -334,7 +336,7 @@ public function getType() { * TODO: * Duplicated implementation in Model/Timeframe.php * - * @return array + * @return array */ public function getAdmins() { @@ -377,7 +379,7 @@ public function getAdmins() { * * @param Booking[] $bookings booking post objects. */ - protected function cancelBookings( $bookings ) { + protected function cancelBookings( array $bookings ): void { foreach ( $bookings as $booking ) { $booking->cancel(); } @@ -391,7 +393,7 @@ protected function cancelBookings( $bookings ) { * * @param Booking[] $bookings booking post objects. */ - protected function sendRestrictionMails( $bookings ) { + protected function sendRestrictionMails( array $bookings ): void { foreach ( $bookings as $key => $booking ) { // get User ID from booking $userId = $booking->getUserData()->ID; diff --git a/src/Model/Timeframe.php b/src/Model/Timeframe.php index 6b135ce72..2cae5992c 100644 --- a/src/Model/Timeframe.php +++ b/src/Model/Timeframe.php @@ -206,8 +206,10 @@ public function isUserPrivileged( \WP_User $user ): bool { return true; } - $itemAdmin = commonsbooking_isUserAllowedToEdit( $this->getItem(), $user ); - $locationAdmin = commonsbooking_isUserAllowedToEdit( $this->getLocation(), $user ); + $item = $this->getItem(); + $location = $this->getLocation(); + $itemAdmin = $item ? commonsbooking_isUserAllowedToEdit( $item->ID, $user ) : false; + $locationAdmin = $location ? commonsbooking_isUserAllowedToEdit( $location->ID, $user ) : false; return ( $itemAdmin || $locationAdmin ); } @@ -855,12 +857,12 @@ public function overlaps( Timeframe $otherTimeframe ): bool { /** * Checks if timeframes are overlapping in weekly slot and slot with manual repetition. * - * @param $weeklyTimeframe - * @param $manualTimeframe + * @param Timeframe $weeklyTimeframe + * @param Timeframe $manualTimeframe * * @return bool */ - private static function hasWeeklyManualOverlap( $weeklyTimeframe, $manualTimeframe ): bool { + private static function hasWeeklyManualOverlap( Timeframe $weeklyTimeframe, Timeframe $manualTimeframe ): bool { $manualSelectionWeekdays = array_unique( array_map( fn ( $date ) => date( 'w', strtotime( $date ) ), diff --git a/src/Model/Week.php b/src/Model/Week.php index 41ddad092..f34bde020 100644 --- a/src/Model/Week.php +++ b/src/Model/Week.php @@ -27,19 +27,19 @@ class Week { protected $dayOfYear; /** - * @var array + * @var int[] */ - protected $locations; + protected array $locations; /** - * @var array + * @var int[] */ - protected $items; + protected array $items; /** - * @var array + * @var string[] */ - protected $types; + protected array $types; /** * @var Timeframe[] @@ -49,14 +49,14 @@ class Week { /** * Week constructor. * - * @param $year - * @param $dayOfYear - * @param array $locations - * @param array $items - * @param array $types + * @param int $year + * @param int $dayOfYear + * @param int[] $locations + * @param int[] $items + * @param string[] $types * @param Timeframe[] $possibleTimeframes Timeframes that might be relevant for this week, need to be filtered. */ - public function __construct( $year, $dayOfYear, array $locations = [], array $items = [], array $types = [], array $possibleTimeframes = [] ) { + public function __construct( int $year, int $dayOfYear, array $locations = [], array $items = [], array $types = [], array $possibleTimeframes = [] ) { if ( $year === null ) { $year = date( 'Y' ); } @@ -76,7 +76,7 @@ public function __construct( $year, $dayOfYear, array $locations = [], array $it * * Uses the cache and expires at midnight on a daily basis. * - * @return array + * @return \CommonsBooking\Model\Day[] * @throws Exception */ public function getDays() { diff --git a/src/Plugin.php b/src/Plugin.php index b7e143506..308263720 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -47,7 +47,7 @@ class Plugin { /** * Plugin activation tasks. */ - public static function activation() { + public static function activation(): void { // Register custom user roles (e.g. cb_manager) self::addCustomUserRoles(); @@ -63,7 +63,7 @@ public static function activation() { /** * Plugin deactivation tasks. */ - public static function deactivation() { + public static function deactivation(): void { do_action( Scheduler::UNSCHEDULER_HOOK ); } @@ -108,7 +108,7 @@ public static function addCPTRoleCaps() { * * @return bool[][] */ - public static function getRoleCapMapping( $roleName = null ) { + public static function getRoleCapMapping( ?string $roleName = null ) { if ( $roleName === null ) { return [ // We deliberately don't use the getManagerRoles from the UserRepository here, because the custom roles should be able to define their own permissions @@ -133,7 +133,7 @@ public static function getRoleCapMapping( $roleName = null ) { /** * Adds cb user roles to WordPress. */ - public static function addCustomUserRoles() { + public static function addCustomUserRoles(): void { foreach ( self::getRoleCapMapping() as $roleName => $caps ) { $role = get_role( $roleName ); if ( ! $role ) { @@ -250,7 +250,7 @@ public static function getManagedDepsVersions(): ?array { * * @return bool */ - public static function isPostCustomPostType( $post ): bool { + public static function isPostCustomPostType( int|\WP_Post $post ): bool { if ( is_int( $post ) ) { $post = get_post( $post ); } @@ -281,9 +281,10 @@ private static function getCBManagerCustomPostTypeClasses(): array { /** * Adds permissions to edit custom post types for specified role. * - * @param $postType + * @param string $postType + * @param string $roleName */ - protected static function addRoleCaps( $postType, $roleName ) { + protected static function addRoleCaps( string $postType, string $roleName ): void { // Add the roles you'd like to administer the custom post types $roles = array_keys( self::getRoleCapMapping( $roleName ) ); @@ -322,7 +323,7 @@ protected static function addRoleCaps( $postType, $roleName ) { } } - public static function admin_init() { + public static function admin_init(): void { // check if we have a new version and run tasks Upgrade::runTasksAfterUpdate(); @@ -341,7 +342,7 @@ public static function admin_init() { /** * Adds menu pages. */ - public static function addMenuPages() { + public static function addMenuPages(): void { // Dashboard add_menu_page( 'Commons Booking', @@ -470,7 +471,7 @@ public static function filterAdminBodyClass( $classes ) { /** * Registers custom post types. */ - public static function registerCustomPostTypes() { + public static function registerCustomPostTypes(): void { foreach ( self::getCustomPostTypeObjects() as $customPostType ) { $cptArgs = $customPostType->getArgs(); // make export possible when using WP_DEBUG, this allows us to use the export feature for creating new E2E tests @@ -486,7 +487,7 @@ public static function registerCustomPostTypes() { /** * Registers additional post statuses. */ - public static function registerPostStates() { + public static function registerPostStates(): void { foreach ( Booking::$bookingStates as $bookingState ) { new PostStatus( $bookingState, __( ucfirst( $bookingState ), 'commonsbooking' ) ); } @@ -496,7 +497,7 @@ public static function registerPostStates() { * Renders error for backend_notice. * TODO refactor this using the AdminMessage type */ - public static function renderError() { + public static function renderError(): void { $errorTypes = [ Model\Timeframe::ERROR_TYPE, Model\Timeframe::ORPHANED_TYPE, @@ -537,7 +538,7 @@ public static function renderError() { /** * Enable Legacy CB1 profile fields. */ - public static function maybeEnableCB1UserFields() { + public static function maybeEnableCB1UserFields(): void { $enabled = Settings::getOption( 'commonsbooking_options_migration', 'enable-cb1-user-fields' ); if ( $enabled == 'on' ) { new CB1UserFields(); @@ -547,7 +548,7 @@ public static function maybeEnableCB1UserFields() { /** * Register Admin-Options */ - public static function registerAdminOptions() { + public static function registerAdminOptions(): void { $options_array = include COMMONSBOOKING_PLUGIN_DIR . '/includes/OptionsArray.php'; foreach ( $options_array as $tab_id => $tab ) { new OptionsTab( $tab_id, $tab ); @@ -567,7 +568,7 @@ private static function packagedVersion( string $key ): string { return $versions[ $key ] ?? '0'; } - public static function registerScriptsAndStyles() { + public static function registerScriptsAndStyles(): void { $base = COMMONSBOOKING_PLUGIN_ASSETS_URL . 'packaged/'; // spin.js @@ -704,18 +705,18 @@ public static function registerScriptsAndStyles() { ); } - public function registerShortcodes() { + public function registerShortcodes(): void { add_shortcode( 'cb_search', array( SearchShortcode::class, 'execute' ) ); } /** * Registers all user data exporters ({@link https://developer.wordpress.org/plugins/privacy/adding-the-personal-data-exporter-to-your-plugin/}). * - * @param array $exporters + * @param array> $exporters * - * @return mixed + * @return array> */ - public static function registerUserDataExporters( $exporters ) { + public static function registerUserDataExporters( array $exporters ): array { $exporters[ COMMONSBOOKING_PLUGIN_SLUG ] = array( 'exporter_friendly_name' => __( 'CommonsBooking Bookings', 'commonsbooking' ), 'callback' => array( \CommonsBooking\Wordpress\CustomPostType\Booking::class, 'exportUserBookingsByEmail' ), @@ -726,11 +727,11 @@ public static function registerUserDataExporters( $exporters ) { /** * Registers all user data erasers ({@link https://developer.wordpress.org/plugins/privacy/adding-the-personal-data-eraser-to-your-plugin/}). * - * @param $erasers + * @param array> $erasers * - * @return mixed + * @return array> */ - public static function registerUserDataErasers( $erasers ) { + public static function registerUserDataErasers( array $erasers ): array { $erasers[ COMMONSBOOKING_PLUGIN_SLUG ] = array( 'eraser_friendly_name' => __( 'CommonsBooking Bookings', 'commonsbooking' ), 'callback' => array( \CommonsBooking\Wordpress\CustomPostType\Booking::class, 'removeUserBookingsByEmail' ), @@ -741,7 +742,7 @@ public static function registerUserDataErasers( $erasers ) { /** * Init hooks. */ - public function init() { + public function init(): void { do_action( 'cmb2_init' ); // Enable CB1 User Fields (needed in case of migration from cb 0.9.x) @@ -860,13 +861,13 @@ public function commonsbooking_load_textdomain() { * * @TODO: Add test if cache is cleared correctly. * - * @param $post_id - * @param $post - * @param $update + * @param int $post_id + * @param \WP_Post $post + * @param bool $update * * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ - public function savePostActions( $post_id, $post, $update ) { + public function savePostActions( int $post_id, \WP_Post $post, bool $update ): void { if ( ! self::isPostCustomPostType( $post ) ) { return; } @@ -880,7 +881,7 @@ public function savePostActions( $post_id, $post, $update ) { } /** - * @return array + * @return string[] */ public static function getCustomPostTypesLabels(): array { return [ @@ -899,11 +900,11 @@ public static function getCustomPostTypesLabels(): array { /** * Function to register our new routes from the controller. */ - public function initRoutes() { + public function initRoutes(): void { // Check if API is activated in settings $api_activated = Settings::getOption( 'commonsbooking_options_api', 'api-activated' ); if ( $api_activated != 'on' ) { - return false; + return; } add_action( @@ -937,7 +938,7 @@ function () { * - Hook appropriate function to button that sends out emails with booking codes to the station. * @see \CommonsBooking\View\BookingCodes::renderDirectEmailRow() */ - public function initBookingcodes() { + public function initBookingcodes(): void { add_action( 'admin_action_cb_download-bookingscodes-csv', array( View\BookingCodes::class, 'renderCSV' ), 10, 0 ); add_action( 'admin_action_cb_email-bookingcodes', array( View\BookingCodes::class, 'emailCodes' ), 10, 0 ); } @@ -949,7 +950,7 @@ public function initBookingcodes() { * * @return string */ - public function setParentFile( $parent_file ): string { + public function setParentFile( string $parent_file ): string { global $current_screen; // Set 'cb-dashboard' as parent for cb post types @@ -986,7 +987,7 @@ public function setParentFile( $parent_file ): string { * * @return string */ - public function getTheContent( $content ): string { + public function getTheContent( string $content ): string { // Check if we're inside the main loop in a single post page. if ( is_single() && in_the_loop() && is_main_query() ) { global $post; @@ -1000,12 +1001,12 @@ public function getTheContent( $content ): string { return $content; } - public function registerUserWidget() { + public function registerUserWidget(): void { register_widget( '\CommonsBooking\Wordpress\Widget\UserWidget' ); } - function AddImageSizes() { + function AddImageSizes(): void { $crop = Settings::getOption( 'commonsbooking_options_templates', 'image_listing_crop' ) == 'on' ? true : false; diff --git a/src/Repository/BookablePost.php b/src/Repository/BookablePost.php index 924eed4a6..3a8e5bd7d 100644 --- a/src/Repository/BookablePost.php +++ b/src/Repository/BookablePost.php @@ -29,7 +29,7 @@ abstract class BookablePost extends PostRepository { * * @param bool $publishedOnly * - * @return array + * @return WP_Post[] * @throws CacheException * @throws InvalidArgumentException */ @@ -153,7 +153,7 @@ abstract protected static function getTaxonomyName(); * @param mixed $userId * @param bool $asModel - Whether the posts should be returned as their respective model class or as WP_Post * - * @return array + * @return WP_Post[]|object[] */ public static function getByUserId( $userId, bool $asModel = false ): array { $cbPosts = []; @@ -214,12 +214,12 @@ abstract protected static function getModelClass(); /** * Returns an array of CB item post objects * - * @param array $args WP Post args - * @param bool $bookable + * @param array $args WP Post args + * @param bool $bookable * - * @return array + * @return object[] */ - public static function get( array $args = array(), bool $bookable = false ) { + public static function get( array $args = array(), bool $bookable = false ): array { $posts = []; $args['post_type'] = static::getPostType(); $args['nopaging'] = true; @@ -268,15 +268,15 @@ public static function get( array $args = array(), bool $bookable = false ) { * Returns related object based on bookable post. * Example: We'd like to have the items bookable at a specific location. With this function we are able to get them. * - * @param $postId - * @param $originType - * @param $relatedType - * @param bool $bookable + * @param int|WP_Post $postId + * @param string $originType + * @param string $relatedType + * @param bool $bookable * - * @return int[] Array of post ids + * @return WP_Post[]|object[] Array of post objects * @throws Exception */ - protected static function getByRelatedPost( $postId, $originType, $relatedType, bool $bookable = false ): array { + protected static function getByRelatedPost( int|WP_Post $postId, string $originType, string $relatedType, bool $bookable = false ): array { if ( ! in_array( $originType, self::$relationalTypes ) || ! in_array( $relatedType, self::$relationalTypes ) ) { throw new Exception( 'invalid type submitted' ); @@ -316,13 +316,13 @@ protected static function getByRelatedPost( $postId, $originType, $relatedType, * Returns array with related posts for post with post id and origin type. * Works only for locations and items! * - * @param $postId - * @param $originType - * @param $relatedType + * @param int|WP_Post $postId + * @param string $originType + * @param string $relatedType * - * @return array + * @return array */ - protected static function getRelatedPosts( $postId, $originType, $relatedType ): array { + protected static function getRelatedPosts( $postId, string $originType, string $relatedType ): array { if ( $postId instanceof WP_Post ) { $postId = $postId->ID; } diff --git a/src/Repository/Booking.php b/src/Repository/Booking.php index 2fb725d54..30c9179a5 100644 --- a/src/Repository/Booking.php +++ b/src/Repository/Booking.php @@ -15,30 +15,30 @@ class Booking extends PostRepository { /** * Returns 0:00 timestamp for day of $timestamp. * - * @param $timestamp + * @param int $timestamp * * @return false|int */ - protected static function getStartTimestamp( $timestamp ) { + protected static function getStartTimestamp( int $timestamp ) { return strtotime( 'midnight', $timestamp ); } /** * Returns 23:59 timestamp for day of $timestamp. * - * @param $startTimestamp + * @param int $startTimestamp * * @return false|int */ - protected static function getEndTimestamp( $startTimestamp ) { + protected static function getEndTimestamp( int $startTimestamp ) { return strtotime( '+23 Hours +59 Minutes +59 Seconds', $startTimestamp ); } /** * Returns bookings ending at day of timestamp. * - * @param int $timestamp - * @param array $customArgs + * @param int $timestamp + * @param array $customArgs * * @return \CommonsBooking\Model\Booking[] * @throws Exception @@ -83,8 +83,8 @@ public static function getEndingBookingsByDate( int $timestamp, array $customArg /** * Returns bookings beginning at day of timestamp. * - * @param int $timestamp - * @param array $customArgs + * @param int $timestamp + * @param array $customArgs * * @return \CommonsBooking\Model\Booking[] * @throws Exception @@ -209,12 +209,12 @@ function ( $post ) { } /** - * @param int $startDate - * @param int $endDate - * @param $locationId - * @param $itemId - * @param array $customArgs - * @param array $postStatus + * @param int $startDate + * @param int $endDate + * @param int|null $locationId + * @param int|null $itemId + * @param array $customArgs + * @param string[] $postStatus * * @return \CommonsBooking\Model\Booking[] * @throws Exception @@ -222,8 +222,8 @@ function ( $post ) { public static function getByTimerange( int $startDate, int $endDate, - $locationId = null, - $itemId = null, + ?int $locationId = null, + ?int $itemId = null, array $customArgs = [], array $postStatus = [ 'confirmed', 'unconfirmed' ] ): array { @@ -279,8 +279,10 @@ public static function getByTimerange( /** * Returns all bookings, allowed to see for user. * + * @param \WP_User $user * @param bool $asModel if true, returns as Booking array, if false, return int array (defaults to false) * @param int|null $minTimestamp + * @param string[] $postStatus * * @return \CommonsBooking\Model\Booking[]|int[] * @throws Exception @@ -288,7 +290,7 @@ public static function getByTimerange( public static function getForUser( \WP_User $user, bool $asModel = false, - $minTimestamp = null, + ?int $minTimestamp = null, array $postStatus = [ 'canceled', 'confirmed', 'unconfirmed' ] ): array { $customId = $user->ID; @@ -327,16 +329,17 @@ function ( $post ) use ( $user ) { /** * Returns all bookings, allowed to see/edit for current user. * - * @param bool $asModel - * @param null $startDate + * @param bool $asModel + * @param int|null $startDate + * @param string[] $postStatus * - * @return array + * @return \CommonsBooking\Model\Booking[]|int[] * @throws Exception */ public static function getForCurrentUser( bool $asModel = false, - $startDate = null, - $postStatus = [ 'canceled', 'confirmed', 'unconfirmed' ] + ?int $startDate = null, + array $postStatus = [ 'canceled', 'confirmed', 'unconfirmed' ] ): array { if ( ! is_user_logged_in() ) { return []; @@ -351,12 +354,12 @@ public static function getForCurrentUser( * Returns bookings. This uses the CommonsBooking\Repository\Timeframe::get() method which * is not based on the WP_Query class but will perform its own SQL query. * - * @param array $locations - * @param array $items + * @param int[] $locations + * @param int[] $items * @param string|null $date Date-String in format YYYY-mm-dd * @param bool $returnAsModel if true, returns booking model, if false return int array (defaults to false) * @param int|null $minTimestamp - * @param array $postStatus + * @param string[] $postStatus * * @return int[]|\CommonsBooking\Model\Booking[] * @throws Exception @@ -385,10 +388,11 @@ public static function get( * This is to prevent timeouts for bigger queries such as data exports. As opposed to the getForUser() function, * this function will use the WP_Query class to perform the query allowing us to use the pagination features of WP_Query. * - * @param \WP_User $user The user for which to get the bookings. - * @param int $page The current page that is processed. - * @param int $perPage The number of bookings per page. A lower number will result in faster queries. - * @param array $customArgs Valid WP_Query args array. + * @param \WP_User $user The user for which to get the bookings. + * @param int $page The current page that is processed. + * @param int $perPage The number of bookings per page. A lower number will result in faster queries. + * @param array $customArgs Valid WP_Query args array. + * @param string[] $postStatus * * @return \CommonsBooking\Model\Booking[] An array of Booking models. */ @@ -396,8 +400,8 @@ public static function getForUserPaginated( \WP_User $user, int $page = 1, int $perPage = 10, - $customArgs = [], - $postStatus = [ 'confirmed', 'unconfirmed', 'canceled', 'publish', 'inherit' ] + array $customArgs = [], + array $postStatus = [ 'confirmed', 'unconfirmed', 'canceled', 'publish', 'inherit' ] ): array { $args = array( 'author' => $user->ID, @@ -445,15 +449,15 @@ public static function getByRestriction( \CommonsBooking\Model\Restriction $rest * This is used to check if the given parameters are overlapping with existing bookings. * The given $postID will be excluded from the result so that the given booking will not be counted as overlapping. * - * @param $itemId - * @param $locationId + * @param int $itemId + * @param int $locationId * @param int $startDate * @param int $endDate * @param int|null $postId * * @return \CommonsBooking\Model\Booking[] empty array if none are found */ - public static function getExistingBookings( $itemId, $locationId, $startDate, $endDate, $postId = null ): array { + public static function getExistingBookings( int $itemId, int $locationId, int $startDate, int $endDate, ?int $postId = null ): array { // Get existing bookings for defined parameters $existingBookingsInRange = self::getByTimerange( @@ -477,7 +481,7 @@ public static function getExistingBookings( $itemId, $locationId, $startDate, $e /** * Will take a valid WP_Query args array and return an array of Booking models. * - * @param array $args + * @param array $args * * @return \CommonsBooking\Model\Booking[] * @throws Exception diff --git a/src/Repository/BookingCodes.php b/src/Repository/BookingCodes.php index dd61efed9..68f5ebf44 100644 --- a/src/Repository/BookingCodes.php +++ b/src/Repository/BookingCodes.php @@ -41,7 +41,7 @@ class BookingCodes { * @param int|null $endDate - Where to get booking codes to (timestamp) * @param int $advanceGenerationDays - Open-ended timeframes: If 0, generate code(s) until today. If >0, generate additional codes after today * - * @return array + * @return array * @throws BookingCodeException */ public static function getCodes( int $timeframeId, ?int $startDate = null, ?int $endDate = null, int $advanceGenerationDays = self::ADVANCE_GENERATION_DAYS ): array { @@ -142,7 +142,7 @@ public static function getCodes( int $timeframeId, ?int $startDate = null, ?int * * @return void works by reference on param $bookingCodes */ - private static function backwardCompatibilityFilter( &$bookingCodes, $preferredTimeframeId, $preferredLocationId ) { + private static function backwardCompatibilityFilter( mixed &$bookingCodes, int $preferredTimeframeId, int $preferredLocationId ): void { $filteredCodes = []; $codesByDate = []; @@ -415,7 +415,7 @@ public static function persist( BookingCode $bookingCode, $timeframeId = 0, $loc /** * Will get the configured booking codes from the settings and return them as an array. * - * @return array - Array of booking codes, empty array if no booking codes are configured. + * @return array Array of booking codes, empty array if no booking codes are configured. */ private static function getCodesArray(): array { $bookingCodes = Settings::getOption( 'commonsbooking_options_bookingcodes', 'bookingcodes' ); diff --git a/src/Repository/CB1.php b/src/Repository/CB1.php index 0b519ada2..4681587af 100644 --- a/src/Repository/CB1.php +++ b/src/Repository/CB1.php @@ -56,18 +56,18 @@ public static function isInstalled() { /** * Get the old CB1 location post type posts * - * @return array + * @return \WP_Post[] */ - public static function getLocations() { + public static function getLocations(): array { return self::get( self::$LOCATION_TYPE_ID ); } /** - * @param $postType + * @param string $postType * - * @return array + * @return \WP_Post[] */ - protected static function get( $postType ) { + protected static function get( string $postType ): array { $posts = []; $args = array( 'post_type' => $postType, @@ -85,9 +85,9 @@ protected static function get( $postType ) { /** * Get the old CB1 item post type posts * - * @return array + * @return \WP_Post[] */ - public static function getItems() { + public static function getItems(): array { return self::get( self::$ITEM_TYPE_ID ); } @@ -148,7 +148,7 @@ public static function getBookingCodes() { * * @return ?string */ - public static function getBookingCode( $id ): ?string { + public static function getBookingCode( int $id ): ?string { global $wpdb; $table_bookingcodes = $wpdb->prefix . self::$BOOKINGCODES_TABLE; @@ -209,7 +209,7 @@ protected static function getCB2PostIdByType( int $id, string $type ) { * * @return false|int */ - public static function getCB2ItemId( $locationId ) { + public static function getCB2ItemId( int $locationId ): int|false { return self::getCB2PostIdByType( $locationId, \CommonsBooking\Wordpress\CustomPostType\Item::$postType ); } @@ -218,7 +218,7 @@ public static function getCB2ItemId( $locationId ) { * * @return false|int */ - public static function getCB2TimeframeId( $timeframeId ) { + public static function getCB2TimeframeId( int $timeframeId ): int|false { return self::getCB2PostIdByType( $timeframeId, \CommonsBooking\Wordpress\CustomPostType\Timeframe::$postType ); } @@ -229,7 +229,7 @@ public static function getCB2TimeframeId( $timeframeId ) { * * @return ?int */ - public static function getCB2PostIdByCB1Id( $id ): ?int { + public static function getCB2PostIdByCB1Id( int $id ): ?int { global $wpdb; $table_postmeta = $wpdb->prefix . 'postmeta'; diff --git a/src/Repository/Item.php b/src/Repository/Item.php index ada54a228..dabd5c25e 100644 --- a/src/Repository/Item.php +++ b/src/Repository/Item.php @@ -9,14 +9,13 @@ class Item extends BookablePost { /** * Returns array with items at location based on bookable timeframes. * - * @param $locationId - * + * @param int $locationId * @param bool $bookable * - * @return array + * @return array * @throws Exception */ - public static function getByLocation( $locationId, bool $bookable = false ): array { + public static function getByLocation( int $locationId, bool $bookable = false ): array { return self::getByRelatedPost( $locationId, 'location', 'item', $bookable ); } diff --git a/src/Repository/Location.php b/src/Repository/Location.php index ae3b881c1..e8198681e 100644 --- a/src/Repository/Location.php +++ b/src/Repository/Location.php @@ -9,14 +9,13 @@ class Location extends BookablePost { /** * Returns array with locations for item based on bookable timeframes. * - * @param $itemId - * + * @param int $itemId * @param bool $bookable * - * @return array + * @return array * @throws Exception */ - public static function getByItem( $itemId, bool $bookable = false ): array { + public static function getByItem( int $itemId, bool $bookable = false ): array { return self::getByRelatedPost( $itemId, 'item', 'location', $bookable ); } diff --git a/src/Repository/PostRepository.php b/src/Repository/PostRepository.php index 16135751a..96e27493d 100644 --- a/src/Repository/PostRepository.php +++ b/src/Repository/PostRepository.php @@ -18,7 +18,7 @@ abstract class PostRepository { * @throws \CommonsBooking\Psr\Cache\CacheException * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ - public static function getPostById( $postId ) { + public static function getPostById( int $postId ) { $cacheItem = Plugin::getCacheItem(); if ( $cacheItem ) { return $cacheItem; diff --git a/src/Repository/Restriction.php b/src/Repository/Restriction.php index 38cc197db..3d75d699f 100644 --- a/src/Repository/Restriction.php +++ b/src/Repository/Restriction.php @@ -12,11 +12,11 @@ class Restriction extends PostRepository { /** * Returns active restrictions. * - * @param array $locations one or more location ids to filter - * @param array $items one or more item ids to filter + * @param int[] $locations one or more location ids to filter + * @param int[] $items one or more item ids to filter * @param string|null $date if provided, filters restrictions to be valid on the given date * @param bool $returnAsModel returns array of models instead of ids, default false (returns ids) - * @param int $minTimestamp if provided, returns restrictions where rep-end > min-timestamp. default null + * @param int|null $minTimestamp if provided, returns restrictions where rep-end > min-timestamp. default null * @param string[] $postStatus filters for given list of status, defaults to all WordPress post status enums * * @return \CommonsBooking\Model\Restriction[] @@ -27,7 +27,7 @@ public static function get( array $items = [], ?string $date = null, bool $returnAsModel = false, - $minTimestamp = null, + ?int $minTimestamp = null, array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ] ): array { $customCacheKey = serialize( $postStatus ); @@ -38,7 +38,7 @@ public static function get( } else { $posts = self::queryPosts( $date, $minTimestamp, $postStatus ); - if ( $posts && count( $posts ) ) { + if ( $posts ) { $posts = Wordpress::flattenWpdbResult( $posts ); // If there are locations or items to be filtered, we iterate through @@ -64,13 +64,13 @@ public static function get( * Queries restriction posts from db. * Only queries active restrictions. * - * @param $date - * @param $minTimestamp int checks if rep-end > minTimestamp (0:00) - * @param $postStatus + * @param string|null $date + * @param int|null $minTimestamp checks if rep-end > minTimestamp (0:00) + * @param string[] $postStatus * - * @return array|object|null + * @return \WP_Post[] */ - private static function queryPosts( $date, $minTimestamp, $postStatus ) { + private static function queryPosts( ?string $date, ?int $minTimestamp, array $postStatus ): array { $cacheItem = Plugin::getCacheItem(); if ( $cacheItem ) { return $cacheItem; @@ -109,11 +109,11 @@ private static function queryPosts( $date, $minTimestamp, $postStatus ) { /** * Returns filter to query be minimum timestamp. * - * @param $minTimestamp + * @param int $minTimestamp * * @return string */ - private static function getMinTimestampQuery( $minTimestamp ): string { + private static function getMinTimestampQuery( int $minTimestamp ): string { global $wpdb; $table_postmeta = $wpdb->prefix . 'postmeta'; @@ -141,11 +141,11 @@ private static function getMinTimestampQuery( $minTimestamp ): string { /** * Returns query to filter by date. * - * @param $date + * @param string $date * * @return string */ - private static function getDateQuery( $date ): string { + private static function getDateQuery( string $date ): string { global $wpdb; $table_postmeta = $wpdb->prefix . 'postmeta'; @@ -196,11 +196,11 @@ private static function getActiveQuery(): string { * WARNING: This method will filter out posts that are only queried by item OR location. * Meaning, if a restriction is created that has a location and an item, but the query only contains the location, the restriction will not be returned. * - * @param array $posts - * @param array $locations - * @param array $items + * @param \WP_Post[] $posts + * @param int[] $locations + * @param int[] $items * - * @return array + * @return \WP_Post[] */ private static function filterPosts( array $posts, array $locations, array $items ): array { return array_filter( @@ -251,12 +251,12 @@ function ( $post ) use ( $locations, $items ) { /** * Casts all posts in the array to Restriction objects. * - * @param $posts + * @param \WP_Post[] $posts * - * @return mixed + * @return \CommonsBooking\Model\Restriction[] * @throws Exception */ - private static function castPostsToRestrictions( $posts ) { + private static function castPostsToRestrictions( array $posts ): array { foreach ( $posts as &$post ) { $post = new \CommonsBooking\Model\Restriction( $post ); } diff --git a/src/Repository/Timeframe.php b/src/Repository/Timeframe.php index 3130c26c5..080a5cad7 100644 --- a/src/Repository/Timeframe.php +++ b/src/Repository/Timeframe.php @@ -19,14 +19,14 @@ class Timeframe extends PostRepository { /** * Returns only bookable timeframes. * - * @param array $locations - * @param array $items + * @param int[] $locations + * @param int[] $items * @param string|null $date * @param bool $returnAsModel - * @param $minTimestamp - * @param array $postStatus + * @param int|null $minTimestamp + * @param string[] $postStatus * - * @return array + * @return int[]|\WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] * @throws Exception */ public static function getBookable( @@ -34,7 +34,7 @@ public static function getBookable( array $items = [], ?string $date = null, bool $returnAsModel = false, - $minTimestamp = null, + ?int $minTimestamp = null, array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ] ): array { return self::get( @@ -51,14 +51,14 @@ public static function getBookable( /** * Returns only bookable timeframes for current user. * - * @param array $locations - * @param array $items + * @param int[] $locations + * @param int[] $items * @param string|null $date * @param bool $returnAsModel - * @param $minTimestamp - * @param array $postStatus + * @param int|null $minTimestamp + * @param string[] $postStatus * - * @return array + * @return int[]|\WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] * @throws Exception */ public static function getBookableForCurrentUser( @@ -66,7 +66,7 @@ public static function getBookableForCurrentUser( array $items = [], ?string $date = null, bool $returnAsModel = false, - $minTimestamp = null, + ?int $minTimestamp = null, array $postStatus = [ 'confirmed', 'unconfirmed', 'publish', 'inherit' ] ): array { @@ -93,9 +93,9 @@ public static function getBookableForCurrentUser( * TODO: Investigate * This function is not based on the WP_Query class, probably because of performance reasons. * - * @param array $locations - * @param array $items - * @param array $types + * @param int[] $locations + * @param int[] $items + * @param int[] $types * @param string|null $date Date-String in format YYYY-mm-dd * @param bool $returnAsModel if true, returns as custom wp-post model, if false, return wp-post or int array (defaults to false) * @param int|null $minTimestamp @@ -165,9 +165,9 @@ public static function get( /** * Will get all timeframes in the database to perform mass operations on (like migrations). * - * @param int $page - * @param int $perPage - * @param array $customArgs + * @param int $page + * @param int $perPage + * @param array $customArgs * * @return \stdClass Properties: array posts, int totalPosts, int totalPages, bool done * @throws Exception @@ -218,15 +218,16 @@ public static function getAllPaginated( * We need this for the Timeframe Export, so that it does not time out on large datasets. * This function is in general slower than the getInRange function. But it can be used in AJAX requests. * - * @param int $minTimestamp - * @param int|null $maxTimestamp - * @param int $page - * @param int $perPage - * @param array $types - * @param bool $asModel - * @param array $customArgs - * - * @return array An array with the keys 'posts', 'totalPages' and 'done' (bool) to indicate if there are more posts to fetch + * @param int $minTimestamp + * @param int|null $maxTimestamp + * @param int $page + * @param int $perPage + * @param int[] $types + * @param string[] $postStatus + * @param bool $asModel + * @param array $customArgs + * + * @return array An array with the keys 'posts', 'totalPages' and 'done' (bool) to indicate if there are more posts to fetch */ public static function getInRangePaginated( int $minTimestamp, @@ -240,7 +241,7 @@ public static function getInRangePaginated( \CommonsBooking\Wordpress\CustomPostType\Timeframe::REPAIR_ID, \CommonsBooking\Wordpress\CustomPostType\Timeframe::OFF_HOLIDAYS_ID, ], - $postStatus = [ 'confirmed', 'unconfirmed', 'canceled', 'publish', 'inherit' ], + array $postStatus = [ 'confirmed', 'unconfirmed', 'canceled', 'publish', 'inherit' ], bool $asModel = false, array $customArgs = [] ): array { @@ -323,9 +324,9 @@ function ( $post ) use ( $args ) { * * Why? It's because of performance. We use the ids as base set for following filter queries. * - * @param array $types the types of timeframes to return, will return default set when not set - * @param array $items the items that the timeframes should be applicable to, will return all if not set - * @param array $locations the locations that the timeframes should be applicable to, will return all if not set + * @param int[] $types the types of timeframes to return, will return default set when not set + * @param int[] $items the items that the timeframes should be applicable to, will return all if not set + * @param int[] $locations the locations that the timeframes should be applicable to, will return all if not set * * @since 2.9.0 Supports now single and multi selection for items and locations * @@ -425,6 +426,12 @@ function ( $post ) { * * @since 2.9.0 Supports now single and multi selection for items and locations * + * @param string $joinAlias + * @param string $table_postmeta + * @param int[] $entities + * @param string $singleEntityKey + * @param string $multiEntityKey + * * @return string join statement */ private static function getEntityQuery( string $joinAlias, string $table_postmeta, array $entities, string $singleEntityKey, string $multiEntityKey ): string { @@ -457,13 +464,13 @@ private static function getEntityQuery( string $joinAlias, string $table_postmet * Queries for posts within $postIds and filters them by $date and/or $minTimestamp and $postStatus. * Why? This kind of filtering is needed nearly everywhere in commonsbooking. * - * @param string|null $date - * @param int|null $minTimestamp - * @param int|null $maxTimestamp - * @param array $postIds - * @param array $postStatus + * @param string|null $date + * @param int|null $minTimestamp + * @param int|null $maxTimestamp + * @param string[]|int[] $postIds + * @param string[] $postStatus * - * @return array + * @return \WP_Post[] */ private static function getPostsByBaseParams( ?string $date, ?int $minTimestamp, ?int $maxTimestamp, array $postIds, array $postStatus ): array { $cacheItem = Plugin::getCacheItem(); @@ -624,10 +631,10 @@ private static function getTimerangeQuery( string $table_postmeta, int $minTimes /** * Wrapper function for all filters. * - * @param array $posts + * @param \WP_Post[] $posts * @param string|null $date * - * @return array + * @return \WP_Post[] */ private static function filterTimeframes( array $posts, ?string $date ): array { // Filter by configured days @@ -642,10 +649,10 @@ private static function filterTimeframes( array $posts, ?string $date ): array { * Why? Because you can define days for your timeframe. Here's the point where we make sure, that only these days * are taken into account. * - * @param array $posts + * @param \WP_Post[] $posts * @param string|null $date string format: YYYY-mm-dd * - * @return array + * @return \WP_Post[] * @throws \CommonsBooking\Psr\Cache\InvalidArgumentException */ private static function filterTimeframesByConfiguredDays( array $posts, ?string $date ): array { @@ -681,11 +688,11 @@ function ( $post ) use ( $date ) { * Filters timeframes from array, which aren't bookable because of the max booking days in * advance setting. * - * @param $posts + * @param \WP_Post[] $posts * - * @return array + * @return \WP_Post[] */ - private static function filterTimeframesByMaxBookingDays( $posts ): array { + private static function filterTimeframesByMaxBookingDays( array $posts ): array { return array_filter( $posts, function ( $post ) { @@ -710,11 +717,11 @@ function ( $post ) { * Filters timeframes from array, * removes timeframes which are not bookable by current user * - * @param $posts + * @param \WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] $posts * - * @return array + * @return \WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] */ - private static function filterTimeframesForCurrentUser( $posts ): array { + private static function filterTimeframesForCurrentUser( array $posts ): array { return array_filter( $posts, function ( $post ) { @@ -768,9 +775,10 @@ function ( $timeframe ) use ( $startTimestamp, $endTimestamp ) { * * @param int[]|\WP_Post[] $posts * + * @return void * @throws Exception */ - private static function castPostsToModels( &$posts ) { + private static function castPostsToModels( array &$posts ): void { foreach ( $posts as &$post ) { // If we have a standard timeframe if ( $post->post_type == \CommonsBooking\Wordpress\CustomPostType\Timeframe::getPostType() ) { @@ -833,20 +841,20 @@ public static function getByLocationItemTimestamp( int $locationId, int $itemId, * Why? We often need timeframes for a specific timerange. For example in the calendar the default range is * three months. Another example is the table view. * - * @param $minTimestamp - * @param $maxTimestamp + * @param int $minTimestamp + * @param int $maxTimestamp * @param int[] $locations * @param int[] $items - * @param array $types + * @param int[] $types * @param bool $returnAsModel * @param string[] $postStatus * - * @return array + * @return int[]|\WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] * @throws Exception */ public static function getInRange( - $minTimestamp, - $maxTimestamp, + int $minTimestamp, + int $maxTimestamp, array $locations = [], array $items = [], array $types = [], @@ -903,20 +911,20 @@ public static function getInRange( /** * Returns timeframes in explicit timerange that are bookable by the current user. * - * @param $minTimestamp - * @param $maxTimestamp + * @param int $minTimestamp + * @param int $maxTimestamp * @param int[] $locations * @param int[] $items - * @param array $types + * @param int[] $types * @param bool $returnAsModel * @param string[] $postStatus * - * @return array + * @return int[]|\WP_Post[]|\CommonsBooking\Model\Timeframe[]|\CommonsBooking\Model\Booking[] * @throws Exception */ public static function getInRangeForCurrentUser( - $minTimestamp, - $maxTimestamp, + int $minTimestamp, + int $maxTimestamp, array $locations = [], array $items = [], array $types = [], diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php index b486617e0..3bfa95b79 100644 --- a/src/Repository/UserRepository.php +++ b/src/Repository/UserRepository.php @@ -90,7 +90,7 @@ public static function getOwners(): array { /** * Returns an array of all User Roles as roleID => translated role name * - * @return array + * @return array */ public static function getUserRoles(): array { global $wp_roles; @@ -115,8 +115,8 @@ public static function getUserRoles(): array { * * @since 2.9.0 * - * @param int $userID - * @param string|array $roles + * @param int $userID + * @param string|string[] $roles * @return bool */ public static function userHasRoles( int $userID, $roles ): bool { diff --git a/src/Service/Booking.php b/src/Service/Booking.php index 40c64c31b..7410f73b7 100644 --- a/src/Service/Booking.php +++ b/src/Service/Booking.php @@ -40,7 +40,7 @@ public static function cleanupBookings() { } } - private static function sendMessagesForDay( int $tsDate, bool $onStartDate, Message $message ) { + private static function sendMessagesForDay( int $tsDate, bool $onStartDate, Message $message ): void { if ( $onStartDate ) { $bookings = \CommonsBooking\Repository\Booking::getBeginningBookingsByDate( $tsDate ); } else { @@ -63,7 +63,7 @@ private static function sendMessagesForDay( int $tsDate, bool $onStartDate, Mess * * @throws \Exception */ - public static function sendReminderMessage() { + public static function sendReminderMessage(): void { if ( Settings::getOption( 'commonsbooking_options_reminder', 'pre-booking-reminder-activate' ) != 'on' ) { return; @@ -80,7 +80,7 @@ public static function sendReminderMessage() { * * @throws \Exception */ - public static function sendFeedbackMessage() { + public static function sendFeedbackMessage(): void { if ( Settings::getOption( 'commonsbooking_options_reminder', 'post-booking-notice-activate' ) != 'on' ) { return; @@ -92,15 +92,15 @@ public static function sendFeedbackMessage() { self::sendMessagesForDay( $endDate, false, $message ); } - public static function sendBookingStartLocationReminderMessage() { + public static function sendBookingStartLocationReminderMessage(): void { self::sendLocationBookingReminderMessage( 'start' ); } - public static function sendBookingEndLocationReminderMessage() { + public static function sendBookingEndLocationReminderMessage(): void { self::sendLocationBookingReminderMessage( 'end' ); } - protected static function sendLocationBookingReminderMessage( string $type ) { + protected static function sendLocationBookingReminderMessage( string $type ): void { if ( Settings::getOption( 'commonsbooking_options_reminder', 'booking-' . $type . '-location-reminder-activate' ) != 'on' ) { return; diff --git a/src/Service/BookingCodes.php b/src/Service/BookingCodes.php index 612b61151..bb0b3581c 100644 --- a/src/Service/BookingCodes.php +++ b/src/Service/BookingCodes.php @@ -58,7 +58,7 @@ public static function sendBookingCodesMessage(): void { * * @param int $timeframeId * - * @return array|false Parameters. + * @return array{from: int, to: int, nextCronEventTs: int}|false Parameters. */ public static function getCronParams( $timeframeId ) { $tsCurrentCronEvent = get_post_meta( $timeframeId, \CommonsBooking\View\BookingCodes::NEXT_CRON_EMAIL, true ); diff --git a/src/Service/BookingRule.php b/src/Service/BookingRule.php index bbe26f427..bd3aaf8d6 100644 --- a/src/Service/BookingRule.php +++ b/src/Service/BookingRule.php @@ -56,13 +56,13 @@ class BookingRule { * Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter. * These parameters are text fields that can be used to configure the rule. We can currently only support 2 parameters * - * @var array + * @var array> */ protected array $params = []; /** * Array where first element is the description of the select field and the second element is an associative array of the select options * - * @var array + * @var array */ protected array $selectParam; /** @@ -81,8 +81,8 @@ class BookingRule { * @param String $description A detailed description of the rule, will be shown to the configuration admin * @param String $errorMessage The static error message that will be shown to the booking user if the rule is not met * @param Closure $validationFunction The function that will be called to validate the rule. This is a closure that takes a Booking object, the passed args and an array of the selected terms as arguments - * @param array $params Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter. Only 2 parameters are currently supported. They have to be integer values. - * @param array $selectParam Array where first element is the description of the select field and the second element is an associative array of the select options + * @param array> $params Array of associative arrays in which the key "title" is the title of the parameter and "description" is the description of the parameter. Only 2 parameters are currently supported. They have to be integer values. + * @param array $selectParam Array where first element is the description of the select field and the second element is an associative array of the select options * * @throws BookingRuleException */ @@ -126,7 +126,10 @@ public function getDescription(): string { * * @return string */ - public function getErrorMessage( $args = [] ): string { + /** + * @param array $args + */ + public function getErrorMessage( array $args = [] ): string { $errorMessage = commonsbooking_sanitizeHTML( $this->errorMessage ); if ( $this->errorFromArgs !== null ) { $errorMessageFunction = $this->errorFromArgs; @@ -145,7 +148,7 @@ public function getName(): string { } /** - * @return array + * @return array> */ public function getParams(): array { return $this->params; @@ -161,7 +164,7 @@ public function getValidationFunction(): Closure { /** * Create associative array for CMB2 select * - * @return array + * @return array */ public static function getRulesForSelect(): array { $assoc_array = []; @@ -344,11 +347,11 @@ public static function init(): array { * If the user has bookings at the same day it will return an array with conflicting bookings * If there is no booking at the same day, will return null * - * @param Booking $booking - * @param array $args - * @param bool|array $appliedTerms + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms * - * @return array|null + * @return array|null * @throws Exception */ public static function checkSimultaneousBookings( Booking $booking, array $args = [], $appliedTerms = false ): ?array { @@ -371,11 +374,11 @@ function ( $userBooking ) use ( $booking ) { * If the user has chained too many days in that timespan will return the conflicting bookings * If the user bookings are NOT above the limit, will return null * - * @param Booking $booking - * @param array $args - * @param bool|array $appliedTerms + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms * - * @return array|null + * @return array|null * @throws Exception */ public static function checkChainBooking( Booking $booking, array $args = [], $appliedTerms = false ): ?array { @@ -432,11 +435,11 @@ function ( Booking $collectionItem ) use ( $booking ) { * Params: $args[0} = The amount of days the user is allowed to book * $args[1] = The period over which the user is allowed to book * - * @param Booking $booking - * @param array $args - * @param bool|array $appliedTerms + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms * - * @return array + * @return array|null * @throws Exception */ public static function checkMaxBookingDays( Booking $booking, array $args, $appliedTerms = false ): ?array { @@ -456,7 +459,12 @@ public static function checkMaxBookingDays( Booking $booking, array $args, $appl return self::checkBookingRangeForDays( $startOfPeriod, $endOfPeriod, $booking, $appliedTerms, $allowedBookedDays ); } - public static function maxBookingDaysErrorMessage( $args ) { + /** + * @param array $args + * + * @return string + */ + public static function maxBookingDaysErrorMessage( array $args ): string { $allowedBookedDays = $args[0]; $periodDays = $args[1]; @@ -472,11 +480,11 @@ public static function maxBookingDaysErrorMessage( $args ) { * $args[1] : Unused * $args[2]: The day on which the counter is reset, default: 1 = sunday, 2 = monday, ..., 7 = saturday * - * @param Booking $booking - * @param array $args - * @param bool|array $appliedTerms + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms * - * @return array|null + * @return array|null */ public static function checkMaxBookingDaysPerWeek( Booking $booking, array $args, $appliedTerms = false ): ?array { $allowedBookableDays = $args[0]; @@ -487,6 +495,11 @@ public static function checkMaxBookingDaysPerWeek( Booking $booking, array $args return self::checkBookingRangeForDays( $range[0], $range[1], $booking, $appliedTerms, $allowedBookableDays ); } + /** + * @param array $args + * + * @return string + */ public static function maxDaysWeekErrorMessage( array $args ): string { $maxDays = $args[0]; $resetDay = $args[2] - 1; @@ -497,6 +510,13 @@ public static function maxDaysWeekErrorMessage( array $args ): string { return sprintf( __( 'You can only book %1$s days per week, please try again after %2$s next week.', 'commonsbooking' ), $maxDays, $resetDayString ); } + /** + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms + * + * @return array|null + */ public static function checkMaxBookingsWeek( Booking $booking, array $args, $appliedTerms = false ): ?array { $allowedTotalBookings = $args[0]; // default is sunday @@ -506,6 +526,11 @@ public static function checkMaxBookingsWeek( Booking $booking, array $args, $app return self::checkBookingAmount( $range[0], $range[1], $booking, $appliedTerms, $allowedTotalBookings ); } + /** + * @param array $args + * + * @return string + */ public static function maxBookingsWeekErrorMessage( array $args ): string { $maxDays = $args[0]; $resetDay = $args[2]; @@ -524,11 +549,11 @@ public static function maxBookingsWeekErrorMessage( array $args ): string { * $args[1] : Unused * $args[2]: The day on which the counter is reset, from 0 to max 31. * - * @param Booking $booking - * @param array $args - * @param bool|array $appliedTerms + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms * - * @return array|null + * @return array|null */ public static function checkMaxBookingDaysPerMonth( Booking $booking, array $args, $appliedTerms = false ): ?array { $allowedBookableDays = $args[0]; @@ -538,6 +563,11 @@ public static function checkMaxBookingDaysPerMonth( Booking $booking, array $arg return self::checkBookingRangeForDays( $range[0], $range[1], $booking, $appliedTerms, $allowedBookableDays ); } + /** + * @param array $args + * + * @return string + */ public static function maxDaysMonthErrorMessage( array $args ): string { $maxDays = $args[0]; $resetDay = $args[2]; @@ -546,6 +576,13 @@ public static function maxDaysMonthErrorMessage( array $args ): string { return sprintf( __( 'You can only book %1$s days per month, please try again after the %2$s. next month.', 'commonsbooking' ), $maxDays, $resetDay ); } + /** + * @param Booking $booking + * @param array $args + * @param bool|array $appliedTerms + * + * @return array|null + */ public static function checkMaxBookingsMonth( Booking $booking, array $args, $appliedTerms = false ): ?array { $allowedTotalBookings = $args[0]; $resetDay = $args[2]; @@ -554,6 +591,11 @@ public static function checkMaxBookingsMonth( Booking $booking, array $args, $ap return self::checkBookingAmount( $range[0], $range[1], $booking, $appliedTerms, $allowedTotalBookings ); } + /** + * @param array $args + * + * @return string + */ public static function maxBookingsMonthErrorMessage( array $args ): string { $maxDays = $args[0]; $resetDay = $args[2]; @@ -626,11 +668,11 @@ private static function getBookingMonthRange( Booking $booking, int $resetDay ): * * Is often used by BookingRule to determine if a booking should be taken into consideration * - * @param Booking[] $bookings - * @param \WP_User $user - * @param $terms + * @param Booking[] $bookings + * @param \WP_User $user + * @param bool|array $terms * - * @return array|null + * @return Booking[]|null */ private static function filterBookingsForTermsAndUser( array $bookings, \WP_User $user, $terms ): ?array { $filteredTerms = Booking::filterTermsApply( $bookings, $terms ); @@ -661,7 +703,7 @@ public static function hasDefaultSettings(): bool { * * @return Booking[] */ - private static function filterEmptyBookings( array $bookings ) { + private static function filterEmptyBookings( array $bookings ): array { return array_filter( $bookings, fn( $booking ) => $booking->getDuration() > 0 ); } @@ -672,13 +714,13 @@ private static function filterEmptyBookings( array $bookings ) { * Will return the conflicting bookings if a user has too many in the range. * Will also consider the setting if cancelled bookings should be considered. * - * @param DateTime $startOfRange - * @param DateTime $endOfRange - * @param Booking $booking - * @param array|false $appliedTerms - * @param int $allowedBookableDays + * @param DateTime $startOfRange + * @param DateTime $endOfRange + * @param Booking $booking + * @param bool|array $appliedTerms + * @param int $allowedBookableDays * - * @return array|null - conflicting bookings in order of post_date + * @return Booking[]|null - conflicting bookings in order of post_date * @throws Exception */ private static function checkBookingRangeForDays( DateTime $startOfRange, DateTime $endOfRange, Booking $booking, $appliedTerms, int $allowedBookableDays ): ?array { @@ -723,16 +765,16 @@ private static function checkBookingRangeForDays( DateTime $startOfRange, DateTi * Will return the conflicting bookings if a user has too many in the range. * Cancelled bookings will be considered when they were cancelled after the start of the range. * - * @param DateTime $startOfRange - * @param DateTime $endOfRange - * @param Booking $booking - * @param $appliedTerms - * @param int $allowedTotalBookings + * @param DateTime $startOfRange + * @param DateTime $endOfRange + * @param Booking $booking + * @param bool|array $appliedTerms + * @param int $allowedTotalBookings * * @return Booking[]|null * @throws Exception */ - private static function checkBookingAmount( DateTime $startOfRange, DateTime $endOfRange, Booking $booking, $appliedTerms, int $allowedTotalBookings ) { + private static function checkBookingAmount( DateTime $startOfRange, DateTime $endOfRange, Booking $booking, $appliedTerms, int $allowedTotalBookings ): ?array { $countedPostTypes = [ 'confirmed' ]; if ( Settings::getOption( 'commonsbooking_options_restrictions', 'bookingrules-count-cancelled' ) == 'on' ) { $countedPostTypes[] = 'canceled'; diff --git a/src/Service/BookingRuleApplied.php b/src/Service/BookingRuleApplied.php index a9db1e2b6..66577a1de 100644 --- a/src/Service/BookingRuleApplied.php +++ b/src/Service/BookingRuleApplied.php @@ -20,12 +20,15 @@ class BookingRuleApplied extends BookingRule { private bool $appliesToAll; + /** @var array */ private array $appliedTerms; + /** @var array */ private array $appliedParams; /** * @var int|string */ private $appliedSelectParam; + /** @var string[] */ private array $excludedRoles; /** @@ -51,8 +54,8 @@ public function __construct( BookingRule $rule ) { /** * Will set what this Booking Rule applies to, either needs to be all or at least one category * - * @param bool $appliesToAll - * @param array $appliedTerms + * @param bool $appliesToAll + * @param array $appliedTerms * * @throws BookingRuleException */ @@ -67,8 +70,8 @@ public function setAppliesToWhat( bool $appliesToAll, array $appliedTerms = [] ) /** * Will set the necessary params for the BookingRule to work * - * @param array $paramsToSet needs to be numeric - * @param int|string $selectParam needs to be numeric + * @param array $paramsToSet needs to be numeric + * @param int|string|null $selectParam needs to be numeric * * @throws BookingRuleException - if not enough params were specified for the BookingRule */ @@ -96,7 +99,7 @@ public function setAppliedParams( array $paramsToSet, $selectParam ): void { /** * Sets the roles that the rule will not apply to * - * @param array $excludedRoles + * @param string[] $excludedRoles */ public function setExcludedRoles( array $excludedRoles ): void { $this->excludedRoles = $excludedRoles; @@ -109,7 +112,7 @@ public function setExcludedRoles( array $excludedRoles ): void { * * @param Booking $booking - The booking object to check for rule compliance * - * @return array|null - An array of conflicting bookings or an empty array if the booking complies with all rules + * @return Booking[]|null - An array of conflicting bookings or null if the booking complies with all rules */ public function checkBookingCompliance( Booking $booking ): ?array { if ( $booking->isBookingOwnerPrivileged() ) { diff --git a/src/Service/Holiday.php b/src/Service/Holiday.php index 82338030e..2596a2901 100644 --- a/src/Service/Holiday.php +++ b/src/Service/Holiday.php @@ -8,15 +8,15 @@ class Holiday { * Will render the fields in the timeframe settings where the user can define the holidays to get for the different German states and years. * The actual holidays will be loaded through feiertagejs. * - * @param $field - * @param $value - * @param $object_id - * @param $object_type - * @param $field_type + * @param mixed $field + * @param mixed $value + * @param mixed $object_id + * @param mixed $object_type + * @param mixed $field_type * * @return string */ - public static function renderFields( $field, $value, $object_id, $object_type, $field_type ) { + public static function renderFields( $field, $value, $object_id, $object_type, $field_type ): string { // make sure we specify each part of the value we need. $value = wp_parse_args( diff --git a/src/Service/MassOperations.php b/src/Service/MassOperations.php index 35b7d6c57..d82312a2d 100644 --- a/src/Service/MassOperations.php +++ b/src/Service/MassOperations.php @@ -4,7 +4,7 @@ class MassOperations { - public static function ajaxMigrateOrphaned() { + public static function ajaxMigrateOrphaned(): void { check_ajax_referer( 'cb_orphaned_booking_migration', 'nonce' ); if ( $_POST['data'] == 'false' ) { diff --git a/src/Service/Scheduler.php b/src/Service/Scheduler.php index 8f7fc65f6..d642f275a 100644 --- a/src/Service/Scheduler.php +++ b/src/Service/Scheduler.php @@ -28,12 +28,12 @@ class Scheduler { * It also hooks the appropriate actions that will un-schedule the job upon certain changes. * We can safely un-schedule the job upon changes, because the job will be re-scheduled with the correct settings when the page is loaded again. * - * @param string $jobhook the action hook to run when the event is executed - * @param callable $callback the callback function of that hook - * @param string $reccurence how often the event should subsequently recur - * @param string $executionTime takes time of day the job should be executed, only for daily reccurence - * @param array $option first element is the options_key, second is the field_id. If set, the field is checked and determines wether the hook should be ran - * @param string $updateHook The WordPress hook that should update the option + * @param string $jobhook the action hook to run when the event is executed + * @param callable $callback the callback function of that hook + * @param string $reccurence how often the event should subsequently recur + * @param string $executionTime takes time of day the job should be executed, only for daily reccurence + * @param array $option first element is the options_key, second is the field_id. If set, the field is checked and determines wether the hook should be ran + * @param string $updateHook The WordPress hook that should update the option */ function __construct( string $jobhook, @@ -91,7 +91,7 @@ function () { /** * Returns array with custom time intervals. * - * @return array[] + * @return array */ public static function getIntervals(): array { return array( @@ -117,11 +117,11 @@ public static function getIntervals(): array { /** * Inits custom intervals. * - * @param $schedules + * @param array> $schedules * - * @return array + * @return array> */ - public static function initIntervals( $schedules ): array { + public static function initIntervals( array $schedules ): array { return array_merge( $schedules, self::getIntervals() ); } @@ -132,7 +132,7 @@ public static function initIntervals( $schedules ): array { * * @return void */ - public static function initHooks() { + public static function initHooks(): void { // Init booking cleanup job new Scheduler( 'cleanup', @@ -251,7 +251,7 @@ private function unscheduleJob() { * There are also jobs still from CommonsBooking 0.X listed here. * It is important to remove the jobs, because WordPress does not delete them on it's own, not even on plugin deactivation. */ - public static function unscheduleOldEvents() { + public static function unscheduleOldEvents(): void { $cbCronHooks = [ 'cb_cron_hook', 'cb_reminder_cron_hook', diff --git a/src/Service/TimeframeExport.php b/src/Service/TimeframeExport.php index b7d89dd24..c0b6ac7ca 100644 --- a/src/Service/TimeframeExport.php +++ b/src/Service/TimeframeExport.php @@ -30,19 +30,19 @@ class TimeframeExport { /** * The extra meta fields to export for locations. * - * @var array|null + * @var string[]|null */ private ?array $locationFields = null; /** * The extra meta fields to export for items. * - * @var array|null + * @var string[]|null */ private ?array $itemFields = null; /** * The extra meta fields to export for users. * - * @var array|null + * @var string[]|null */ private ?array $userFields = null; /** @@ -112,9 +112,9 @@ class TimeframeExport { * @param string $exportStartDate Start date string of export * @param string $exportEndDate End date string of export * - * @param array|null $locationFields Metafields of location objects that should be included in the export - * @param array|null $itemFields Metafields of item objects that should be included in the export - * @param array|null $userFields Metafields of user objects that should be included in the export + * @param string[]|null $locationFields Metafields of location objects that should be included in the export + * @param string[]|null $itemFields Metafields of item objects that should be included in the export + * @param string[]|null $userFields Metafields of user objects that should be included in the export * @param int|null $lastProcessedPage 0 when starting, otherwise the last processed page from previous run * @param int|null $totalPosts Set on previous run, total amount of posts in export * @param string|null $transientName Set on previous run, name of transient where intermediate results are stored @@ -435,11 +435,11 @@ private function getProgressString(): string { /** * Return user defined export fields. * - * @param $inputName + * @param string $inputName * - * @return false|string[] + * @return string[] */ - protected static function getInputFields( $inputName ) { + protected static function getInputFields( string $inputName ): array { $inputFieldsString = array_key_exists( $inputName, $_REQUEST ) ? sanitize_text_field( $_REQUEST[ $inputName ] ) : Settings::getOption( 'commonsbooking_options_export', '$inputName' ); @@ -535,7 +535,7 @@ public function getExportData( int $page = - 1 ): bool { * * @return DatePeriod */ - protected static function getPeriod( $start, $end ) { + protected static function getPeriod( string $start, string $end ): \DatePeriod { // Timerange $begin = Wordpress::getUTCDateTime( $start ); $end = Wordpress::getUTCDateTime( $end ); @@ -572,7 +572,7 @@ protected static function getType(): int { * * @param int[] $timeframeIDs Array of timeframe post IDs * - * @return array + * @return array> */ public static function getTimeframeData( array $timeframeIDs ): array { @@ -670,7 +670,7 @@ function ( $location ) { * * @param \CommonsBooking\Model\Timeframe $timeframe The timeframe object to process * - * @return array + * @return array */ protected static function getRelevantTimeframeFields( \CommonsBooking\Model\Timeframe $timeframe ): array { $postArray = get_object_vars( $timeframe->getPost() ); diff --git a/src/Service/Upgrade.php b/src/Service/Upgrade.php index c74854a24..f34cf6632 100644 --- a/src/Service/Upgrade.php +++ b/src/Service/Upgrade.php @@ -36,7 +36,7 @@ class Upgrade { * * This is so that once the upgrade from a specific version has been run, it will not be run again. * - * @var array[] + * @var array>> */ private static array $upgradeTasks = [ '2.6.0' => [ @@ -71,7 +71,7 @@ class Upgrade { * * ATTENTION: These tasks will be ignored upon new installations. * - * @var array|array[] + * @var array>> */ private static array $ajaxUpgradeTasks = [ '2.8.5' => [ @@ -173,11 +173,11 @@ public function runUpgradeTasks(): void { /** * Returns an array of tasks that need to be run for this upgrade. * - * @param $upgradeTasks - An associative array with the version as key and the tasks as value (array of tasks). + * @param array>> $upgradeTasks An associative array with the version as key and the tasks as value. * - * @return array + * @return array> */ - private function getTasksForUpgrade( $upgradeTasks ): array { + private function getTasksForUpgrade( array $upgradeTasks ): array { $tasks = []; foreach ( $upgradeTasks as $version => $versionTasks ) { if ( version_compare( $this->previousVersion, $version, '<' ) && version_compare( $this->currentVersion, $version, '>=' ) ) { diff --git a/src/Service/iCalendar.php b/src/Service/iCalendar.php index 8e902f853..95af01929 100755 --- a/src/Service/iCalendar.php +++ b/src/Service/iCalendar.php @@ -109,12 +109,12 @@ public static function getCurrentUserCalendarLink() { /** * Get the ics file for an existing booking. Will be called, when the "Add to Calendar" button on the booking page is pressed * - * @param $bookingID + * @param int $bookingID * * @return void * @throws \Exception */ - public static function downloadICS( $bookingID ): void { + public static function downloadICS( int $bookingID ): void { $postID = $bookingID; $booking = new Booking( $postID ); $template_objects = [ @@ -150,7 +150,7 @@ public function addBookingEvent( Booking $booking, string $eventTitle, string $eventDescription - ) { + ): void { $eventDescription = preg_replace( "/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $eventDescription ); // remove empty lines from the description, they are not part of the standard $bookingLocation = $booking->getLocation(); diff --git a/src/Settings/Settings.php b/src/Settings/Settings.php index 0bd718aaf..bdb601115 100644 --- a/src/Settings/Settings.php +++ b/src/Settings/Settings.php @@ -72,7 +72,7 @@ public static function updateOption( $option_name, $field_id, $field_value ) { } - public static function returnFormattedMetaboxFields( $postType ) { + public static function returnFormattedMetaboxFields( string $postType ): string { $metabox_array = self::getOption( 'commonsbooking_settings_metaboxfields', $postType ); $result = '
'; diff --git a/src/View/Admin/Filter.php b/src/View/Admin/Filter.php index 7b03abe61..5bd4d2015 100644 --- a/src/View/Admin/Filter.php +++ b/src/View/Admin/Filter.php @@ -7,12 +7,14 @@ class Filter { /** * Renders backend list filter. * - * @param $postType - * @param $label - * @param $key - * @param $values + * @param string $postType + * @param string $label + * @param string $key + * @param array $values + * + * @return void */ - public static function renderFilter( $postType, $label, $key, $values ) { + public static function renderFilter( string $postType, string $label, string $key, array $values ): void { // only add filter to post type you want if ( isset( $_GET['post_type'] ) && $postType == $_GET['post_type'] ) { ?> @@ -37,13 +39,15 @@ public static function renderFilter( $postType, $label, $key, $values ) { /** * Renders Start-/Enddate filters for admin lists. * - * @param $postType - * @param $startDateInputName - * @param $endDateInputName - * @param $from - * @param $to + * @param string $postType + * @param string $startDateInputName + * @param string $endDateInputName + * @param string $from + * @param string $to + * + * @return void */ - public static function renderDateFilter( $postType, $startDateInputName, $endDateInputName, $from, $to ) { + public static function renderDateFilter( string $postType, string $startDateInputName, string $endDateInputName, string $from, string $to ): void { if ( isset( $_GET['post_type'] ) && $postType == sanitize_text_field( $_GET['post_type'] ) ) { echo '