table = $db->prefix . static::TABLE; } /** * Current UTC time for DATETIME columns. */ protected static function now(): string { return gmdate( 'Y-m-d H:i:s' ); } /** * Unix time to a DATETIME string. * * @param int $ts Unix time. */ public static function dt( int $ts ): string { return gmdate( 'Y-m-d H:i:s', $ts ); } /** * DATETIME string (UTC) to Unix time. * * @param string|null $dt DATETIME. */ public static function ts( ?string $dt ): int { return null === $dt || '' === $dt ? 0 : (int) strtotime( $dt . ' UTC' ); } /** * Decode a JSON column. * * @param mixed $value Column value. * @param mixed $fallback When empty or invalid. */ protected static function json( mixed $value, mixed $fallback = array() ): mixed { if ( null === $value || '' === $value ) { return $fallback; } $decoded = json_decode( (string) $value, true ); return null === $decoded ? $fallback : $decoded; } /** * Placeholders for an IN () list. * * @param array $values Values. * @param string $type %d or %s. */ protected static function in( array $values, string $type = '%d' ): string { return implode( ',', array_fill( 0, max( 1, count( $values ) ), $type ) ); } /** * Run a callback inside a named MySQL lock so two requests cannot book * the same time at once. Returns null when the lock could not be had. * * @template T * @param string $name Lock name. * @param callable(): T $callback Work. * @param int $timeout Seconds to wait. * @return T|null */ public function locked( string $name, callable $callback, int $timeout = 10 ) { $name = 'schedulereed_' . substr( md5( $this->db->prefix . $name ), 0, 40 ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $got = (int) $this->db->get_var( $this->db->prepare( 'SELECT GET_LOCK(%s, %d)', $name, $timeout ) ); if ( 1 !== $got ) { return null; } try { return $callback(); } finally { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->db->query( $this->db->prepare( 'SELECT RELEASE_LOCK(%s)', $name ) ); } } }