} $this->id = $wpdb->insert_id; if ($this->update() === false) { $this->delete(); return false; } return $this->id; } /** * Update entity * * @return bool True on success, or false on error. */ protected function update(): bool { /** @var wpdb $wpdb */ global $wpdb; if ($this->id < 0) { throw new Exception('Entity don\'t exists in database'); } $this->beforeUpdate(); $data = $this->getUpdateData(); $result = $wpdb->update( static::getTableName(), $data['data'], ['id' => $this->id], $data['formats'] ); if ($result === false) { DupLog::infoTrace('Update entity fail error: ' . $wpdb->last_error); return false; } return true; } /** * Delete current entity * * @return bool True on success, or false on error. */ public function delete(): bool { /** @var wpdb $wpdb */ global $wpdb; if ($this->id < 0) { return true; } if ( $wpdb->delete( static::getTableName(), ['id' => $this->id], ['%d'] ) === false ) { DupLog::infoTrace('Delete entity fail error: ' . $wpdb->last_error); return false; } $this->id = -1; return true; } /** * Get where clause for get from database, can be overridden by child classes * * @return string */ protected static function getWhereClause(): string { return '1 = 1'; } /** * Get Model from database row * * @param array $row Database row * * @return static|false Concrete implementations may return false when the * row cannot be mapped to this model's hierarchy. */ abstract protected static function getModelFromRow(array $row); /** * Get ids of current type * * @param int<0, max> $page Current page * @param int<0, max> $pageSize Page size, 0 returns all IDs * @param array{col:string,mode:string} $orderby Query ordering * * @return int[]|false return entities list of false on failure */ final protected static function getIdsFromDatabase( int $page = 0, int $pageSize = 0, array $orderby = [ 'col' => 'id', 'mode' => 'ASC', ] ) { try { /** @var wpdb $wpdb */ global $wpdb; $where = static::getWhereClause(); $offset = $page * max(1, $pageSize); $pageSize = ($pageSize ?: PHP_INT_MAX); $orderCol = $orderby['col'] ?? 'id'; $order = $orderby['mode'] ?? 'ASC'; $query = $wpdb->prepare( "SELECT id FROM `" . static::getTableName(true) . "` WHERE {$where} ORDER BY {$orderCol} {$order} LIMIT %d OFFSET %d", $pageSize, $offset ); if (($rows = $wpdb->get_results($query, ARRAY_A)) === null) { throw new Exception('Get item query fail'); } $ids = []; foreach ($rows as $row) { $ids[] = (int) $row['id']; } } catch (Throwable $e) { DupLog::infoTraceException($e); return false; } return $ids; } /** * Load models, distinguishing database failures from unreadable stored data. * Unreadable rows are skipped: items always holds the readable models. * * @param int<0, max> $page Current page * @param int<0, max> $pageSize Page size, 0 returns all models * @param array{col:string,mode:string} $orderby Query ordering * * @return array{status:self::LOAD_SUCCESS|self::LOAD_INVALID_DATA|self::LOAD_DATABASE_ERROR,items:static[]} */ final protected static function loadFromDatabase( int $page = 0, int $pageSize = 0, array $orderby = [ 'col' => 'id', 'mode' => 'ASC', ] ): array { try { /** @var wpdb $wpdb */ global $wpdb; $where = static::getWhereClause(); $offset = $page * max(1, $pageSize); $pageSize = ($pageSize ?: PHP_INT_MAX); $orderCol = $orderby['col'] ?? 'id'; $order = $orderby['mode'] ?? 'ASC'; $query = $wpdb->prepare( "SELECT * FROM `" . static::getTableName(true) . "` WHERE {$where} ORDER BY {$orderCol} {$order} LIMIT %d OFFSET %d", $pageSize, $offset ); if (($rows = $wpdb->get_results($query, ARRAY_A)) === null || $wpdb->last_error !== '') { throw new Exception('Get item query fail'); } } catch (Throwable $e) { DupLog::infoTraceException($e); return [ 'status' => self::LOAD_DATABASE_ERROR, 'items' => [], ]; } $instances = []; $status = self::LOAD_SUCCESS; foreach ($rows as $row) { try { $instance = static::getModelFromRow($row); } catch (Throwable $e) { // Primitive logging only: this path also loads singletons SnapLog::phpErr('Unreadable stored data for ' . static::class . ' id ' . $row['id'] . ': ' . $e->getMessage()); $status = self::LOAD_INVALID_DATA; continue; } if ($instance === false) { continue; } $instances[] = $instance; } return [ 'status' => $status, 'items' => $instances, ]; } /** * Count entity items * * @return int|false */ final protected static function countItemsFromDatabase() { try { /** @var wpdb $wpdb */ global $wpdb; $where = static::getWhereClause(); $query = "SELECT COUNT(*) FROM `" . static::getTableName(true) . "` WHERE {$where}"; if (($count = $wpdb->get_var($query)) === null) { throw new Exception('Get item query fail'); } } catch (Throwable $e) { DupLog::infoTraceException($e); return false; } return (int) $count; } /** * Entity table name * * @param bool $escape If true apply esc_sql to table name * * @return string */ abstract public static function getTableName(bool $escape = false): string; /** * Init entity table * * @return string[] Strings containing the results of the various update queries. */ abstract public static function initTable(): array; }