db = $db; } /** * Prefixed table name. * * @param string $suffix Table suffix without prefix (e.g. bookings). * * @since 0.1.0 */ protected function table( string $suffix ): string { return $this->db->prefix . 'bookline_' . $suffix; } /** * Format a UTC instant for DATETIME storage. * * @param DateTimeImmutable $dt Instant. * * @since 0.1.0 */ protected function format_datetime( DateTimeImmutable $dt ): string { return $dt->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s' ); } /** * Parse a DATETIME string as UTC. * * @param string $value MySQL DATETIME. * * @throws RuntimeException When the value is invalid. * * @since 0.1.0 */ protected function parse_datetime( string $value ): DateTimeImmutable { $dt = DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', $value, new DateTimeZone( 'UTC' ) ); if ( false === $dt ) { throw new RuntimeException( 'Invalid DATETIME value from database.' ); } return $dt; } /** * Encode meta array to JSON or null. * * @param array|null $meta Meta. * * @throws RuntimeException When encoding fails. * * @since 0.1.0 */ protected function encode_meta( ?array $meta ): ?string { if ( null === $meta ) { return null; } $json = wp_json_encode( $meta ); if ( false === $json ) { throw new RuntimeException( 'Failed to encode meta JSON.' ); } return $json; } /** * Decode meta JSON. * * @param string|null $json JSON. * @return array|null * * @since 0.1.0 */ protected function decode_meta( ?string $json ): ?array { if ( null === $json || '' === $json ) { return null; } $decoded = json_decode( $json, true ); return is_array( $decoded ) ? $decoded : null; } /** * Last insert id as int. * * @since 0.1.0 */ protected function last_insert_id(): int { return (int) $this->db->insert_id; } /** * Run a prepared statement when prepare() succeeded. * * @param string|null $sql Prepared SQL. * * @since 0.1.0 */ protected function query_prepared( ?string $sql ): void { if ( ! is_string( $sql ) ) { return; } $this->db->query( $sql ); } /** * Count rows that have not been soft-deleted. * * @param string $suffix Table suffix (services, agents, locations). */ protected function count_not_deleted( string $suffix ): int { $sql = $this->db->prepare( 'SELECT COUNT(*) FROM %i WHERE `deleted_at` IS NULL', $this->table( $suffix ) ); if ( ! is_string( $sql ) ) { return 0; } return (int) $this->db->get_var( $sql ); } }