diff --git a/.claude/hooks/docs-sync-check.sh b/.claude/hooks/docs-sync-check.sh new file mode 100755 index 0000000..a142668 --- /dev/null +++ b/.claude/hooks/docs-sync-check.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Stop hook: block finishing a session that changed src/ but no documentation. +# See docs/agents/docs-map.md for which pages each source file affects. + +input=$(cat) + +# Prevent an infinite block loop: if we already blocked once this stop, let it through. +if echo "$input" | grep -q '"stop_hook_active":true'; then + exit 0 +fi + +cd "$(dirname "$0")/../.." || exit 0 + +changed=$(git status --porcelain 2>/dev/null | awk '{print $NF}') +src_changed=$(echo "$changed" | grep -c '^src/.*\.php$') +docs_changed=$(echo "$changed" | grep -cE '^(docs/|README\.md|llms\.txt|CONTEXT\.md)') + +if [ "$src_changed" -gt 0 ] && [ "$docs_changed" -eq 0 ]; then + echo "Docs sync check: this session has uncommitted changes under src/ but none under docs/, README.md, or llms.txt. Consult docs/agents/docs-map.md for the pages affected by the changed files and update them, or state explicitly in your reply why no documentation is affected (e.g. pure refactor with no behavior/signature change). Then finish." >&2 + exit 2 +fi + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..0e7799f --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,14 @@ +{ + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/docs-sync-check.sh\"" + } + ] + } + ] + } +} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index dca00a0..ed612a4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,6 +21,15 @@ jobs: with: node-version: 20 - run: npm install + - name: Use archived Debian packages for the PHP 8.0 image + if: matrix.php == '8.0' + run: | + docker build --tag wordpress:php8.0 - <<'DOCKERFILE' + FROM wordpress:php8.0 + RUN sed -i 's|http://deb.debian.org|https://archive.debian.org|g; s|http://security.debian.org|https://archive.debian.org|g; /bullseye-updates/d' /etc/apt/sources.list \ + && printf 'Acquire::Check-Valid-Until "false";\n' > /etc/apt/apt.conf.d/99archive \ + && apt-get update + DOCKERFILE - run: npx wp-env start - run: npx wp-env run tests-cli --env-cwd=wp-content/wpify-model composer install --no-interaction - run: npx wp-env run tests-cli --env-cwd=wp-content/wpify-model vendor/bin/phpunit diff --git a/.gitignore b/.gitignore index 1af0f5a..c779051 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ .phpdoc /wordpress/ .phpunit.result.cache + +# Claude Code local state (committed: settings.json, hooks/) +/.claude/settings.local.json +/.claude/worktrees/ diff --git a/CLAUDE.md b/CLAUDE.md index c791eed..23bdb55 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1,11 @@ # CLAUDE.md +## Documentation + +User documentation lives in `docs/` (index: `docs/README.md`; flat agent index with one-line descriptions: `llms.txt`). The glossary in `CONTEXT.md` defines the terminology both code and docs must use. When writing code that *uses* this library (examples, tests, consuming projects), treat `docs/` as the source of truth for conventions — start from `llms.txt`. + +**Docs-sync rule (hard requirement):** any change under `src/` that alters behavior, signatures, properties, attributes, defaults, or error messages requires updating the documentation pages mapped to the changed files in `docs/agents/docs-map.md` — in the same commit. New source files and new docs pages get a row added to that map. If a `src/` change genuinely affects no docs (pure internal refactor), state that explicitly when finishing. A Stop hook enforces this check. + ## Agent skills ### Issue tracker diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..7dcf963 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,26 @@ +# wpify/model — domain context + +Ubiquitous language for this library. Documentation, code, issues, and agent output must use these terms exactly as defined; don't drift to synonyms. + +## The rule + +**Models hold the data, repositories talk to WordPress, the Manager wires them together.** + +## Glossary + +- **model** — a data class extending `Wpify\Model\Model` that holds one entity's data (one post, one term, one table row). Public typed properties, resolved lazily on first read. Models never query WordPress themselves. +- **repository** — a class extending `Wpify\Model\Repository` that reads and writes models: `get()`, `find()`, `create()`, `save()`, `delete()`. All WordPress/WooCommerce I/O lives in repositories. +- **the Manager** — `Wpify\Model\Manager`, the registry that maps each model class to its repository. Registers the 18 built-in repositories in its constructor; custom repositories are added via constructor arguments or `register_repository()`. Always written "the Manager". +- **source object** — the underlying WordPress/WooCommerce object a model wraps (`WP_Post`, `WP_Term`, `WP_User`, `WP_Comment`, `WP_Site`, `WC_Product`, `WC_Order`, or a table row object). Accessed via `$model->source()`. +- **source attribute** — a PHP attribute implementing `SourceAttributeInterface` placed on a model property to declare where its value comes from: `#[SourceObject]`, `#[Meta]`, `#[AccessorObject]`, `#[AliasOf]`, `#[Column]`, and the relation attributes. +- **property resolution** — the lazy `__get` flow: cached value → `get_{prop}()` accessor → source attribute → type coercion → cache. Specified in `docs/concepts/property-resolution.md`. +- **relation attribute** — a source attribute that resolves other models (e.g. `#[PostTermsRelation]`, `#[ManyToOneRelation]`, `#[ChildPostsRelation]`). All are read-only views except `#[PostTermRelation]`/`#[PostTermsRelation]`, which persist through `PostRepository::save()`. +- **built-in models** — the model/repository pairs shipped with the library (Post, Page, Attachment, Category, PostTag, Term, User, Comment, Site, Menu, MenuItem, Product, ProductCat, Order and order items). Not "core models". +- **custom table model** — a model whose properties carry `#[Column]` attributes, served by a repository extending `CustomTableRepository`, stored in a dedicated database table. Not "database model". +- **accessor method** — the `get_{prop}` / `set_{prop}` / `persist_{prop}` naming conventions on models: computed reads, write normalization, and custom save behavior respectively. + +## Pointers + +- Architecture decisions: `docs/adr/` +- User documentation: `docs/` (index in `docs/README.md`, agent index in `llms.txt`) +- Docs↔source mapping for keeping docs in sync: `docs/agents/docs-map.md` diff --git a/README.md b/README.md index 76c954f..4b683a9 100644 --- a/README.md +++ b/README.md @@ -1,387 +1,68 @@ -# Models for WordPress +# wpify/model -This library provides a better access to data in WordPress. It is a wrapper around the WordPress API, which provides -a more object-oriented approach to the data. It also provides a way to define custom models for your data, for example -to define a model for a custom post type, custom taxonomy or custom database table. +Object-oriented access to WordPress data. Typed model classes with lazily resolved properties, repositories for every read and write, and one Manager wiring them together — for posts, terms, users, comments, sites, menus, WooCommerce products and orders, and your own custom database tables. -## Benefits - -* Object-oriented access to data. -* Easy to use. -* Easy to extend. -* Easy to define and use custom tables. -* Minimise the number of queries to the database. -* Uses modern PHP 8 features for better developer experience. - -## Core concepts - -The library uses a few types of objects: - -* **Model**: A model is a class that contains data of one entity, e.g. single post, term or table row. Model has clearly defined properties and methods to access the data. -* **Repository**: A repository is a class that provides access to the data. Repository can retrieve data from the database, from the cache or from other sources. -* **Manager**: Manager keeps the list of registered models and repositories. It also provides a way to retrieve a model or repository by its name. - -## Requirements - -* PHP 8.0 or higher - -## Installation - -Install the library using composer: - -```shell -composer require wpify/model -``` - -# Basic usage - -First think you need to do is to initialize the Manager to have access to built-in models and repositories: +**Models hold the data, repositories talk to WordPress, the Manager wires them together.** ```php use Wpify\Model\Manager; +use Wpify\Model\PostRepository; $manager = new Manager(); -``` - -With the manager you can use a built-in models and repositories. For example, to get all published posts -you can use the following code: - -```php -$post_repository = $manager->get_repository( Wpify\Model\Post::class ); -$posts = $post_repository->find_published(); -``` +$posts = $manager->get_repository( PostRepository::class ); -And then you can access the data using the model: - -```php -foreach ( $posts as $post ) { - echo $post->title; +// Read +foreach ( $posts->find_published() as $post ) { + echo $post->title; } -``` -You can also retrieve a single post by its ID or other keys: +// Write +$post = $posts->create( array( 'title' => 'Hello' ) ); +$posts->save( $post ); -```php -$post = $post_repository->get( 123 ); -$post = $post_repository->get( 'article-slug' ); -$post = $post_repository->get( 'https://myblog.con/article-url/' ); +echo $post->id; // result: the new post ID ``` -## Updating the model - -To update the data, you simply update model's properties and then save the data by calling the `save()` method on the repository: - -```php -$post->title = 'New title'; - -$post_repository->save( $post ); - -echo $post->title; // New title -``` - -## Creating new entries - -To create a new entry, you need to create a new model via repository and then save it: - -```php -$post = $post_repository->create( array( - 'title' => 'New post', - 'content' => 'New content', -) ); - -$post_repository->save( $post ); - -echo $post->id; // 123 -``` - -## Deleting the entry - -To delete the entry, you need to call the `delete()` method on the repository: - -```php -$post_repository->delete( $post ); -``` - -# Custom models - -You can define your own models to access the data in custom post types, custom taxonomies or custom database tables. -All your custom models must extend the `Wpify\Model\Model` class or other models. Every custom model must have -a repository, which must extend the `Wpify\Model\Repository` class or other repositories. - -## Defining a custom model - -In this example, we will define a model for a custom post type with some meta fields: +Defining a model for your own post type is a class and two attributes: ```php use Wpify\Model\Post; -use Wpify\Model\Attributes; +use Wpify\Model\Attributes\Meta; class Book extends Post { - #[Attributes\Meta] - public string $isbn; - - #[Attributes\Meta] - public string $author; -} -``` - -All properties have a definition in the form of a PHP attribute. You can use the following attributes: - -* `Attributes\AliasOf` - defines an alias for another property. -* `Attributes\AccessorObject` - defines a getter and setter from the source object. -* `Attributes\ChildPostRelation` - defines a relation to a child post (for post models only). -* `Attributes\ChildTermRelation` - defines a relation to a child term (for term models only). -* `Attributes\Column` - defines a column in a custom table (for custom table models only). -* `Attributes\IdsRelation` - retrieves related posts by IDs. -* `Attributes\ManyToOneRelation` - retrieves related models by foreign model's ID in another property. -* `Attributes\Meta` - defines a meta field. -* `Attributes\OrderItemsRelation` - retrieves order items. -* `Attributes\PostTermsRelation` - retrieves related terms by post ID. This attribute also persists the post-term relation. -* `Attributes\PostTermRelation` - retrieves related term by post ID. This attribute also persists the post-term relation. Beware, that if the post has more than one term, only the first one will be returned or persisted. -* `Attributes\SourceObject` - defines a value in a source object for the model (e.g. WP_Post property). -* `Attributes\TermPostsRelation` - retrieves related posts of term (for term models only). - -There are also attributes that can modify a behaviour of the propery: - -* `Attributes\ReadOnlyProperty` - makes the property read-only. - -Some of the attributes have additional parameters, that can be passed by named constructor arguments: - -```php -#[Attributes\SourceObject( 'ID' )] -public int $id; - -#[Attributes\Meta( '_isbn' )] -public string $isbn; - -#[Attributes\Meta( meta_key: '_author' )] -public string $author; - -#[Attributes\Column( type: Attributes\Column::VARCHAR, params: 1000, unique: true )] -public string $custom_column; -``` - -Most of the attributes have a default values, so you can omit some of the parameters. - -## Defining a custom repository - -To actually use the model, you need to define a repository for it. In this example, we will define a repository for the `Book` model: - -```php -use Wpify\Model\PostRepository; - -class BookRepository extends PostRepository { - public function model() : string{ - return Book::class; - } - - public function post_types() : array{ - array( 'book' ); - } + #[Meta( meta_key: 'isbn' )] + public string $isbn = ''; } ``` -After repository creation, you need to register it in the manager: - -```php -$manager->register_repository( BookRepository::class ); -``` - -You can also register the repository in the constructor of the manager: - -```php -$manager = new Manager( new BookRepository() ); -``` - -If you use a [PHP-DI](https://php-di.org/), you can register the repository in the container: - -```php -use DI; -use Wpify\Model\Manager; - -$container_builder = new DI\ContainerBuilder(); - -$container_builder->addDefinitions( array( - Manager::class => DI\create()->constructor( - DI\get( BookRepository::class ), - ), -) ); - -$container = $container_builder->build(); -$manager = $container->get( Manager::class ); -$book_repo = $manager->get_repository( BookRepository::class ); -``` - -# Built-in models - -The library provides a few built-in models and repositories. -You can use them also to define your custom models by extending them. - -* `Post` and `PostRepository` for posts. -* `Page` and `PageRepository` for pages. -* `Attachment` and `AttachmentRepository` for attachments. -* `Category` and `CategoryRepository` for categories. -* `PostTag` and `PostTagRepository` for post tags. -* `User` and `UserRepository` for users. -* `Comment` and `CommentRepository` for comments. -* `User` and `UserRepository` for users. -* `Menu` and `MenuRepository` for menus. -* `Site` and `SiteRepository` for sites. -* `Product` and `ProductRepository` for WooCommerce products. -* `Order` and `OrderRepository` for WooCommerce orders. -* `OrderItem` and `OrderItemRepository` for WooCommerce order items. -* `ProductCat` and `ProductCatRepository` for WooCommerce product categories. - -# Custom table models +## Why -You can create and use custom table models. To do this, you need to define a repository for the model and a model itself. -The table is created automatically, so you don't need to handle it manually, but you can disable this behaviour. +- **Typed properties instead of `get_post_meta()` calls** — declare a property, annotate its source with a PHP attribute, and the library resolves, casts, and caches it lazily. +- **All WordPress I/O in one place** — repositories wrap `WP_Query`, meta APIs, and WooCommerce CRUD, so your business code never touches globals. +- **Custom tables without the boilerplate** — `#[Column]` attributes generate the schema, migrations run automatically, and a structured where-syntax replaces hand-written SQL. +- **Built for extension** — every built-in model and repository is designed to be subclassed. -Example: - -```php -class MyModelRepository extends CustomTableRepository { - public function model(): string { - return MyModel::class; - } - - public function table_name(): string { - return 'my_model'; - } -} -``` - -You also need to define the model with column attributes: - -```php -class MyModel extends Model { - #[Column( type: Column::INT, auto_increment: true, primary_key: true )] - public int $id = 0; - - #[Column( type: Column::VARCHAR, params: 255 )] - public string $name = ''; -} -``` - -The Column attribute accepts the following parameters: -- `name`: The name of the column. If not specified, the name of the property will be used. -- `type`: The type of the column. If not specified, the type will be inferred from the property type. -- `params`: The parameters for the column type. For example, for VARCHAR, you can specify the length. -- `unsigned`: Whether the column is unsigned. Default is false. -- `nullable`: Whether the column is nullable. Default is false. -- `default`: Column default value. -- `on_update`: Column default value on update. -- `auto_increment`: Whether the column is auto-increment. Default is false. -- `primary_key`: Whether the column is primary key. Default is false. -- `unique`: Whether the column is unique. Default is false. -- `foreign_key`: Array with data to set foreign key. - -The model must contain exactly one primary key column. - -Column can be one of the following types: -- `Column::TINYINT` (`tinyint`) -- `Column::INT` (`int`) -- `Column::BIGINT` (`bigint`) -- `Column::BOOLEAN` (`boolean`) -- `Column::DECIMAL` (`decimal`) -- `Column::DATE` (`date`) -- `Column::DATETIME` (`datetime`) -- `Column::TIMESTAMP` (`timestamp`) -- `Column::TIME` (`time`) -- `Column::CHAR` (`char`) -- `Column::VARCHAR` (`varchar`) -- `Column::BLOB` (`blob`) -- `Column::TEXT` (`text`) -- `Column::ENUM` (`enum`) -- `Column::SET` (`set`) -- `Column::JSON` (`json`) - -Foreign key array contains these items: -- `Column::FOREIGN_TABLE`: Foreign table name without WP prefix (e.g. `posts`). -- `Column::FOREIGN_COLUMN`: Foreign column name (e.g. `ID`). -- `Column::FOREIGN_SETTINGS`: Optional settings, for example `ON DELETE CASCADE`. - -The repository will automatically create the table when the repository is used. If you want to disable automatic migrations, -you can pass `false` to the `auto_migrate` parameter in the constructor. You can then manually migrate the table by calling -the `migrate()` method in appropriate place, e.g. plugin activation hook, `admin_init` hook, etc. - -```php -$repository = new MyModelRepository( auto_migrate: false ); - -$manager->register_repository( $repository ); - -add_action( 'admin_init', array( $repository, 'migrate' ) ); -``` - -The table name is automatically prefixed with the WordPress table prefix. If you want to disable this, you can pass `false` -to the `use_prefix` parameter in the constructor. - -```php -$repository = new MyModelRepository( use_prefix: false ); - -$manager->register_repository( $repository ); -``` - -If you want to drop the database table, you can call the `drop_table()` method. This is useful when uninstalling the plugin. - -```php -$repository = new MyModelRepository(); - -$manager->register_repository( $repository ); - -register_uninstall_hook( $main_php_file_path, array( $repository, 'drop_table' ) ); -``` +## Requirements -## Querying the custom table +- PHP 8.0+ +- WordPress (WooCommerce models require WooCommerce; Site models require multisite) -You can query custom tables with find function: +## Installation -```php -$items = $repository->find( array( - 'where' => "name = '" . esc_sql( 'Alex' ) . "'", -) ); +```shell +composer require wpify/model ``` -Even this works, it is not recommended to use this method, because it is vulnerable to SQL injection. -Instead, you should use array as arguments, that sanitizes the values, and you can use complex queries: +## Documentation -```php -$items = $repository->find( array( - array( - 'table.col0 <>' => true, - 'OR', - 'table.col1' => true, - 'or', - array( - 'table.col2' => 'active', - 'table.col3 <>' => 'active' - ) - ), - 'table.col4' => array( 1, 2, 3 ), - 'table.col5 NOT IN' => array( 'test', 'test2', 'test3' ), - 'table.col6 BETWEEN 1 AND 10', - 'table.col7 BETWEEN' => array( 1, 10 ), - 'EXISTS' => 'SELECT * FROM table2 WHERE table.id = table2.table_id', -) ); -``` +Full documentation lives in [`docs/`](docs/README.md): -As you can see, you can use even nested queries or specify the operator in the key. You can also define, whether to use OR, or AND operator. +- **New here?** [Installation](docs/getting-started/installation.md) → [Quickstart](docs/getting-started/quickstart.md) — first success in about five minutes. +- **Building something?** Guides for [custom post types](docs/guides/custom-post-types.md), [custom taxonomies](docs/guides/custom-taxonomies.md), [meta fields](docs/guides/meta-fields.md), [relations](docs/guides/relations.md), [querying](docs/guides/querying.md), [custom tables](docs/guides/custom-tables.md), [WooCommerce](docs/guides/woocommerce.md), and more. +- **Looking something up?** The [reference](docs/README.md#reference) covers every class and all 17 attributes. +- **Something broken?** [Troubleshooting](docs/guides/troubleshooting.md). +- **AI agent?** Start from [`llms.txt`](llms.txt). -# TODO: +## License -- make generated documentation -- add tests -- custom tables - caching, metadata -- implement other WooCommerce models: - - VariableProduct - - SimpleProduct - - GroupedProduct - - ExternalProduct - - DownloadableProduct - - ProductTag - - ProductAttribute - - ProductVariation - - ShopCoupon - - ShopWebhook -- implement WooCommerce Subscriptions models -- implement SQL query model +GPL-2.0-or-later diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..911fd2d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,71 @@ +# wpify/model documentation + +Object-oriented access to WordPress data: typed models, repositories, one Manager. + +**Models hold the data, repositories talk to WordPress, the Manager wires them together.** + +## Where do you want to go? + +**I'm evaluating the library** → read the [architecture concept](concepts/architecture.md) and skim the [quickstart](getting-started/quickstart.md). + +**I'm starting from zero** → [Installation](getting-started/installation.md), then the [quickstart](getting-started/quickstart.md). First success takes about five minutes. + +**I want a model for my custom post type / taxonomy / table** → the three flagship guides: [custom post types](guides/custom-post-types.md), [custom taxonomies](guides/custom-taxonomies.md), [custom tables](guides/custom-tables.md). + +**I need to look something up** → the [reference](#reference) section below, or the flat index in [`llms.txt`](../llms.txt). + +**Something's broken** → [Troubleshooting](guides/troubleshooting.md). + +## Getting started + +| Page | What you'll do | +| --- | --- | +| [Installation](getting-started/installation.md) | Install via Composer and bootstrap the Manager in a plugin | +| [Quickstart](getting-started/quickstart.md) | Run the full CRUD loop on posts, then define your first custom model | + +## Concepts + +| Page | What it explains | +| --- | --- | +| [Architecture](concepts/architecture.md) | The Model/Repository/Manager split and how the pieces talk | +| [Property resolution](concepts/property-resolution.md) | How lazy properties resolve: cache → accessor → source attribute → coercion | +| [Persistence](concepts/persistence.md) | What `create()`, `save()`, and `delete()` actually do, per model family | + +## Guides + +| Page | Task | +| --- | --- | +| [Custom post types](guides/custom-post-types.md) | Model + repository for a custom post type (the canonical extension example) | +| [Custom taxonomies](guides/custom-taxonomies.md) | Term model + repository for a custom taxonomy | +| [Meta fields](guides/meta-fields.md) | Map properties to post/term/user/comment meta with `#[Meta]` | +| [Model properties](guides/model-properties.md) | Computed props, setters, custom persistence, read-only props, aliases | +| [Relations](guides/relations.md) | Link models to other models with relation attributes | +| [Querying](guides/querying.md) | `get()`, `find()`, finders, and pagination across model families | +| [Custom tables](guides/custom-tables.md) | Dedicated database tables with `#[Column]`, auto-migrations, and the where-array syntax | +| [WooCommerce](guides/woocommerce.md) | Product, order, and order item models *(requires WooCommerce)* | +| [Menus](guides/menus.md) | Navigation menus and nested menu item trees | +| [Multisite](guides/multisite.md) | Site models *(requires multisite)* | +| [Troubleshooting](guides/troubleshooting.md) | Error messages mapped to causes and fixes | + +## Reference + +| Page | Covers | +| --- | --- | +| [Manager](reference/manager.md) | Registration and repository lookup | +| [Model](reference/model.md) | The abstract base every model extends | +| [Repository](reference/repository.md) | The shared repository contract and type coercion | +| [Attributes](reference/attributes.md) | All 17 property attributes | +| [CustomTableRepository](reference/custom-table-repository.md) | Custom table CRUD, migrations, query grammar | +| [Transactions](reference/transactions.md) | Atomic custom-table writes, nesting and rollback limits | +| [Post models](reference/models/post.md) | Post, Page, Attachment | +| [Term models](reference/models/term.md) | Term, Category, PostTag | +| [User model](reference/models/user.md) | User | +| [Comment model](reference/models/comment.md) | Comment | +| [Site model](reference/models/site.md) | Site *(multisite)* | +| [Menu models](reference/models/menu.md) | Menu, MenuItem | +| [Product models](reference/models/product.md) | Product, ProductCat *(WooCommerce)* | +| [Order models](reference/models/order.md) | Order and order items *(WooCommerce)* | + +## For AI agents + +Start from [`llms.txt`](../llms.txt) at the repo root — a flat annotated index of every page. Use the terminology defined in [`CONTEXT.md`](../CONTEXT.md). Pages are self-contained; code blocks are complete and copy-paste-runnable. diff --git a/docs/adr/0001-documentation-architecture.md b/docs/adr/0001-documentation-architecture.md new file mode 100644 index 0000000..b4f1360 --- /dev/null +++ b/docs/adr/0001-documentation-architecture.md @@ -0,0 +1,25 @@ +# 0001 — Documentation architecture + +Date: 2026-07-26 +Status: accepted + +## Context + +The library was documented by a single 387-line README that had drifted from the code (wrong `get_repository()` semantics, a `post_types()` example missing its `return`, listed attributes that don't match `src/Attributes/`). The library's real surface — 40+ classes, 17 attributes, a 727-line `CustomTableRepository` — outgrew one file. Audiences are public WordPress developers *and* AI coding agents, which copy examples verbatim and pattern-match page structure. + +Research on Laravel Eloquent, Doctrine ORM, Timber/Meta Box/Pods, and Prisma/Drizzle docs converged on: rigid stamped templates per similar entity, "1–3 sentences of prose then one code block", zero-config quickstart, showing the underlying platform consequence of each call, documenting shared behavior once, and never listing a class without an example. + +## Decision + +- Docs live as a plain markdown tree under `docs/`, browsable on GitHub, no build tooling. The README is a slim pitch + quickstart + map. +- Structure is Diátaxis-lite: `getting-started/` (tutorial), `guides/` (task recipes), `reference/` (stamped per-class/family pages), `concepts/` (architecture, property resolution, persistence semantics). +- Reference pages are agent-written from source, not docblock-generated; shared repository behavior is documented once in `reference/repository.md`, family pages document deltas only. +- Sharp edges are documented in place with GitHub alert callouts; behavior that looks buggy is documented as current reality ("Known limitation"). +- AI-facing artifacts: root `llms.txt` (annotated, task-grouped page index), self-contained pages with stable heading schemas, `CONTEXT.md` glossary as ubiquitous language. +- Docs-sync enforcement: `docs/agents/docs-map.md` maps source files to affected pages; the repo `CLAUDE.md` requires a docs check for any `src/` change; a Stop hook in `.claude/settings.json` blocks a coding session that modified `src/**/*.php` without touching docs. + +## Consequences + +- Docs must be updated in the same session/commit as behavior changes — the hook makes forgetting loud. The docs map is itself a maintained artifact. +- No generated reference means signatures can drift silently if the sync rule is bypassed; the map + hook are the mitigation. +- Page count (~30) is the tradeoff for lookup-sized, agent-friendly pages over monoliths. diff --git a/docs/agents/docs-map.md b/docs/agents/docs-map.md new file mode 100644 index 0000000..69307e6 --- /dev/null +++ b/docs/agents/docs-map.md @@ -0,0 +1,29 @@ +# Docs map — source → documentation pages + +When a change under `src/` alters behavior, signatures, properties, attributes, or defaults, update every page mapped to the changed file(s) below, plus `llms.txt` if pages are added/removed/renamed. Keep this map current: new source files and new pages get a row in the same commit that introduces them. + +Pages that always apply to broad changes: `docs/guides/troubleshooting.md` (new/changed error messages), `docs/concepts/persistence.md` (any save/delete semantics), `docs/concepts/property-resolution.md` (Model/Repository resolution or coercion logic). + +| Source file(s) | Documentation pages | +| --- | --- | +| `src/Model.php` | `docs/reference/model.md`, `docs/concepts/property-resolution.md`, `docs/concepts/architecture.md`, `docs/guides/model-properties.md` | +| `src/Repository.php` | `docs/reference/repository.md`, `docs/concepts/property-resolution.md`, `docs/concepts/persistence.md` | +| `src/Manager.php` | `docs/reference/manager.md`, `docs/getting-started/installation.md`, `docs/concepts/architecture.md` | +| `src/Attributes/Meta.php` | `docs/reference/attributes.md`, `docs/guides/meta-fields.md`, `docs/concepts/persistence.md` | +| `src/Attributes/Column.php` | `docs/reference/attributes.md`, `docs/guides/custom-tables.md`, `docs/reference/custom-table-repository.md` | +| `src/Attributes/*Relation*.php` | `docs/reference/attributes.md`, `docs/guides/relations.md` | +| `src/Attributes/` (any other) | `docs/reference/attributes.md`, `docs/guides/model-properties.md` | +| `src/Interfaces/*`, `src/Exceptions/*` | `docs/reference/model.md`, `docs/reference/repository.md`, `docs/guides/troubleshooting.md` | +| `src/Post.php`, `src/PostRepository.php` | `docs/reference/models/post.md`, `docs/guides/custom-post-types.md`, `docs/guides/querying.md`, `docs/getting-started/quickstart.md` | +| `src/Page.php`, `src/PageRepository.php`, `src/Attachment.php`, `src/AttachmentRepository.php` | `docs/reference/models/post.md` | +| `src/Term.php`, `src/TermRepository.php` | `docs/reference/models/term.md`, `docs/guides/custom-taxonomies.md`, `docs/guides/querying.md` | +| `src/Category.php`, `src/CategoryRepository.php`, `src/PostTag.php`, `src/PostTagRepository.php` | `docs/reference/models/term.md` | +| `src/User.php`, `src/UserRepository.php` | `docs/reference/models/user.md`, `docs/guides/querying.md` | +| `src/Comment.php`, `src/CommentRepository.php` | `docs/reference/models/comment.md` | +| `src/Site.php`, `src/SiteRepository.php` | `docs/reference/models/site.md`, `docs/guides/multisite.md` | +| `src/Menu.php`, `src/MenuRepository.php`, `src/MenuItem.php`, `src/MenuItemRepository.php` | `docs/reference/models/menu.md`, `docs/guides/menus.md` | +| `src/CustomTableRepository.php` | `docs/reference/custom-table-repository.md`, `docs/guides/custom-tables.md`, `docs/reference/transactions.md` | +| `src/Transaction.php` | `docs/reference/transactions.md`, `docs/concepts/persistence.md`, `docs/guides/troubleshooting.md` | +| `src/Product.php`, `src/ProductRepository.php`, `src/ProductCat.php`, `src/ProductCatRepository.php` | `docs/reference/models/product.md`, `docs/guides/woocommerce.md` | +| `src/Order*.php` (all order/order-item classes) | `docs/reference/models/order.md`, `docs/guides/woocommerce.md` | +| `composer.json` (PHP requirement, package name) | `docs/getting-started/installation.md`, `README.md` | diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md index 82cfbf5..df8952a 100644 --- a/docs/agents/issue-tracker.md +++ b/docs/agents/issue-tracker.md @@ -25,6 +25,14 @@ When set to `yes`, PRs run through the same labels and states as issues, using t GitHub shares one number space across issues and PRs, so a bare `#42` may be either — resolve with `gh pr view 42` and fall back to `gh issue view 42`. +## Definition of done + +Before closing an issue or opening a PR that changes `src/`: + +1. Check `docs/agents/docs-map.md` for the documentation pages mapped to every changed source file. +2. Update those pages (and `llms.txt` if pages were added/removed/renamed) in the same branch/commit, or record in the issue/PR why no documentation is affected. +3. Tests pass. + ## When a skill says "publish to the issue tracker" Create a GitHub issue. diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.md new file mode 100644 index 0000000..3ce9682 --- /dev/null +++ b/docs/concepts/architecture.md @@ -0,0 +1,179 @@ +# Architecture + +**Models hold the data, repositories talk to WordPress, the Manager wires them together.** + +That one sentence is the whole design of wpify/model. Every class you will write or use falls into one of three roles, and each role has exactly one job. If you keep the sentence in mind, you always know where a piece of code belongs: data shape goes in a model, WordPress calls go in a repository, and the mapping between the two lives in the Manager. + +## The three roles + +| Role | Base class | Responsibility | +|---|---|---| +| Model | `Wpify\Model\Model` | Typed data class for one entity; resolves its properties lazily | +| Repository | `Wpify\Model\Repository` | All reads and writes between models and WordPress | +| The Manager | `Wpify\Model\Manager` | Registry mapping each model class to its repository | + +### Models hold the data + +A model is a plain PHP class with typed public properties. Each property is decorated with a source attribute — `#[SourceObject]`, `#[Meta]`, a relation attribute — that declares where its value comes from; the model itself never queries the database. Here is a complete custom model for a bookstore plugin: + +```php +get_repository( BookRepository::class ); +$book = $books->get( 123 ); + +echo $book->title; // result: Dune +``` + +Constructing the Manager eagerly instantiates all built-in repositories, which is cheap — they hold no state until used. Any constructor argument that is not a `RepositoryInterface` is silently ignored, which makes the Manager friendly to DI containers. + +## Why repositories, not active record + +An active-record design (`$book->save()`) mixes data and storage in one class. wpify/model deliberately splits them, for two reasons. + +First, **every WordPress call lives in exactly one place**. When you need to know what a save actually does — which WP function fires, which hooks run, what lands in `wp_posts` versus `wp_postmeta` — you read one repository class, not attribute magic scattered across models. Changing storage behavior for a whole family of models means overriding one repository. + +Second, **testability**. Models are plain data holders that never touch the database, so code that consumes models can be tested by handing it models hydrated from fixtures. All I/O is concentrated behind the repository's interface, so a test can register a fake repository with the Manager and the models are none the wiser. + +The practical consequence: `save()`, `delete()`, and all finders are methods on the *repository*, not the model. `$book->save()` does not exist; `$book_repository->save( $book )` does. + +## How a property read flows + +Reading `$book->isbn` is not a plain property access — the property was unset at construction, so PHP routes the read through `Model::__get`, which asks the repository to resolve the value: + +```text +$book->isbn + ├─ cached value on the model? → yes: return it immediately + ├─ does Book define get_isbn()? → yes: call it (computed prop wins) + ├─ otherwise ask the source attribute: + │ #[Meta( 'isbn' )] → get_post_meta( $book->id, 'isbn', true ) + ├─ coerce to the declared type → (string) '978-0441172719' + ├─ still null after coercion? → fall back to the declared default + └─ cache the value on the model → subsequent reads skip all of the above +``` + +So the first read of a meta property costs one `get_post_meta()` call and later reads are free. Coercion runs before the default kicks in, and it has one shortcut: when the raw value is `null` or `''` *and* the property's type is nullable, coercion skips the cast and returns the declared default directly. A non-nullable property never takes that shortcut — for `string $isbn = ''` with no stored meta, the `''` you get back comes from `strval()` coercing the empty meta value, not from the default. + +Type coercion also covers model classes: when the declared type is a registered model class, the coercion step feeds the raw value (an ID) to that model's repository and returns the loaded model. The type alone fetches nothing, though — a property needs a source attribute to produce that ID in the first place; `Post::$author`, for example, is resolved by its `#[ManyToOneRelation( 'author_id' )]` source attribute, not by being typed `?User`. The full pipeline, including setters and cache invalidation, is documented in [Property resolution](property-resolution.md). + +## The built-in repositories + +The Manager's constructor registers 18 built-in repositories, so the common WordPress objects work with zero configuration: + +| Repository | Model | WP object | +|---|---|---| +| `PostRepository` | `Post` | `WP_Post` (post type `post`) | +| `PageRepository` | `Page` | `WP_Post` (post type `page`) | +| `AttachmentRepository` | `Attachment` | `WP_Post` (post type `attachment`) | +| `TermRepository` | `Term` | `WP_Term` | +| `CategoryRepository` | `Category` | `WP_Term` (taxonomy `category`) | +| `PostTagRepository` | `PostTag` | `WP_Term` (taxonomy `post_tag`) | +| `UserRepository` | `User` | `WP_User` | +| `CommentRepository` | `Comment` | `WP_Comment` | +| `MenuRepository` | `Menu` | nav menu (`WP_Term`) | +| `MenuItemRepository` | `MenuItem` | nav menu item (`WP_Post`) | +| `SiteRepository` | `Site` | `WP_Site` | +| `ProductRepository` | `Product` | `WC_Product` | +| `ProductCatRepository` | `ProductCat` | `WP_Term` (taxonomy `product_cat`) | +| `OrderRepository` | `Order` | `WC_Order` | +| `OrderItemRepository` | `OrderItem` | `WC_Order_Item` | +| `OrderItemLineRepository` | `OrderItemLine` | `WC_Order_Item_Product` | +| `OrderItemFeeRepository` | `OrderItemFee` | `WC_Order_Item_Fee` | +| `OrderItemShippingRepository` | `OrderItemShipping` | `WC_Order_Item_Shipping` | + +> [!IMPORTANT] +> Requires WooCommerce: the `Product*` and `Order*` repositories. Requires multisite: `SiteRepository`. All 18 are registered unconditionally — registration itself is harmless, but calling methods on these repositories without WooCommerce active (or outside multisite) is a PHP fatal error, not a catchable library exception. See the [WooCommerce](../guides/woocommerce.md) and [multisite](../guides/multisite.md) guides. + +`CustomTableRepository` — the base for [custom table models](../guides/custom-tables.md) — is *not* auto-registered; you pass your subclass to the Manager yourself. + +## How models map to repositories + +Every repository declares which model it manages by returning the model's class name from `model()` — that return value is the registry key. The Manager then offers two lookups, one keyed by repository class and one keyed by model class: + +```php +use Wpify\Model\Post; +use Wpify\Model\PostRepository; + +$posts = $manager->get_repository( PostRepository::class ); // by repository class +$posts = $manager->get_model_repository( Post::class ); // by model class +// result: both return the same PostRepository instance +``` + +The model-class lookup is an exact string match with no inheritance walking. That is why every model subclass needs its own registered repository: constructing a `Book` when no repository returns `Book::class` from `model()` throws `RepositoryNotFoundException`, even though `Book` extends `Post`. Registration order also matters — custom repositories register after the built-ins, so a repository whose `model()` returns a built-in class (say, `Wpify\Model\Post`) overrides the default mapping for that model. + +> [!NOTE] +> `get_repository()` with a class that was never registered lazily instantiates it *without* wiring in the Manager — the instance throws `RepositoryNotInitialized` as soon as it needs its manager, and models cannot find it. Always register custom repositories via the Manager's constructor or `register_repository()`; treat `get_repository()` as a lookup for repositories that are already registered. Details in the [Manager reference](../reference/manager.md). + +## Extending the library + +The extension story is always the same three steps, no matter the model family: subclass a model (add typed properties with source attributes, or `get_*` accessor methods for computed values), subclass the matching repository (override `model()` plus the family-specific config such as `post_types()` or `taxonomy()`), and register the repository with the Manager. That trio — model, repository, registration — is all the wiring there is; the [custom post types guide](../guides/custom-post-types.md) walks through it end to end, and the same pattern covers [taxonomies](../guides/custom-taxonomies.md) and [custom tables](../guides/custom-tables.md). + +## Models are array-like + +Besides magic properties, `Model` implements `IteratorAggregate` and `ArrayAccess`, and offers `to_array()` for serialization — handy when passing models to templates or REST responses: + +```php +$book = $books->get( 123 ); + +echo $book['isbn']; // ArrayAccess read, same lazy resolution as $book->isbn +$data = $book->to_array( [ 'id', 'title', 'isbn' ] ); +// result: [ 'id' => 123, 'title' => 'Dune', 'isbn' => '978-0441172719' ] +``` + +> [!NOTE] +> `to_array()` with no argument — and `foreach ( $book as … )`, which iterates over it — resolves *every* declared property, including relations, and can fire many queries. Pass the allow-list of properties you actually need for cheap serialization. + +## Related + +- [Quickstart](../getting-started/quickstart.md) — the whole CRUD loop in five minutes +- [Property resolution](property-resolution.md) — the lazy `__get`/`__set` pipeline in full +- [Persistence](persistence.md) — what `create()`, `save()`, and `delete()` actually do per family +- [Manager reference](../reference/manager.md) — constructor, registration, and lookup methods +- [Model reference](../reference/model.md) — the abstract model API +- [Repository reference](../reference/repository.md) — the shared repository contract +- [Custom post types guide](../guides/custom-post-types.md) — the extension story, step by step diff --git a/docs/concepts/persistence.md b/docs/concepts/persistence.md new file mode 100644 index 0000000..991dc04 --- /dev/null +++ b/docs/concepts/persistence.md @@ -0,0 +1,197 @@ +# Persistence + +**`create()` builds a model in memory and never touches the database — only the repository's `save()` writes, and each model family writes through a different WordPress function.** + +Models hold the data, repositories talk to WordPress, the Manager wires them together. That means a model never saves itself: there is no `$book->save()`. Persistence is always a repository call — `$repository->save( $model )` to write, `$repository->delete( $model )` to remove. This page explains exactly what those calls do for every built-in model family, what gets persisted, what silently doesn't, and how failures are reported. + +Two families bend the "nothing is written before `save()`" rule — [site meta](#site-multisite) writes to the database immediately on assignment, and [WooCommerce models](#woocommerce-product-order-order-items) write through to an in-memory WooCommerce object on assignment. Both are covered below. + +## `create()` builds, `save()` writes + +`Repository::create( array $data = array() )` instantiates the model and assigns each `$data` key through the model's `__set` (so type coercion and `set_*` hooks apply, and unknown keys are silently dropped). It performs no database query — the model exists only in memory until you pass it to `save()`. + +```php +use Wpify\Model\PostRepository; + +$posts = $manager->get_repository( PostRepository::class ); +$book = $posts->create( array( 'title' => 'Dune', 'post_status' => 'draft' ) ); +echo $book->id; // result: 0 — nothing in the database yet +$book = $posts->save( $book ); +echo $book->id; // result: 123 — wp_insert_post() ran, row exists in wp_posts +``` + +> [!NOTE] +> `create()` is the only supported way to hydrate a model from an array. The `$data` parameter of the `Model` constructor is accepted but completely ignored — `new Book( $manager, array( 'title' => 'Dune' ) )` produces an empty model. See the [quickstart](../getting-started/quickstart.md). + +## What `save()` does + +Most repositories' `save()` follows the same pipeline; only the middle "write" step differs per family. Two families deviate from the ordering — see the note below the diagram. + +```text +$repository->save( $model ) + ├─ collect writable props (collect_persistable_props) + │ ├─ skip every #[ReadOnlyProperty] prop + │ ├─ persist_{prop}( $value ) model hooks → called (side effect only, value not bucketed) + │ ├─ #[SourceObject] values → 'data' bucket, keyed by the source key + │ └─ #[Meta] values → 'meta' bucket, keyed by the meta key + ├─ dispatch to the family's WordPress write function (table below) + ├─ post family only: run relation persist() (PostTermRelation / PostTermsRelation) + ├─ refresh the model from a freshly loaded source + │ (skippable via the 'wpify_model_refresh_model_after_save' filter) + └─ do_action( 'wpify_model_repository_save_insert' | 'wpify_model_repository_save_update' ) +``` + +> [!NOTE] +> Term repositories run the collect step **after** the write, not before: `TermRepository::save()` calls `collect_persistable_props()` only once `wp_insert_term()` / `wp_update_term()` has run, so `persist_*` hooks on term models fire post-write, together with the `meta` bucket. The WooCommerce repositories skip the collect step entirely — they run `persist_*` hooks in a plain loop and never build the `data`/`meta` buckets (see [below](#woocommerce-product-order-order-items)). + +Collecting the props reads every writable property, so a `save()` forces resolution of all lazy props that are persistable — including any lazy database lookups backing them. Props with no source attribute and no `persist_*` hook land in neither bucket and are never persisted. + +> [!NOTE] +> Props marked `#[ReadOnlyProperty]` are never persisted, by any repository. Assigning one while it is still empty succeeds in memory (see [property resolution](property-resolution.md)) but the value is skipped at save time — it silently vanishes on the next refresh. + +### The write step per family + +| Family | WP write call | Meta written via | Notes | +|---|---|---|---| +| Post, Page, Attachment | `wp_insert_post()` / `wp_update_post()` | `meta_input` on the same call | Insert when `$model->id` is `0`; relation `persist()` runs after the write | +| Term, Category, PostTag, ProductCat | `wp_insert_term()` / `wp_update_term()` | `update_term_meta()` after the term write | Writes a fixed field list, not the `data` bucket | +| User | `wp_insert_user()` / `wp_update_user()` | `meta_input` | Booleans stored as the strings `'true'` / `'false'` | +| Comment | `wp_insert_comment()` / `wp_update_comment()` | `comment_meta` key in the data array | Booleans cast to `int` before writing | +| Site (multisite) | `wp_insert_site()` / `wp_update_site()` | `update_site_meta()` — already written at assignment | Meta write-through happens before `save()` | +| Product, Order, order items (WooCommerce) | the WC object's own `save()` | WC `update_meta_data()` at assignment, in memory | Props already written through to the WC object | + +Custom table models follow their own SQL-based flow — see the [custom tables guide](../guides/custom-tables.md). + +## Per-family save semantics + +### Posts (Post, Page, Attachment) + +- Insert vs. update is decided by the collected `ID`: `0` → `wp_insert_post()`, otherwise `wp_update_post()`. +- `#[Meta]` props are deferred: assignment only caches the value, and everything is written in one call via `meta_input`. +- After the post write, `PostRepository::save()` additionally calls `persist()` on relation source attributes — this is what makes `$post->categories` and `$post->tags` (both `#[PostTermsRelation]`) persist, via `wp_set_post_terms()` with `$append = false`. Because reading the relation lazily loads the current terms, every save re-assigns the post's categories and tags even when you never touched them. +- Model `persist_*` hooks run during prop collection, **before** the post is written. `Post::persist_featured_image_id()` calls `set_post_thumbnail()` at that point. + +> [!WARNING] +> Because `persist_featured_image_id()` runs before `wp_insert_post()`, a featured image set on a **new** post is silently lost on the first save (the model's ID is still `0`). Save once, then set `featured_image_id` and save again. Details in the [custom post types guide](../guides/custom-post-types.md). + +### Terms (Term, Category, PostTag, ProductCat) + +- `save()` does **not** use the `data` bucket. It passes an explicit field list to `wp_insert_term()` / `wp_update_term()`: `name`, `slug`, `term_group` (from `$model->group`), `description`, `parent` (from `$model->parent_id`), and `alias_of`. `taxonomy_id`, `count`, and `filter` are never written. +- The taxonomy is `$model->taxonomy` when set, falling back to the repository's `taxonomy()`. +- `#[Meta]` props (on custom term model subclasses) are written one by one via `update_term_meta()` after the term write. +- On insert, the model's `id` is populated only by the post-save refresh — if the `wpify_model_refresh_model_after_save` filter returns `false`, an inserted term model keeps `id = 0`. +- Save failures wrap the underlying `WP_Error` — see [When saving fails](#when-saving-fails). + +### Users + +- `#[SourceObject]` keys have their `data.` prefix stripped, so `user_login`, `user_email`, etc. are passed bare to `wp_insert_user()` / `wp_update_user()`. +- `#[Meta]` props go into `meta_input`; boolean values are stored as the strings `'true'` / `'false'` and converted back to `bool` on read. +- `$user->password` is a write-only prop with no source attribute; `save()` reads it explicitly. On insert with an empty password, the repository generates one via `wp_generate_password( 24 )` — `wp_insert_user()` requires it. +- WordPress itself ignores `user_login` changes in `wp_update_user()`, so editing `$user->login` on an existing user silently does nothing. + +### Comments + +- All `#[SourceObject]` values go into the data array (`comment_ID`, `comment_post_ID`, …); `#[Meta]` props of custom subclasses are attached under the `comment_meta` key. +- Booleans in the data are cast to `int`, so `$comment->approved = true` is written as `comment_approved = 1`. +- The insert path uses the low-level `wp_insert_comment()` — no flood check, no validation, unlike `wp_new_comment()`. +- On insert, `$model->id` is assigned directly from the return value, even when the post-save refresh is filtered off — the only family that does this. +- `save()` throws on a `WP_Error` **or** on a `false` result. + +### Site (multisite) + +> [!IMPORTANT] +> Requires multisite. Every `SiteRepository` method that touches WordPress — including `save()` and `delete()` — is a PHP fatal error (`Call to undefined function`) on a single-site install. See the [multisite guide](../guides/multisite.md). + +- `save()` strips `blog_id` from the data and renames `site_id` to `network_id` (the shape `wp_insert_site()` / `wp_update_site()` expect), then inserts or updates based on `$model->id`. +- `#[Meta]` props are written via `update_site_meta()` after the site write — but they were already written once at assignment time (below). +- Save failures wrap the underlying `WP_Error`. + +> [!NOTE] +> Site meta is the one place where assignment writes to the database **immediately**: setting `$site->admin_email` calls `update_site_meta()` on the spot, before any `save()`. Every other WordPress family defers meta writes to `save()`. If site meta is unsupported (no `wp_blogmeta` table), writes are silently dropped. + +### WooCommerce (Product, Order, order items) + +> [!IMPORTANT] +> Requires WooCommerce. The repositories are registered unconditionally, but the first real call without WooCommerce active is a PHP fatal error (`Call to undefined function wc_get_product()`), not a catchable library exception. See the [WooCommerce guide](../guides/woocommerce.md). + +- Assigning an `#[AccessorObject]` or `#[Meta]` prop writes through to the in-memory WC object immediately (`WC_Product::set_name()`, `update_meta_data()`, …). Nothing reaches the database yet. +- `save()` does not use the `data`/`meta` buckets at all: it runs the model's `persist_*` hooks, then calls the source object's own `save()` (`WC_Product::save()`, `WC_Order::save()`), which performs the actual database write. +- Insert vs. update is decided by `$model->source()->get_id()` — by the WC object, not the model. +- `OrderItemRepository::save()` refreshes the model but fires no save actions and skips the refresh filter, unlike the Product and Order repositories. + +> [!WARNING] +> `create()` + `save()` alone cannot persist a WooCommerce model. `create()` attaches no WC source object, so prop assignments have nowhere to write through, and `save()` fatals with `Call to a member function get_id() on null` — the insert-vs-update check on `$model->source()` runs before the write. Attach a WC object first, then set props. + +```php +use Wpify\Model\ProductRepository; + +$products = $manager->get_repository( ProductRepository::class ); +$product = $products->create(); +$product->source( new WC_Product_Simple() ); // attach the WC source object FIRST +$product->name = 'Dune — hardcover'; // now writes through to the WC_Product +$product = $products->save( $product ); // WC_Product::save() hits the database +echo $product->id; // result: 456 +``` + +## Relations do not persist (with one exception) + +Relation props (`ManyToOneRelation`, `ChildPostsRelation`, `TermPostsRelation`, `OrderItemsRelation`, …) are read-only views: assigning them caches a value on the model that no repository ever writes. To change a relation, persist the underlying foreign key (`$book->author_id = 7;`), not the relation prop. The full list is in the [relations guide](../guides/relations.md). + +The exception is `PostTermRelation` / `PostTermsRelation`, which carry a `persist()` method — but only `PostRepository::save()` (and its Page/Attachment subclasses) calls it. + +> [!WARNING] +> `Product::$categories` uses `#[PostTermsRelation]`, but `ProductRepository::save()` never calls relation `persist()` — assigning `$product->categories` and saving silently discards the change. Set `$product->category_ids` instead, which writes through to `WC_Product::set_category_ids()`. + +## Deleting models + +Every repository implements `delete( ModelInterface $model, bool $force_delete = true ): bool`, but only some honor the flag — WordPress has no trash for terms, users, or sites. + +| Family | Delete call | `$force_delete` honored? | Notes | +|---|---|---|---| +| Post, Page, Attachment | `wp_delete_post()` / `wp_trash_post()` | Yes — `false` trashes | Default `true` deletes permanently | +| Term family | `wp_delete_term()` | No | Always permanent | +| User | `wp_delete_user()` | No | Requires `require_once ABSPATH . 'wp-admin/includes/user.php';` outside admin requests | +| Comment | `wp_delete_comment()` | Yes — `false` trashes | | +| Site | `wp_delete_site()` | No | Always permanent; multisite only | +| Product, Order, order items | the WC object's own `delete( $force_delete )` | Yes | Default `true` skips the trash — the opposite of WooCommerce admin behavior | + +Passing `false` where the flag is honored moves the record to the trash instead of deleting it. + +```php +$posts->delete( $book, false ); // result: true — wp_trash_post(), recoverable +$posts->delete( $book ); // result: true — wp_delete_post(), permanent +``` + +## When saving fails + +Every `save()` throws `CouldNotSaveModelException` (a subclass of `Wpify\Model\Exceptions\ModelException`) when the underlying WordPress call fails. Term and Site saves attach the original `WP_Error` to the exception; User, Comment, Post, and WooCommerce saves throw with the message only, so `get_wp_error()` returns `null` for them. + +```php +use Wpify\Model\CategoryRepository; +use Wpify\Model\Exceptions\CouldNotSaveModelException; + +$categories = $manager->get_repository( CategoryRepository::class ); +try { + $categories->save( $categories->create( array( 'name' => 'Fantasy' ) ) ); +} catch ( CouldNotSaveModelException $e ) { + $e->getMessage(); // result: "A term with the name provided already exists…" + $e->get_wp_error(); // result: WP_Error — attached for Term and Site saves only +} +``` + +Catch `Wpify\Model\Exceptions\ModelException` to handle every failure the library can throw in one place. The [troubleshooting guide](../guides/troubleshooting.md) maps each error message to its cause. + +## Related + +- [Architecture](architecture.md) — the model / repository / Manager mental model +- [Property resolution](property-resolution.md) — how lazy props, caching, and readonly enforcement work +- [Meta fields](../guides/meta-fields.md) — everything `#[Meta]`, including per-family write timing +- [Relations](../guides/relations.md) — every relation attribute and which ones persist +- [Custom post types](../guides/custom-post-types.md) — the full `Book` CRUD walkthrough +- [Custom tables](../guides/custom-tables.md) — persistence for custom table models +- [WooCommerce](../guides/woocommerce.md) · [Multisite](../guides/multisite.md) +- [Repository reference](../reference/repository.md) — the shared repository contract + +## Custom-table transactions + +`CustomTableRepository::transaction()` and the `Transaction` helper group database writes with rollback on exceptions and savepoint-based nesting. They do not roll back WordPress caches, in-memory models or hook side effects. See [transactions](../reference/transactions.md) before grouping writes across repositories. diff --git a/docs/concepts/property-resolution.md b/docs/concepts/property-resolution.md new file mode 100644 index 0000000..b0a3eca --- /dev/null +++ b/docs/concepts/property-resolution.md @@ -0,0 +1,247 @@ +# Property resolution + +**Reading a model property runs a fixed pipeline — cached value → `get_*` accessor method → source attribute → type coercion → declared default — and the result stays cached until you invalidate it.** + +Models declare ordinary typed public properties, but you never actually read those properties: the `Model` constructor unsets every one of them, so all access goes through `__get`/`__set`. In line with the library's core rule — models hold the data, repositories talk to WordPress, the Manager wires them together — `Model::__get` does not resolve values itself; it delegates to the repository's `resolve_property()`. This page walks the entire flow in order: what the constructor records, what happens on read, how type coercion works, what happens on write, and how to invalidate the cache. Consult it whenever a property reads or writes something you did not expect. + +## The running example + +All snippets on this page use this bookstore model. It is a complete pasteable file: a `Book` custom post type model with meta-backed, computed, relation-typed, and read-only properties, plus its repository and the Manager registration. + +```php +title . ' (ISBN ' . $this->isbn . ')'; + } +} + +class BookRepository extends PostRepository { + public function model(): string { + return Book::class; + } + + public function post_types(): array { + return array( 'book' ); + } +} + +$manager = new Manager( new BookRepository() ); +``` + +## What the constructor records + +When a model is constructed (`Repository::create()`, `get()`, and `find()` all do this for you), it reflects over every declared property, stores its metadata in an internal registry, and then `unset()`s the property itself. The reflection does not filter by visibility — a protected or private property is swept into the same machinery — so declare only public data properties on models. From that moment on the declared properties exist only for IDEs and static analysis — every runtime read and write is routed through the magic accessors and this registry. + +Per property, the registry records: + +| Key | Meaning | +| --- | --- | +| `name` | The property name. | +| `type` | The declared PHP type name; `'string'` when the property is untyped. | +| `readonly` | `true` when the property carries `#[ReadOnlyProperty]`. | +| `default` | The property's initialized default value, or `null` if it has none. | +| `allows_null` | Whether the declared type is nullable; `false` for untyped properties. | +| `source` | The property's source attribute instance (`#[SourceObject]`, `#[Meta]`, a relation…), if any. | +| `value` | The cached resolved value; absent until the first read. | + +Two details matter in practice. If several source attributes are stacked on one property, only the **last** one is kept — `#[ReadOnlyProperty]` is not a source attribute, so stacking it on top is fine. And an untyped property is treated as a non-nullable `string`, so give every property a real type. The whole registry, including cached values, is available via `$model->props()` — useful when debugging resolution (see the [Model reference](../reference/model.md)). + +## Reading a property + +A read like `$book->isbn` walks this pipeline. Steps 2–4 live in `Repository::resolve_property()`; the rest is `Model::__get`. + +```text +$book->isbn + │ +1. cached value in the registry? ── yes ──▶ return it + │ no +2. Book defines get_isbn()? ── yes ──▶ use its return value ──┐ + │ no │ +3. source attribute get(): │ + #[Meta( meta_key: 'isbn' )] │ + → get_post_meta( $book->id, 'isbn', true ) │ + │ │ +4. maybe_convert_to_type() ◀───────────────────────────────────────┘ + → coerce the value to the declared type (string) + │ +5. result is null? ──▶ fall back to the declared default ( '' ) + │ +6. cache the value in the registry, return it +``` + +Reading a property that was never declared skips this pipeline and throws `PropertyNotDefinedException` — the most common cause is a plain typo (see [Troubleshooting](../guides/troubleshooting.md)). + +### Accessor methods win over attributes + +If the model defines a `get_{prop}()` method, it is called and any source attribute on the property is ignored — this is how you add computed properties, and how you override where a built-in property comes from. The return value still goes through type coercion. + +```php +$books = $manager->get_repository( BookRepository::class ); +$book = $books->get( 42 ); +echo $book->citation; +// result: 'Dune (ISBN 9780441172719)' — built by get_citation(), no attribute involved +``` + +### Source attributes do the WordPress work + +Without an accessor method, the property's source attribute resolves the value: `#[SourceObject]` reads a field off the raw source object (for `Book`, the `WP_Post`), `#[Meta]` calls the meta API (`get_post_meta()` here), and relation attributes run queries through other repositories. The [attributes reference](../reference/attributes.md) documents every source attribute. A property with neither an accessor method nor a source attribute resolves as `null` pushed through type coercion: a nullable property short-circuits to its declared default, but a non-nullable property gets the coerced `null` — `''`, `0`, `false`, or `[]` — and any non-empty declared default is silently ignored (`public string $binding = 'paperback';` reads as `''`). + +```php +$book = $manager->get_repository( BookRepository::class )->get( 42 ); +echo $book->isbn; +// result: '9780441172719' — from get_post_meta( 42, 'isbn', true ), now cached +``` + +### Type coercion + +Every resolved value — whether it came from an accessor method or a source attribute — passes through `Repository::maybe_convert_to_type()`, which coerces it to the property's declared type. The rules, in the order they are checked: + +| Declared type | Conversion rule | +| --- | --- | +| any nullable type, when the value is `null` or `''` | Short-circuit: the declared default is returned, no coercion runs. | +| `int` / `integer` | `intval()` | +| `float` | `floatval()` | +| `string` | `strval()` | +| `bool` / `boolean` | The literal strings `'true'` / `'false'` become booleans; anything else goes through `boolval()`. | +| `array` | A string value is `json_decode`d associatively; anything else is `(array)` cast. | +| `object` | A string value is `json_decode`d; anything else is `(object)` cast. | +| any existing class name | The value is passed to that model class's repository: `$repository->get( $value )` — this is how model-typed properties auto-load related models. | +| anything else | Returned unchanged. | + +Two edge cases: a malformed JSON string on an `array`/`object` property decodes to `null` (no exception), and if the class-typed branch finds no registered repository for the class, the `RepositoryNotFoundException` is swallowed and the raw value is returned unchanged. + +The class-name rule is the most powerful one — a property typed with a registered model class turns a stored ID into a loaded model with zero configuration: + +```php +$book = $manager->get_repository( BookRepository::class )->get( 42 ); +echo $book->cover->id; +// result: 15 — meta '_cover_id' held '15'; coercion loaded it via AttachmentRepository::get() +``` + +At the WordPress layer that read runs `get_post_meta( 42, '_cover_id', true )` and then `get_post( 15 )` inside `AttachmentRepository::get()`. + +> [!NOTE] +> Nullable properties short-circuit coercion: when the raw value is `null` or `''`, the declared default is returned and no conversion runs. `?int $page_count = null` therefore reads as `null` when the meta row is missing — not `0`, as a non-nullable `int` would. If a property keeps returning its default, check whether it is nullable and its raw value empty. + +### Caching + +The final value is cached in the property registry, so the pipeline — including any meta lookups and relation queries — runs once per property. Later reads return the cached value until you invalidate it (see below); this also means a model does not notice changes made to the database behind its back. + +> [!NOTE] +> A resolved value of `null` is never cached — the cache check uses `isset()`. A nullable property whose value is genuinely `null` therefore re-runs the whole pipeline on every read. That is safe, but for a relation property it can mean a repeated query on every access. + +## Writing a property + +An assignment like `$book->isbn = '9780441172719'` runs through `Model::__set` in this order: + +1. **Read-only check** — throws `ReadOnlyPropertyException`, but only when the property is marked `#[ReadOnlyProperty]` *and* already holds a non-empty cached value. +2. **`set_{prop}()` hook** — if the model defines one, it is called *instead of* the default assignment and becomes fully responsible for storing the value. +3. **Coercion + cache** — otherwise the value goes through `maybe_convert_to_type()` (same table as above) and is cached. This is why assigning a raw ID to a model-typed property stores a loaded model: `$book->cover = 15` caches an `Attachment`. +4. **Write-through** — if the property's source attribute is an `#[AccessorObject]` or `#[Meta]`, its `set()` method is invoked immediately with the value you assigned. + +Note that assigning does **not** persist anything for most model families — for a `Book`, both `$book->title` and `$book->isbn` only update the in-memory cache until you call `$books->save( $book )`. What `save()` does with the cached values is covered in [Persistence](./persistence.md). + +### `set_*` hooks normalize on write + +Define `set_{prop}( $value )` on the model to normalize values as they are assigned. Because the hook replaces the default assignment, it must cache the value itself — use the ArrayAccess form `$this['prop']`, which writes straight to the registry. + +```php +// Inside the Book class: strip dashes from any assigned ISBN. +public function set_isbn( string $isbn ): void { + $this['isbn'] = str_replace( '-', '', $isbn ); +} +``` + +> [!WARNING] +> Never write `$this->isbn = $value` inside `set_isbn()` — that re-enters `__set`, which calls `set_isbn()` again, and the infinite recursion crashes PHP. Always use `$this['prop'] = $value` inside a `set_*` hook. Also note that a `set_*` hook bypasses type coercion — whatever it caches is what later reads return. + +### Write-through on assignment + +Step 4 means some source attributes react to assignment immediately, and the behavior differs by attribute and model family: + +| Source attribute | What happens on assignment | +| --- | --- | +| `#[AccessorObject]` | Calls the source object's setter immediately (e.g. `WC_Product::set_name()`) — in memory only. | +| `#[Meta]` on Product / Order / OrderItem models | Calls `update_meta_data()` on the WooCommerce object — in memory until `save()`. | +| `#[Meta]` on Site models | Calls `update_site_meta()` — an **immediate database write**, before any `save()`. | +| `#[Meta]` on Post / Term / User / Comment models | No-op — the value is only cached; meta is written by the repository's `save()`. | +| `#[SourceObject]`, relations, `#[Column]`, no attribute | No write-through — cache only until `save()`. | + +The write-through receives the exact value you assigned — not the coerced value from step 3, and not what a `set_*` hook cached. + +### Read-only properties + +`#[ReadOnlyProperty]` excludes a property from persistence and blocks overwriting it — but the guard is narrower than the name suggests. + +> [!WARNING] +> `#[ReadOnlyProperty]` throws only once a **non-empty** value is already cached. An unread property, or one whose cached value is empty (`''`, `0`, `false`, `null`, `[]`), can be freely assigned — any non-empty cached value arms the guard, whether it got there from a read or from an earlier assignment. And ArrayAccess writes bypass the check entirely: `$model['prop'] = $value` skips the readonly guard, `set_*` hooks, type coercion, *and* write-through, so a value set this way on an `#[AccessorObject]` or `#[Meta]`-on-WooCommerce property never reaches the underlying object and is silently lost on save. Treat `$model['prop'] = …` as an internal escape hatch, not a normal assignment. + +```php +$book = $manager->get_repository( BookRepository::class )->get( 42 ); +echo $book->catalog_code; // resolves and caches 'BK-0042' — the guard is now armed +$book->catalog_code = 'BK-9999'; +// result: ReadOnlyPropertyException: Cannot set readonly property catalog_code +``` + +## Invalidating the cache + +Because resolved values stay cached, a model does not see changes made outside it — by another process, a direct `update_post_meta()` call, or a WP admin edit. There are three ways to force re-resolution. + +To re-resolve a single property, `unset()` it — the property stays declared, only the cached value is dropped, and the next read runs the pipeline again (its ArrayAccess twin `unset( $book['isbn'] )` does exactly the same): + +```php +update_post_meta( $book->id, 'isbn', '9780593099322' ); // changed outside the model +echo $book->isbn; // result: '9780441172719' — still the cached value +unset( $book->isbn ); +echo $book->isbn; // result: '9780593099322' — re-resolved via get_post_meta() +``` + +To drop every cached value at once, call `refresh()` — optionally passing a new source object so `#[SourceObject]` properties re-read fresh data too. Repositories call `refresh()` for you after `save()`: + +```php +$book->refresh(); // clear all cached values, keep the current WP_Post +$book->refresh( get_post( $book->id ) ); // also swap in a freshly fetched source object +echo $book->title; +// result: the current title from the new WP_Post — nothing is served from cache anymore +``` + +A falsy argument (`null`, `false`, `0`) leaves the old source object in place, so `refresh()` alone is enough for meta and relation properties but keeps `#[SourceObject]` properties reading the same `WP_Post` snapshot. + +## Related + +- [Architecture](./architecture.md) — the model / repository / Manager mental model this page builds on. +- [Persistence](./persistence.md) — what `save()`, `create()`, and `delete()` do with the cached values. +- [Model properties guide](../guides/model-properties.md) — practical recipes: accessors, aliases, read-only props, serialization. +- [Meta fields guide](../guides/meta-fields.md) — everything about `#[Meta]`. +- [Relations guide](../guides/relations.md) — every relation attribute with examples. +- [Model reference](../reference/model.md) — the full `Model` API, including ArrayAccess and iteration. +- [Repository reference](../reference/repository.md) — `resolve_property()`, `maybe_convert_to_type()`, and the repository contract. +- [Attributes reference](../reference/attributes.md) — parameter tables for all 17 attributes. +- [Troubleshooting](../guides/troubleshooting.md) — exception messages mapped to causes and fixes. diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 0000000..c74e777 --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,94 @@ +# Installation + +Get wpify/model installed and bootstrapped inside a WordPress plugin in three steps: install the package, create the Manager, and verify it works by fetching a post. + +## Requirements + +| Requirement | Version | Needed for | +|---|---|---| +| PHP | 8.0 or newer | Everything — the library is built on PHP attributes | +| WordPress | Any currently supported release | Everything | +| Composer | Any 2.x | Installation and autoloading | +| WooCommerce | Active WooCommerce plugin | [Product and order models](../guides/woocommerce.md) only | +| WordPress multisite | Multisite install | [Site models](../guides/multisite.md) only | + +WooCommerce and multisite are **not** required to install or bootstrap the library. Their repositories are registered by default but only fail if you actually call them without WooCommerce active or outside a multisite install. + +## Step 1: install the package + +Install the library into your plugin (or theme) with Composer. + +```bash +composer require wpify/model +``` + +## Step 2: bootstrap the Manager + +The library has three moving parts: **models** hold the data, **repositories** talk to WordPress, and **the Manager** wires them together. To bootstrap, load Composer's autoloader in your plugin main file and create one `Manager` instance — its constructor registers all 18 built-in repositories (posts, pages, terms, users, comments, menus, and more; see the [Manager reference](../reference/manager.md) for the full list). + +```php +register_repository( new BookRepository() ); // result: void — BookRepository is wired to the Manager and Book models can now resolve it +``` + +Both paths inject the Manager into the repository, so its models can resolve it later. You will write your first custom repository in the [custom post types guide](../guides/custom-post-types.md). + +> [!WARNING] +> Do not rely on `get_repository()` to *create* a custom repository. If you ask for a repository class that was never registered, the Manager instantiates it lazily **without** wiring it up: the Manager is not injected and the repository is not indexed under its model class. The instance throws `RepositoryNotInitialized` as soon as it needs the Manager, and its models cannot be resolved. Always register custom repositories via constructor arguments or `register_repository()` first; treat `get_repository()` purely as a lookup for already-registered repositories. + +> [!NOTE] +> The two Manager getters take different arguments: `get_repository()` takes a **repository** class (`get_repository( PostRepository::class )`), while `get_model_repository()` takes a **model** class (`get_model_repository( Post::class )`). Mixing them up throws `RepositoryNotFoundException` or triggers the unwired lazy instantiation described above. + +## Step 3: verify it works + +Fetch any existing post through the built-in `PostRepository` — if this prints a title, the library is bootstrapped correctly. + +```php +use Wpify\Model\PostRepository; + +$posts = bookstore_manager()->get_repository( PostRepository::class ); +$post = $posts->get( 1 ); + +echo $post->title; // result: Hello world! +``` + +At the WordPress layer, `get( 1 )` calls `get_post( 1 )` and wraps the returned `WP_Post` in a `Post` model; `$post->title` is then read lazily from `WP_Post->post_title`. If no post with that ID exists, `get()` returns `null`. + +## Next steps + +- [Quickstart](quickstart.md) — the full create/read/update/delete loop on posts in five minutes. +- [Architecture](../concepts/architecture.md) — how models, repositories, and the Manager fit together. diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md new file mode 100644 index 0000000..50c4466 --- /dev/null +++ b/docs/getting-started/quickstart.md @@ -0,0 +1,122 @@ +# Quickstart + +In about five minutes you will run the whole CRUD loop — fetch, read, create, update, delete — on the built-in `Post` model, then get a first taste of a custom model. The library follows one rule throughout: **models hold the data, repositories talk to WordPress, the Manager wires them together.** + +**Prerequisites:** [Installation](installation.md) — Composer package installed and autoloader loaded in your plugin. + +## 1. Get a repository from the Manager + +Every operation starts with a repository, and repositories come from the Manager — construct it once (see [Installation](installation.md)) and pull repositories from it by class name. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); +// result: PostRepository instance, already wired to the Manager +``` + +## 2. Fetch a post + +`get()` is polymorphic: pass an ID, a slug, a full URL, or an existing `WP_Post` object, and you get a `Post` model back — or `null` when nothing matches. + +```php +$post = $posts->get( 1 ); // by ID +$post = $posts->get( 'hello-world' ); // by slug (tries slug first, then URL) +// result: Wpify\Model\Post instance, or null when not found +``` + +At the WordPress layer this calls `get_post()` for IDs and `get_posts()` (then `url_to_postid()`) for strings; the found `WP_Post` becomes the model's source object. + +## 3. Read properties + +Model properties are lazy: nothing is resolved until you read it, and each value is cached on the model after the first read. + +```php +echo $post->title; // result: 'Hello world!' +echo $post->permalink; // result: 'https://example.com/hello-world/' +$author = $post->author; +// result: Wpify\Model\User model, or null when the author no longer exists +``` + +`title` comes straight from `WP_Post->post_title` (the raw database value, no filters applied), `permalink` calls `get_permalink()`, and reading `author` loads a `User` model through `UserRepository` on first access. See [Post models](../reference/models/post.md) for the full property list. + +> [!NOTE] +> Reading a property that the model does not declare throws `PropertyNotDefinedException` — a typo like `$post->tittle` fails loudly instead of returning `null`. + +## 4. Create and save a post + +`create()` hydrates a new model from an array of property values — but the model exists only in memory: nothing is written to the database yet, and `$post->id` is still `0`. + +```php +$post = $posts->create( [ + 'title' => 'Summer reading sale', + 'content' => 'Every paperback 20% off this week.', + 'post_status' => 'draft', +] ); +// result: unsaved Post model, $post->id === 0 +``` + +> [!WARNING] +> Do not instantiate models directly with data: `new Post( $manager, [ 'title' => '…' ] )` silently ignores the array — the constructor accepts `$data` but never uses it. Always hydrate through the repository's `create()`. + +Persisting is the repository's job — call `save()` on the repository, passing the model. + +```php +$post = $posts->save( $post ); +// result: $post->id is now a real post ID, e.g. 123 +``` + +At the WordPress layer, `save()` collects the model's writable properties and calls `wp_insert_post()` (or `wp_update_post()` for existing posts), sending meta properties along as `meta_input`. + +> [!NOTE] +> `save()` lives on the repository, not the model — there is no `$post->save()`. Models hold the data; repositories talk to WordPress. + +## 5. Update and save + +Assigning a property only updates the model's in-memory cache; the change reaches the database when you `save()` again. + +```php +$post->title = 'Summer reading sale — extended'; +$post->post_status = 'publish'; +$posts->save( $post ); +// result: post 123 updated via wp_update_post() +``` + +## 6. Delete + +`delete()` removes the post permanently by default. + +```php +$deleted = $posts->delete( $post ); +// result: true — wp_delete_post() removed the post and its meta +``` + +Pass `false` as the second argument (`$posts->delete( $post, false )`) to move the post to trash instead, via `wp_trash_post()`. + +## 7. A taste of a custom model + +The same machinery powers your own content: subclass a built-in model and declare typed public properties with source attributes. Here is a `Book` with an ISBN stored in post meta. + +```php + 'Books', + 'public' => true, + ) ); +} ); +``` + +## Define the model + +A model is a plain class extending `Wpify\Model\Post`: every public property you declare becomes a lazily resolved, cached, typed property, and a source attribute on it tells the repository where its value lives. `#[Meta]` maps a property to post meta — by default under a meta key equal to the property name, or under an explicit key via `meta_key:`. + +```php + [!NOTE] +> The default meta key is the property name, so renaming `$isbn` to `$ean` would silently start reading a different meta key and your data would appear lost. For production models, pin the key explicitly with `meta_key:` — see the [meta fields guide](meta-fields.md). + +## Define the repository + +The repository binds the model class to the post type. Extending `PostRepository` you override exactly two methods: `model()` names the model class, `post_types()` names the post type(s) queried. + +```php + [!WARNING] +> `post_types()` must **return** the array. An older README example was missing the `return` keyword — copying it makes every call that touches `post_types()` — all `find*()` methods, `create()`, and `get()` by slug — fatal with a `TypeError`. Also note that `create()` requires `post_types()` to return exactly one post type; with zero or several it throws `CouldNotSaveModelException`. + +## Register with the Manager + +Pass your repository to the `Manager` constructor (alongside the 18 built-in repositories it registers itself), then retrieve it by its class name. Create the Manager once per request and share the instance — see [installation](../getting-started/installation.md). + +```php +use Wpify\Model\Manager; + +$manager = new Manager( new BookRepository() ); +$books = $manager->get_repository( BookRepository::class ); +// result: the registered BookRepository instance +``` + +An already-created Manager accepts late registrations too — useful when repositories come from a plugin container. + +```php +$manager->register_repository( new BookRepository() ); +// result: BookRepository is registered and wired to Book +``` + +## Retrieve many books + +`find()` and its variants are thin wrappers over `WP_Query`, pre-filtered to `post_type => 'book'`; every WP_Query argument works. `find_published()` is the everyday listing call. + +```php +$published = $books->find_published(); +foreach ( $published as $book ) { + echo $book->title; // result: titles of all published 'book' posts +} +``` + +At the WordPress layer this runs `new WP_Query( array( 'post_type' => array( 'book' ), 'post_status' => 'publish', 'posts_per_page' => -1 ) )`. + +> [!NOTE] +> Plain `find()` (and `find_all()`) defaults to `post_status => 'any'` — drafts, pending, and private books are included. Use `find_published()` for anything user-facing, or pass `post_status` yourself. More query options in the [querying guide](querying.md). + +## Retrieve one book + +`get()` accepts an ID, a slug, a full permalink URL, or a `WP_Post` object, and returns `null` when nothing matches — it never throws for a missing post. + +```php +$book = $books->get( 42 ); // by ID +$book = $books->get( 'dune' ); // by slug, restricted to post_type 'book' +echo $book->isbn; // result: '978-0-441-17271-9' +``` + +The ID lookup calls `get_post()`; the slug lookup calls `get_posts()`. Reading `$book->isbn` lazily calls `get_post_meta( $book->id, 'isbn', true )` on first access and caches the value on the model. + +## Create a book + +`create()` builds an in-memory model with `id === 0` and `post_type` already set to `book` — it writes nothing to the database. Only `save()` persists, and `save()` lives on the repository, not the model. + +```php +$book = $books->create( array( + 'title' => 'Dune', + 'isbn' => '978-0-441-17271-9', + 'price' => 19.99, +) ); +$book = $books->save( $book ); +echo $book->id; // result: 123 (the new post ID) +``` + +`save()` collects the writable properties and calls `wp_insert_post()` once: source-object properties (`title`, `slug`, `post_status`, …) become the post row in `wp_posts` (with `post_type = 'book'`), and `#[Meta]` properties are passed as `meta_input`, producing `isbn` and `_price` rows in `wp_postmeta`. On failure it throws `CouldNotSaveModelException`. + +> [!WARNING] +> A featured image set on a **new** model is silently lost on the first save: the persist step runs before `wp_insert_post()`, while the model's ID is still `0`, so `set_post_thumbnail()` targets a nonexistent post. Workaround — save first, then set the image and save again: +> +> ```php +> $book = $books->save( $book ); // insert first, so $book->id exists +> $book->featured_image_id = $attachment_id; +> $books->save( $book ); // now set_post_thumbnail() sticks +> ``` + +## Update a book + +Assigning a property only updates the model's in-memory cache; the database changes when you `save()`. + +```php +$book->price = 24.99; +$books->save( $book ); // result: same Book, refreshed from the database +``` + +This calls `wp_update_post()` for the post row and updates the `_price` row in `wp_postmeta` via `meta_input`. After a successful save the model is refreshed from `get_post()`, so its cached values reflect the database. + +## Delete a book + +`delete()` hard-deletes by default; pass `false` to move the book to trash instead. + +```php +$books->delete( $book ); // wp_delete_post( $book->id, true ) +$books->delete( $book, false ); // wp_trash_post( $book->id ) +// result: true on success +``` + +## Add a computed property + +Declare a property with a `get_{prop}` method and the method becomes its source: the repository calls it on first read, caches the result, and never persists it. Use this for derived values that should behave like regular model properties. + +```php +// inside class Book +public string $formatted_price = ''; + +public function get_formatted_price(): string { + return number_format( $this->price, 2 ) . ' €'; +} +``` + +Reading it looks exactly like a stored property. + +```php +echo $book->formatted_price; // result: '24.99 €' +``` + +An accessor method wins over any source attribute on the same property, and the value is cached after the first read — `unset( $book->formatted_price )` forces recomputation. More accessor patterns (setters, `persist_*` hooks) in the [model properties guide](model-properties.md). + +## Relate books to a custom taxonomy + +With a `Genre` term model for a custom `genre` taxonomy (built in the [custom taxonomies guide](custom-taxonomies.md)), one `#[PostTermsRelation]` property gives you the book's genres as models — readable and writable. + +```php +// add to the imports at the top of the Book file: +// use Wpify\Model\Attributes\PostTermsRelation; + +// inside class Book +/** @var Genre[] */ +#[PostTermsRelation( Genre::class )] +public array $genres = array(); +``` + +Reading calls the genre repository's `find_terms_of_post()` (a `get_the_terms()` wrapper); assigning term models and saving persists the assignment. + +```php +$genres = $manager->get_repository( GenreRepository::class ); + +$book->genres = array( $genres->get( 'sci-fi' ) ); +$books->save( $book ); // result: wp_set_post_terms( $book->id, [ ], 'genre' ) +``` + +> [!NOTE] +> `PostTermsRelation` replaces the taxonomy's whole term set on every save (`append = false`) — merge with the existing `$book->genres` array if you mean to add. All relation attributes, including single-term and inverse variants, are covered in the [relations guide](relations.md). + +## Add a custom finder + +Repositories are the natural home for reusable queries. A finder is just a method delegating to `find()` with the right `WP_Query` arguments — here, a meta query on the `isbn` key. + +```php +// inside class BookRepository +public function find_by_isbn( string $isbn ): ?Book { + $found = $this->find( array( + 'meta_key' => 'isbn', + 'meta_value' => $isbn, + 'posts_per_page' => 1, + ) ); + + return $found[0] ?? null; +} +``` + +Callers get a typed result with no query details leaking out. + +```php +$book = $books->find_by_isbn( '978-0-441-17271-9' ); +// result: Book, or null when no book has that ISBN +``` + +Because it goes through `find()`, the `post_status => 'any'` default applies — add `'post_status' => 'publish'` to the arguments if drafts should not match. + +## Related + +- [Custom taxonomies](custom-taxonomies.md) — build the `Genre` model used above +- [Meta fields](meta-fields.md) — everything `#[Meta]` can do +- [Model properties](model-properties.md) — accessors, read-only properties, aliases +- [Relations](relations.md) — every relation attribute +- [Querying](querying.md) — `find()` arguments, pagination, per-family `get()` semantics +- [Post family reference](../reference/models/post.md) — all inherited properties and repository methods +- [Attributes reference](../reference/attributes.md) +- [Repository reference](../reference/repository.md) +- [Manager reference](../reference/manager.md) diff --git a/docs/guides/custom-tables.md b/docs/guides/custom-tables.md new file mode 100644 index 0000000..73abdcf --- /dev/null +++ b/docs/guides/custom-tables.md @@ -0,0 +1,481 @@ +# Storing data in custom tables + +After this page you can persist plugin data in your own database table — schema, migrations, and CRUD included — without writing `CREATE TABLE` statements or `$wpdb` boilerplate by hand. + +**Prerequisites:** [Installation](../getting-started/installation.md) · [Architecture](../concepts/architecture.md) + +Throughout this guide we build a `BookLoan` custom table model backed by a `book_loans` table, tracking which reader borrowed which `Book` (the custom post type from the [custom post types guide](custom-post-types.md)). + +## Defining the model + +A custom table model is a plain model whose public properties carry the `#[Column]` source attribute — the attributes define both the table schema and how row values hydrate into typed properties. Save this as a complete file in your plugin: + +```php + 'posts', + Column::FOREIGN_COLUMN => 'ID', + Column::FOREIGN_SETTINGS => 'ON DELETE CASCADE', + ), + )] + public int $book_id = 0; + + #[Column( type: Column::VARCHAR, params: 100 )] + public string $borrower_email = ''; + + #[Column( type: Column::DATETIME )] + public string $loaned_at = ''; + + #[Column( type: Column::DATETIME, nullable: true )] + public ?string $returned_at = null; +} +``` + +Exactly one column must have `primary_key: true`, otherwise every repository operation throws `PrimaryKeyException`. The `foreign_key` table name is given *without* the WordPress prefix — the library always prepends `$wpdb->prefix`, so `'posts'` references `wp_posts`. + +> [!NOTE] +> Keep the primary-key property name and its column name identical (don't set a custom `name:` on the primary key). After an `INSERT`, the repository assigns the new `AUTO_INCREMENT` id to the model using the *column* name — if it differs from the property name, the id lands on the wrong key. + +Every `#[Column]` parameter and type constant is listed in [Column reference](#column-reference) below. + +## Defining the repository + +The repository extends `CustomTableRepository` and answers two questions: which model class defines the schema (`model()`) and what the table is called without the WordPress prefix (`table_name()`). Save this as a complete file: + +```php +get_repository( BookLoanRepository::class ); +// result: $loans is ready to use — the table itself is created lazily on first use +``` + +## Migrations + +### Automatic migration + +You don't run migrations yourself by default: before the first `save()`, `delete()`, or `find()` of a request, the repository compares the current schema against what's installed and runs WordPress's `dbDelta()` when they differ. The "version" is the `md5()` hash of the generated `CREATE TABLE` SQL, stored in the option `custom_table_book_loans_version` (note: the *unprefixed* table name in the option key) — so any change to a `#[Column]` attribute changes the hash and triggers a migration on next use. For `BookLoan`, the generated SQL is: + +```sql +CREATE TABLE wp_book_loans ( + id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + book_id bigint(21) UNSIGNED NOT NULL, + borrower_email varchar(100) NOT NULL, + loaned_at datetime NOT NULL, + returned_at datetime NULL, + CONSTRAINT `wp_book_loans_ibfk_1` FOREIGN KEY (`book_id`) REFERENCES `wp_posts` (`ID`) ON DELETE CASCADE, + PRIMARY KEY (id) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci; +``` + +(The charset/collation clause comes from `$wpdb->get_charset_collate()`.) If `dbDelta()` leaves an error in `$wpdb->last_error`, no exception is thrown — the version is simply not stored, so the migration retries on the next request. + +> [!NOTE] +> All the usual `dbDelta()` quirks apply: it never drops columns or keys you remove from the model, and foreign-key clauses are historically fragile in `dbDelta()`. Verify schema changes on a staging site, and treat removed columns as leftovers you clean up manually. + +Unique column indexes are named after the column so later `dbDelta()` migrations recognize them. A successful upgrade refreshes the version immediately; further operations on that repository in the same request use the upgraded schema. + +### Manual migration + +For production plugins, prefer migrating on the activation hook instead of during a front-end request: construct the repository with `auto_migrate: false` and call `migrate()` yourself. + +```php +use Wpify\Model\Manager; + +$loan_repo = new BookLoanRepository( auto_migrate: false ); +$manager = new Manager( $loan_repo ); + +register_activation_hook( __FILE__, fn () => $loan_repo->migrate() ); +// result: the table is created on plugin activation instead of on the first query +``` + +### Table prefix + +The second constructor argument, `use_prefix` (default `true`), controls whether `$wpdb->prefix` is prepended to `table_name()` — disable it for a table shared across a whole installation. + +```php +$loan_repo = new BookLoanRepository( use_prefix: false ); +// result: the repository reads and writes the unprefixed table `book_loans` +``` + +> [!NOTE] +> On multisite with the default `use_prefix: true`, `$wpdb->prefix` is per-site — every site gets its own `book_loans` table and its own `custom_table_book_loans_version` option. + +### Dropping the table on uninstall + +`drop_table()` removes the table, but it does *not* delete the stored version option — delete it yourself, otherwise after a reinstall the version hash still matches, the migration is skipped, and every query fails against the missing table. + +```php +function book_plugin_uninstall(): void { + ( new BookLoanRepository() )->drop_table(); + delete_option( 'custom_table_book_loans_version' ); +} +register_uninstall_hook( __FILE__, 'book_plugin_uninstall' ); +// result: DROP TABLE IF EXISTS `wp_book_loans`, and the stored schema version is removed +``` + +## CRUD + +All examples below assume `$loans` obtained from the Manager as shown in [Registering with the Manager](#registering-with-the-manager). + +### Retrieving many loans + +`find()` takes a structured argument array and returns hydrated models; the most important key is `where` (full syntax in [the next section](#the-where-array-syntax)). + +```php +$active = $loans->find( array( 'where' => array( 'returned_at' => null ) ) ); +// result: BookLoan[] of every loan not returned yet +``` + +At the WordPress layer this runs `SELECT … FROM wp_book_loans WHERE returned_at IS NULL` through `$wpdb->get_results()` and hydrates each row into a `BookLoan`. `find_all( $args )` is an alias for `find( $args )`. + +### Retrieving one loan + +`get()` accepts a primary-key value, a raw row object, or an existing model (returned unchanged). + +```php +$loan = $loans->get( 7 ); +// result: the BookLoan with id 7, or null when no such row exists +``` + +This runs ``SELECT … FROM wp_book_loans WHERE `id` = '7' LIMIT 1``; the row becomes the model's lazy source. + +### Creating a loan + +`create()` only builds an in-memory model from the given data — nothing touches the database until you pass it to `save()`. + +```php +$loan = $loans->create( array( + 'book_id' => 42, + 'borrower_email' => 'reader@example.com', + 'loaned_at' => current_time( 'mysql' ), +) ); +$loan = $loans->save( $loan ); +// result: $loan->id > 0 — assigned from AUTO_INCREMENT, model refreshed from the database +``` + +`save()` runs `$wpdb->insert( 'wp_book_loans', … )`, then re-reads the row so DB-generated values appear on the model (return the filter `wpify_model_refresh_model_after_save` as `false` to skip the re-read). + +### Updating a loan + +Load the model through the repository, change its properties, and save it back. + +```php +$loan = $loans->get( 7 ); +$loan->returned_at = current_time( 'mysql' ); +$loans->save( $loan ); +// result: row 7 updated; the model is refreshed from the database +``` + +This runs `$wpdb->update( 'wp_book_loans', …, array( 'id' => 7 ) )`. + +> [!WARNING] +> `save()` decides between `INSERT` and `UPDATE` by checking `$model->source()`, **not** the primary key. Models from `get()`/`find()` carry a source and are updated; models from `create()` carry none and are always inserted — even if you set an existing id on one by hand, which inserts a **duplicate row** (the id is merged into the insert data). Always fetch the model through the repository before updating it. + +### Deleting a loan + +`delete()` removes the row matching the model's primary key. + +```php +$deleted = $loans->delete( $loan ); +// result: true — the row was deleted via $wpdb->delete() +``` + +> [!NOTE] +> `delete()` returns `false` (no exception) when the model's primary key is empty — for example an unsaved model from `create()`. The `$force_delete` parameter exists for interface compatibility and is unused here. + +## The where array syntax + +The `where` key of `find()` accepts a structured array that the repository compiles into SQL, escaping scalar values with `esc_sql()` along the way. Each pattern below stands alone; combine them freely. + +### Equality + +A plain `'column' => value` pair compiles to an equality check; multiple pairs are joined with `AND` by default. + +```php +$loans->find( array( 'where' => array( + 'book_id' => 42, + 'borrower_email' => 'reader@example.com', +) ) ); +// result: WHERE book_id = 42 AND borrower_email = 'reader@example.com' +``` + +### Comparison operators + +Put the operator in the key after the column name — it's split on the first whitespace and upper-cased. + +```php +$old = $loans->find( array( 'where' => array( 'loaned_at <' => '2026-01-01 00:00:00' ) ) ); +// result: WHERE loaned_at < '2026-01-01 00:00:00' +``` + +### IN and NOT IN + +An array value defaults to `IN`; spell out `NOT IN` in the key for the inverse. + +```php +$loans->find( array( 'where' => array( 'book_id' => array( 42, 43, 44 ) ) ) ); +// result: WHERE book_id IN (42,43,44) +``` + +```php +$loans->find( array( 'where' => array( 'book_id NOT IN' => array( 42, 43 ) ) ) ); +// result: WHERE book_id NOT IN (42,43) +``` + +### LIKE + +With the `LIKE` operator, `%` wildcards are preserved and the text between them is escaped with `esc_sql()`. + +```php +$loans->find( array( 'where' => array( 'borrower_email LIKE' => '%@example.com' ) ) ); +// result: WHERE borrower_email LIKE '%@example.com' +``` + +### BETWEEN + +`BETWEEN` and `NOT BETWEEN` require an array of exactly two values — any other shape throws `SqlException`. + +```php +$h1 = $loans->find( array( 'where' => array( + 'loaned_at BETWEEN' => array( '2026-01-01 00:00:00', '2026-06-30 23:59:59' ), +) ) ); +// result: WHERE loaned_at BETWEEN '2026-01-01 00:00:00' AND '2026-06-30 23:59:59' +``` + +### NULL + +A `null` value compiles to `IS NULL` (the operator auto-switches to `IS`); use the `IS NOT` operator in the key for the inverse. + +```php +$open = $loans->find( array( 'where' => array( 'returned_at' => null ) ) ); +// result: WHERE returned_at IS NULL +``` + +### AND/OR glue + +A bare `'AND'`/`'OR'` string entry changes the glue used before the *next* clause; placed first, it becomes the default glue for the whole group. + +```php +$loans->find( array( 'where' => array( + 'OR', + array( 'borrower_email' => 'anna@example.com' ), + array( 'borrower_email' => 'ben@example.com' ), +) ) ); +// result: WHERE (borrower_email = 'anna@example.com') OR (borrower_email = 'ben@example.com') +``` + +### Nested groups + +An array at an integer key is compiled recursively and wrapped in parentheses — that's how you mix `AND` and `OR`. + +```php +$loans->find( array( 'where' => array( + 'book_id' => 42, + array( 'OR', array( 'returned_at' => null ), array( 'loaned_at >' => '2026-07-01 00:00:00' ) ), +) ) ); +// result: WHERE book_id = 42 AND ((returned_at IS NULL) OR (loaned_at > '2026-07-01 00:00:00')) +``` + +### Subqueries and EXISTS + +A string value starting with `SELECT` is treated as a subquery and wrapped in parentheses; with `EXISTS`/`NOT EXISTS` as the "column", the operator is dropped entirely. + +```php +global $wpdb; + +$book_loans = $loans->find( array( 'where' => array( + 'book_id IN' => "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'book'", +) ) ); +// result: WHERE book_id IN (SELECT ID FROM wp_posts WHERE post_type = 'book') +``` + +```php +global $wpdb; + +$live = $loans->find( array( 'where' => array( + 'EXISTS' => "SELECT 1 FROM {$wpdb->posts} WHERE ID = book_id AND post_status = 'publish'", +) ) ); +// result: WHERE EXISTS (SELECT 1 FROM wp_posts WHERE ID = book_id AND post_status = 'publish') +``` + +### Raw SQL strings + +A plain string instead of an array is used verbatim as the `WHERE` clause — an escape hatch for SQL the array syntax cannot express. + +```php +$loans->find( array( 'where' => 'book_id = 42 AND returned_at IS NULL' ) ); +// result: the string becomes the WHERE clause exactly as written +``` + +> [!WARNING] +> String values for `where`, `having`, `order_by`, `group_by`, `join`, and `select`, subquery strings, and the ids passed to `find_by_ids()` are inserted into the query **verbatim — nothing is escaped**. Only scalar values in the *array* where-syntax pass through `esc_sql()`. Never interpolate untrusted input into any raw-string argument; prefer the array syntax, and run anything raw through `esc_sql()` yourself. + +## Ordering, limits and pagination + +### Ordering + +`order_by` takes a raw `ORDER BY` expression as a string, or an array of them joined with commas (the raw-SQL warning above applies). + +```php +$latest = $loans->find( array( 'order_by' => array( 'loaned_at DESC', 'id ASC' ) ) ); +// result: ORDER BY loaned_at DESC, id ASC +``` + +### Limit and offset + +`limit` and `offset` are plain integers; combine them for pagination. + +```php +$per_page = 20; +$page = 3; + +$rows = $loans->find( array( + 'order_by' => 'loaned_at DESC', + 'limit' => $per_page, + 'offset' => ( $page - 1 ) * $per_page, +) ); +// result: rows 41–60, newest first +``` + +### Fetching by ids + +`find_by_ids()` compiles to an `IN` clause on the primary key — the ids are joined unescaped, so pass trusted integers only. + +```php +$some = $loans->find_by_ids( array( 3, 5, 8 ) ); +// result: WHERE (id IN (3,5,8)) +``` + +### Counting rows + +> [!WARNING] +> Known limitation: the `count` flag of `find()` only splices `COUNT(*)` after the `SELECT` keyword, leaving the column list in place — with the default query that is invalid SQL, so `find( array( 'count' => true ) )` throws `SqlException`. Even with a custom `select` that stays valid after the rewrite, the result rows are still hydrated into models — you never get an int back. + +For a real count, add a method to your repository subclass using the protected `db()` helper — here is the full `BookLoanRepository` with it: + +```php +db()->get_var( + "SELECT COUNT(*) FROM {$this->prefixed_table_name()} WHERE returned_at IS NULL" + ); + } +} +``` + +Call it like any other repository method: + +```php +$open_count = $loans->count_active(); +// result: the number of open loans as an int, e.g. 3 +``` + +### Grouping + +> [!WARNING] +> Known limitation: `group_by` and `having` are appended to the generated SQL *after* `ORDER BY`/`LIMIT`/`OFFSET`, so combining them with ordering or pagination produces invalid MySQL and throws `SqlException`. Use `group_by`/`having` on their own, or write the whole query yourself via the `select` argument. + +## Column reference + +### `#[Column]` parameters + +All parameters are optional named arguments of the attribute constructor. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `name` | `string` | `''` | Column name. Defaults to the property name. | +| `type` | `string` | `''` | One of the `Column::*` type constants below. When empty, inferred from the PHP property type: `bool` → `BOOLEAN`, `int` → `INT`, `float` → `DECIMAL`, `string` → `VARCHAR`, `array`/`object` → `TEXT`. | +| `params` | `mixed` | `null` | Length or precision, e.g. `100` for `VARCHAR` or `array( 10, 2 )` for `DECIMAL`. | +| `unsigned` | `bool` | `false` | Adds `UNSIGNED`. | +| `nullable` | `bool` | `false` | Emits `NULL` instead of `NOT NULL`. Only applies when no `default` is given. | +| `default` | `string` | `''` | Emits `DEFAULT …` (quoted for `VARCHAR`/`TEXT`). When set, neither `NULL` nor `NOT NULL` is emitted. | +| `on_update` | `string` | `''` | Emits `ON UPDATE …` (e.g. `CURRENT_TIMESTAMP`). Columns with `on_update` are **excluded from `save()` writes** — meant for DB-managed timestamps. | +| `auto_increment` | `bool` | `false` | Adds `AUTO_INCREMENT`. | +| `primary_key` | `bool` | `false` | Marks the primary key. Exactly one column must have it; composite keys are not supported. | +| `unique` | `bool` | `false` | Emits a `UNIQUE KEY` for the column. | +| `foreign_key` | `array` | empty | `array( Column::FOREIGN_TABLE => …, Column::FOREIGN_COLUMN => …, Column::FOREIGN_SETTINGS => … )`. Emits a named `CONSTRAINT … FOREIGN KEY` clause; the referenced table is always prefixed with `$wpdb->prefix`. | + +### Column types + +| Constant | SQL type | Default `params` | +|---|---|---| +| `Column::TINYINT` | `tinyint` | `4` | +| `Column::INT` | `int` | `11` | +| `Column::BIGINT` | `bigint` | `21` | +| `Column::BOOLEAN` | `boolean` | — | +| `Column::DECIMAL` | `decimal` | `(65,10)` | +| `Column::DATE` | `date` | — | +| `Column::DATETIME` | `datetime` | — | +| `Column::TIMESTAMP` | `timestamp` | — | +| `Column::TIME` | `time` | — | +| `Column::CHAR` | `char` | `1` | +| `Column::VARCHAR` | `varchar` | `255` | +| `Column::BLOB` | `blob` | — | +| `Column::TEXT` | `text` | — | +| `Column::ENUM` | `enum` | — | +| `Column::SET` | `set` | — | +| `Column::JSON` | `json` | — | + +> [!NOTE] +> Array and object values are stored serialized via `maybe_serialize()` — except columns typed `Column::JSON`, which are written with `wp_json_encode()` and read back with `json_decode( …, true )` (associative arrays), giving clean JSON round-trips. + +## Related + +- [CustomTableRepository reference](../reference/custom-table-repository.md) — full method signatures, the formal `find()` argument grammar, and exceptions +- [Attributes reference](../reference/attributes.md) — `#[Column]` alongside every other attribute +- [Persistence](../concepts/persistence.md) — what `create()`/`save()`/`delete()` do across all model families +- [Querying models](querying.md) — retrieving built-in WordPress models +- [Custom post types](custom-post-types.md) — the `Book` model this guide's `book_id` points at +- [Troubleshooting](troubleshooting.md) — error message → cause → fix + +## Atomic writes + +Use `$repository->transaction( $callback )` to save related custom-table rows together. Prepare other participating tables before entry, and keep HTTP, emails and other external effects outside the callback. Existing transactions use savepoints. See [transactions](../reference/transactions.md) for examples and rollback limitations. + +When reusing a repository across `switch_to_blog()` calls, schema SQL, version and migration caches reset when its physical table changes. Each shop therefore checks/migrates its own prefixed table. Prepare the participating shop’s tables before entering a transaction. diff --git a/docs/guides/custom-taxonomies.md b/docs/guides/custom-taxonomies.md new file mode 100644 index 0000000..7b69a15 --- /dev/null +++ b/docs/guides/custom-taxonomies.md @@ -0,0 +1,312 @@ +# Custom taxonomies + +After this page you can model a custom taxonomy as a typed PHP class — with term meta, parent/child hierarchy, and full CRUD — and attach its terms to a custom post type. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Quickstart](../getting-started/quickstart.md), [Architecture](../concepts/architecture.md) + +This guide builds the `Genre` taxonomy of a bookstore plugin: `Genre extends Term`, `GenreRepository extends TermRepository`, and genres attached to `Book` posts. The post-type half of the bookstore lives in the [custom post types guide](custom-post-types.md). + +## Register the taxonomy in WordPress + +Registering the `genre` taxonomy itself is your job, not the library's — the models only read and write terms of a taxonomy that already exists. + +```php +add_action( 'init', function () { + register_taxonomy( 'genre', array( 'book' ), array( + 'label' => 'Genres', + 'hierarchical' => true, + 'show_ui' => true, + ) ); +} ); +``` + +## Define the Genre model + +A taxonomy model extends `Wpify\Model\Term` and only declares what it adds — here a `color` property stored as term meta. Pin the meta key with `meta_key:` so renaming the property later cannot orphan existing data (see the [meta fields guide](meta-fields.md)). + +```php +get_repository( GenreRepository::class ); +// result: GenreRepository +``` + +## What Genre inherits from Term + +Every `Term` property is available on `Genre`; you only ever add to this list. The full reference lives on the [Term models page](../reference/models/term.md). + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `#[SourceObject( 'term_id' )]` | `0` until the term is saved. | +| `name` | `string` | `#[SourceObject( 'name' )]` | Required on insert — an empty name makes `save()` throw. | +| `slug` | `string` | `#[SourceObject( 'slug' )]` | Generated by WordPress from the name when left empty. | +| `description` | `string` | `#[SourceObject( 'description' )]` | | +| `taxonomy` | `string` | `#[SourceObject( 'taxonomy' )]` | Falls back to the repository's `taxonomy()` on save and delete. | +| `taxonomy_id` | `int` | `#[SourceObject( 'term_taxonomy_id' )]` | Never persisted. | +| `group` | `int` | `#[SourceObject( 'term_group' )]` | Saved as `term_group`. | +| `parent_id` | `int` | `#[SourceObject( 'parent' )]` | Set this to move the term in the hierarchy. | +| `parent` | `?Term` | `#[ManyToOneRelation( 'parent_id' )]` | Lazy; not persisted — set `parent_id` instead. | +| `top_parent` | `?Term` | `#[TopLevelTermParentRelation]` | Highest ancestor; `null` for top-level terms. | +| `children` | `Term[]` | `#[ChildTermsRelation]` | Recursive — includes grandchildren, not just direct children. | +| `count` | `int` | `#[SourceObject( 'count' )]` | WordPress's cached object count; never persisted. | +| `filter` | `string` | `#[SourceObject( 'filter' )]` | Sanitization level; not a database field. | +| `permalink` | `string` | `get_permalink()` getter, `#[ReadOnlyProperty]` | `get_term_link()`. Read it only on saved terms — for a nonexistent term the underlying `WP_Error` cannot be cast to string and the read throws. | +| `alias_of` | `string` | *(none)* | Consumed by `save()` as the `alias_of` argument of `wp_insert_term()` / `wp_update_term()`. | + +## Retrieve many genres + +`find()` runs `get_terms()` scoped to the `genre` taxonomy and wraps every result in a `Genre` model. + +```php +$fiction = $genres->find( array( 'orderby' => 'name' ) ); +// result: [ Genre, Genre, ... ] — only genres that have at least one book +``` + +> [!NOTE] +> `find()` inherits `get_terms()`'s default `hide_empty => true`, so **terms with no assigned objects are silently omitted** — the opposite of the post side, where `find()` returns everything. This also applies to `find_by_ids()` and `find_children_of()`. Pass `hide_empty => false` (or use `find_all()`) to include empty terms. + +```php +$all = $genres->find( array( 'hide_empty' => false ) ); +// result: every genre, including ones with no books yet +``` + +The repository ships these finders — all accept `get_terms()`-style `$args` and return `Genre[]`: + +| Method | Behavior | +|---|---| +| `find( array $args = [] )` | `get_terms()` with `taxonomy => 'genre'`; hides empty terms by default. | +| `find_all( array $args = [] )` | `find()` defaulting to `hide_empty => false` — includes empty terms. | +| `find_not_empty( array $args = [] )` | `find()` defaulting to `hide_empty => true`. | +| `find_children_of( int $parent_id = 0, array $args = [] )` | All descendants via `child_of`; hides empty terms by default; returns `[]` without querying unless `$parent_id > 0`. | +| `find_terms_of_post( int $post_id )` | Genres assigned to a post, via `get_the_terms()`. | +| `find_child_terms_of( ModelInterface $model )` | Backs the `children` property; includes empty terms. | +| `find_by_ids( array $ids, array $args = [] )` | `find()` with `include => $ids`; still hides empty terms unless overridden. | + +More querying patterns (pagination, cross-family `get()` semantics) are covered in the [querying guide](querying.md). + +## Retrieve one genre + +`get()` accepts a term ID, a `WP_Term` object, a slug, or a term name (slug is tried first), and returns `null` when nothing matches. + +```php +$genre = $genres->get( 'sci-fi' ); // by slug, falling back to name +$genre = $genres->get( 42 ); // by term ID +echo $genre->name; // result: Science fiction +``` + +> [!WARNING] +> `get( 0 )` does **not** return `null`. `get_term( 0 )` returns a `WP_Error`, which is truthy, so the repository wraps it as a model source — you get a `Genre` whose properties all resolve to their defaults (`id === 0`), and reading `permalink` on it throws. Always check `id` after `get()` when the input might be `0`. + +```php +$genre = $genres->get( $maybe_id ); + +if ( $genre && $genre->id > 0 ) { + echo $genre->name; // result: safe to use — the term really exists +} +``` + +## Create a genre + +`create()` builds an in-memory model with `id === 0` and never touches the database; only `save()` persists it. At the WordPress layer, `save()` calls `wp_insert_term( 'Science fiction', 'genre', [...] )` — inserting rows into `wp_terms` and `wp_term_taxonomy` — then writes each `#[Meta]` property via `update_term_meta()` and refreshes the model, populating `id`. + +```php +$genre = $genres->create( array( + 'name' => 'Science fiction', + 'slug' => 'sci-fi', + 'description' => 'Space, robots, and speculative futures.', +) ); +$genre = $genres->save( $genre ); +echo $genre->id; // result: 7 — real term ID after wp_insert_term() +``` + +> [!NOTE] +> When WordPress rejects the term (empty name, duplicate name at the same hierarchy level, …), `save()` throws `CouldNotSaveModelException` with the underlying `WP_Error` attached — call `get_wp_error()` on the exception to inspect the exact error code. + +```php +use Wpify\Model\Exceptions\CouldNotSaveModelException; + +try { + $genres->save( $genres->create() ); // empty name +} catch ( CouldNotSaveModelException $e ) { + $error = $e->get_wp_error(); // result: WP_Error with code 'empty_term_name' +} +``` + +## Update a genre + +Assigning to a property only caches the value in memory — including `#[Meta]` properties like `color`; nothing hits the database until `save()`. On an existing term, `save()` calls `wp_update_term()` with the core fields and then `update_term_meta( $id, '_genre_color', ... )` for the meta. + +```php +$genre->description = 'Updated description.'; +$genre->color = '#3366ff'; +$genre = $genres->save( $genre ); +echo $genre->color; // result: #3366ff — now stored in wp_termmeta under _genre_color +``` + +## Delete a genre + +`delete()` calls `wp_delete_term( $genre->id, 'genre' )` and returns `false` only when that call yields a `WP_Error` (e.g. an invalid taxonomy). Deleting a nonexistent or already-deleted term still returns `true`, so the return value cannot detect that case. Terms have no trash, so the `$force_delete` parameter is accepted but ignored — deletion is always permanent. + +```php +$genres->delete( $genre ); // result: true — rows removed from wp_terms / wp_term_taxonomy +``` + +## Parent and child genres + +Because `genre` is registered with `hierarchical => true`, terms can nest: set `parent_id` on a new term and `save()` passes it as `parent` to `wp_insert_term()`. + +```php +$cyberpunk = $genres->create( array( + 'name' => 'Cyberpunk', + 'parent_id' => $genre->id, +) ); +$cyberpunk = $genres->save( $cyberpunk ); +echo $cyberpunk->parent_id; // result: 7 — the Science fiction term ID +``` + +Reading the hierarchy is lazy: `children` runs a `get_terms()` query on first access, `parent` and `top_parent` each load their term through a repository. + +```php +foreach ( $genre->children as $child ) { + echo $child->name; // result: Cyberpunk +} +echo $cyberpunk->parent->name; // result: Science fiction +echo $cyberpunk->top_parent->name; // result: Science fiction +``` + +> [!NOTE] +> Two asymmetries to keep in mind. First, `children` is recursive (`child_of` includes grandchildren), so on deep hierarchies it is the whole subtree — as `Genre` models, since the relation resolves through your `GenreRepository`. Second, `parent` is typed `?Term` and resolves through the generic `TermRepository`, so it is a plain `Term` without your meta properties; call `$genres->get( $genre->parent_id )` when you need a full `Genre`. + +To fetch a subtree without going through a model, use the finder directly — like `find()`, it hides empty terms unless you override `hide_empty`, and Cyberpunk has no books yet. + +```php +$descendants = $genres->find_children_of( $genre->id, array( 'hide_empty' => false ) ); +// result: [ Genre 'Cyberpunk' ] — all descendants; [] unless the ID is positive +``` + +## Attach genres to books + +The post side owns the assignment: a `#[PostTermsRelation]` property on the `Book` model reads the book's genres and persists them when the book is saved. See the [custom post types guide](custom-post-types.md) for the full `Book` model — the minimal version needed here is: + +```php +id, [ ...term ids ], 'genre' )`. + +```php +use Wpify\Model\Manager; + +$manager = new Manager( new BookRepository(), new GenreRepository() ); +$books = $manager->get_repository( BookRepository::class ); +$genres = $manager->get_repository( GenreRepository::class ); + +$book = $books->get( 'dune' ); +$book->genres = array( $genres->get( 'sci-fi' ) ); +$books->save( $book ); // result: Book — genre assigned via wp_set_post_terms() +``` + +> [!NOTE] +> The relation persists **only** through the post repository: `BookRepository::save()` re-assigns the current `$book->genres` (non-append) on every save, while saving a `Genre` never touches any book. To add or remove one genre, modify the `genres` array and save the book. See the [relations guide](relations.md) for all relation attributes and their persistence rules. + +Reading works from both directions — from the book via the relation property, and from the taxonomy side via finders. + +```php +foreach ( $book->genres as $genre ) { + echo $genre->name; // result: Science fiction +} +``` + +```php +$book_genres = $genres->find_terms_of_post( $book->id ); // result: [ Genre 'Science fiction' ] +$sci_fi_books = $books->find_all_by_term( $genres->get( 'sci-fi' ) ); +// result: [ Book 'Dune', ... ] — WP_Query with a tax_query on the term ID +``` + +## Related + +- [Custom post types](custom-post-types.md) — the `Book` half of this bookstore +- [Meta fields](meta-fields.md) — everything about `#[Meta]` +- [Relations](relations.md) — all relation attributes, including `PostTermsRelation` +- [Querying](querying.md) — `get()`/`find()` semantics across model families +- [Persistence](../concepts/persistence.md) — what `save()` does per family +- [Term models reference](../reference/models/term.md) — full `Term`/`Category`/`PostTag` API +- [Repository reference](../reference/repository.md) — the shared repository contract +- [Attributes reference](../reference/attributes.md) — every attribute with parameters +- [Troubleshooting](troubleshooting.md) — error message → cause → fix diff --git a/docs/guides/menus.md b/docs/guides/menus.md new file mode 100644 index 0000000..cb33655 --- /dev/null +++ b/docs/guides/menus.md @@ -0,0 +1,198 @@ +# Working with navigation menus + +After this page you can load a WordPress navigation menu as a typed model, walk its nested item tree, and render a nav — including current-page highlighting — without touching `wp_nav_menu()`. + +**Prerequisites:** [Installation](../getting-started/installation.md) · [Architecture](../concepts/architecture.md) + +Two built-in models cover menus: `Menu` extends `Term` (a menu is a term in the `nav_menu` taxonomy) and `MenuItem` extends `Post` (each item is a `nav_menu_item` post decorated by WordPress). The Manager registers `MenuRepository` and `MenuItemRepository` by default, so no extra registration is needed. + +> [!NOTE] +> `MenuItemRepository` is marked `@internal` — you should not call it directly; go through `MenuRepository` instead. It still must be registered (the Manager does this by default), because resolving `Menu::$children` looks up the repository for `MenuItem::class` and fails with `RepositoryNotFoundException` without it. + +## Getting a menu by theme location + +`MenuRepository::get()` accepts a theme location key — the string you passed to `register_nav_menus()` — and returns the menu currently assigned to that location, or `null` when nothing matches. + +```php +use Wpify\Model\Manager; +use Wpify\Model\MenuRepository; + +$manager = new Manager(); +$menu_repo = $manager->get_repository( MenuRepository::class ); + +$menu = $menu_repo->get( 'primary' ); // theme location key +echo $menu->name; // result: Main navigation +``` + +At the WordPress layer, `get()` calls `get_nav_menu_locations()` once and resolves the assigned menu via `wp_get_nav_menu_object()`; non-location sources fall through to a normal term lookup (`get_term()` / `get_term_by()`). + +> [!NOTE] +> **Location wins over slug and name.** If the string matches a registered location key, you get the menu assigned to that location — even if another menu has that exact slug or name. Also, the locations array is cached per repository instance on the first `get()` call that finds any assigned locations (caching is skipped while the array is empty), so locations assigned later are invisible to an instance that has already cached a non-empty set. A location key with no menu assigned falls through to the plain term lookup, which usually returns `null`. + +## Getting a menu by ID, slug, or name + +Anything `TermRepository::get()` accepts also works: a term ID, a slug, a name, or a `WP_Term` object. Always check the return value — `get()` returns `null` for menus it cannot find. + +```php +$menu = $menu_repo->get( 42 ); // term ID +$menu = $menu_repo->get( 'main-menu' ); // slug (falls back to name) +echo $menu ? $menu->name : 'not found'; // result: Main navigation +``` + +## Listing menus + +`find_all()` returns every menu on the site, including menus with no items. + +```php +$menus = $menu_repo->find_all(); +echo implode( ', ', array_map( fn( $m ) => $m->name, $menus ) ); +// result: Main navigation, Footer, Social links +``` + +This runs a `WP_Term_Query` over the `nav_menu` taxonomy. Plain `find( $args )` passes your args through to `WP_Term_Query`, whose default `hide_empty` hides menus that have no items — use `find_all()` or pass `'hide_empty' => false` when you want all of them. + +## Reading the item tree + +`Menu::$children` is the nested item tree: an array of top-level `MenuItem` models, each with its own `$children`. It is lazy — resolved on first access, then cached on the model instance. + +```php +$menu = $menu_repo->get( 'primary' ); + +foreach ( $menu->children as $item ) { + echo $item->title, ' -> ', $item->url, PHP_EOL; +} +// result: Home -> https://example.com/ +// Books -> https://example.com/books/ +``` + +First access triggers exactly one `wp_get_nav_menu_items()` call; each returned item is wrapped as a `MenuItem` model and nested under its parent using `menu_item_parent`. + +> [!NOTE] +> Two deprecated aliases exist: `Menu::$items` is an `#[AliasOf( 'children' )]` for `Menu::$children` and still works, while `MenuItem::$item_children` is **non-functional and always resolves to an empty array**. Use `$children` on both models. + +### MenuItem properties + +The nav-specific properties declared on `MenuItem`: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `db_id` | `int` | `#[SourceObject]` | The menu item's own post ID. | +| `menu_item_parent` | `int` | `#[SourceObject]` | Parent item's DB ID; `0` for top-level items. | +| `object_id` | `int` | `#[SourceObject]` | ID of the linked object (post ID, `term_id`, …). | +| `object` | `string` | `#[SourceObject]` | Linked object type: `"page"`, `"category"`, `"custom"`, … | +| `custom` | `string` | `#[SourceObject]` | Custom field of the decorated nav item. | +| `type_label` | `string` | `#[SourceObject]` | Human-readable label of the item type. | +| `title` | `string` | `#[SourceObject]` | The navigation label. | +| `url` | `string` | `#[SourceObject]` | Link target URL. | +| `target` | `string` | `#[SourceObject]` | Link `target` attribute (e.g. `_blank`). | +| `attr_title` | `string` | `#[SourceObject]` | Link `title` attribute. | +| `description` | `string` | `#[SourceObject]` | Item description. | +| `classes` | `array` | `#[SourceObject]` | CSS classes for the item's `
  • `. | +| `xfn` | `string` | `#[SourceObject]` | Link relationship (XFN). | +| `children` | `MenuItem[]` | tree builder | Filled when the parent `Menu` tree is built; read-only. | +| `item_children` | `MenuItem[]` | — | Deprecated, always empty — use `children`. | +| `is_current` | `bool` | computed | `get_is_current()`: `object_id === get_the_ID()`. | +| `is_highlighted` | `bool` | computed | `get_is_highlighted()`: current, or any descendant is. | + +`MenuItem` extends `Post`, so it also inherits every `Post` property (`id`, `menu_order`, `post_type`, …) — see the [Menu model reference](../reference/models/menu.md) for the full list. Note that `title` here is the navigation label, not `post_title` as on every other `Post` subclass. + +> [!NOTE] +> `$children` is only populated when items come from `Menu::$children` or `MenuRepository::items()` — a `MenuItem` fetched any other way has an empty `$children`, which also makes `is_highlighted` collapse to `is_current`. + +## Getting items without the menu model + +`items( $source, $return )` is a shortcut that resolves the menu and returns its `children` directly; `$source` accepts everything `get()` does. With the default `MenuRepository::RETURN_OBJECTS` you get `MenuItem[]`, and an empty array when the menu is not found. + +```php +$items = $menu_repo->items( 'primary' ); +echo $items[0]->title; // result: Home +``` + +Pass `MenuRepository::RETURN_ARRAY` to get nested plain arrays instead — handy for a REST response, since `Menu::to_array()` always serializes `children` recursively. + +```php +use Wpify\Model\MenuRepository; + +$items = $menu_repo->items( 'footer', MenuRepository::RETURN_ARRAY ); +// result: [ [ 'title' => 'About us', 'url' => 'https://example.com/about/', 'children' => [], ... ], ... ] +``` + +> [!NOTE] +> `RETURN_ARRAY` runs a full `to_array()` pass, resolving every lazy property of the menu and every item — noticeably heavier than `RETURN_OBJECTS`. Prefer objects unless you actually need arrays. + +## Highlighting the current page + +`is_current` tells you whether an item points at the post currently being viewed; `is_highlighted` also returns `true` when any descendant item is current — ideal for keeping a top-level item active while on a subpage. + +```php +foreach ( $menu_repo->items( 'primary' ) as $item ) { + echo $item->title, $item->is_highlighted ? ' (active)' : '', PHP_EOL; +} +// result: Home +// Books (active) +``` + +> [!NOTE] +> `is_current` compares `object_id` against `get_the_ID()`, which reads the global post: on a singular page that is the queried post even in the header, on an archive it is the current post of the main query, and it is `false` only when no post global is set (e.g. REST or cron context). For a taxonomy item `object_id` is a `term_id` that can coincidentally equal a post ID. Both flags are cached on first read — read them in the template context where they should be evaluated. + +## Rendering a nav from the tree + +Because every item carries its own `$children`, a short recursive function replaces `wp_nav_menu()` and gives you full markup control. + +```php +'; + + foreach ( $items as $item ) { + printf( + '
  • %s', + esc_attr( implode( ' ', $item->classes ) . ( $item->is_highlighted ? ' active' : '' ) ), + esc_url( $item->url ), + $item->target ? ' target="' . esc_attr( $item->target ) . '"' : '', + esc_html( $item->title ) + ); + + if ( $item->children ) { + render_menu_items( $item->children ); + } + + echo '
  • '; + } + + echo ''; +} + +$manager = new Manager(); +$menu_repo = $manager->get_repository( MenuRepository::class ); + +render_menu_items( $menu_repo->items( 'primary' ) ); +``` + +## What saving supports + +Menus are read-mostly in this library. `MenuRepository` inherits full CRUD from `TermRepository`, so `save()` persists the term fields — `name`, `slug`, `description`, `group`, `parent_id`, `alias_of` — via `wp_update_term()` (or `wp_insert_term()` for a new menu), plus any `#[Meta]` properties via `update_term_meta()`. + +```php +$menu = $menu_repo->get( 'primary' ); +$menu->name = 'Primary navigation'; +$menu_repo->save( $menu ); // calls wp_update_term() on the nav_menu term +// result: menu renamed; its items are untouched +``` + +> [!WARNING] +> **Menu items cannot be saved through this library.** `Menu::$children` is a relation property, so saving the menu never touches its items. Saving a `MenuItem` directly is worse: nav-specific properties (`url`, `target`, `attr_title`, …) are `#[SourceObject]` props, so the repository passes them as top-level `wp_insert_post()` arguments — which WordPress ignores, because it stores them in `_menu_item_*` post meta. The nav fields are silently dropped. Treat menu items as read-only and manage menu structure in the WordPress admin (or via `wp_update_nav_menu_item()`). + +## Related + +- [Menu model reference](../reference/models/menu.md) — full property tables and repository method signatures +- [Term model reference](../reference/models/term.md) — the inherited term surface (`Menu extends Term`) +- [Post model reference](../reference/models/post.md) — the inherited post surface (`MenuItem extends Post`) +- [Relations guide](relations.md) — `MenuItemsRelation` and the other relation attributes +- [Querying guide](querying.md) — `get()`/`find()` semantics across model families +- [Attributes reference](../reference/attributes.md) +- [Troubleshooting](troubleshooting.md) diff --git a/docs/guides/meta-fields.md b/docs/guides/meta-fields.md new file mode 100644 index 0000000..c9d776e --- /dev/null +++ b/docs/guides/meta-fields.md @@ -0,0 +1,230 @@ +# Working with meta fields + +After this page you can map WordPress metadata onto typed model properties with the `#[Meta]` source attribute — and you'll know exactly when each model family writes that meta to the database. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Custom post types](custom-post-types.md), [Property resolution](../concepts/property-resolution.md) + +## Declaring a meta property + +`#[Meta]` is a source attribute: put it on a public model property and the repository resolves the value from the model's meta storage on first access. With no arguments, the meta key defaults to the property name. + +```php +get_model_repository( Book::class ); + +$book = $books->get( 42 ); +echo $book->isbn; // result: '978-80-257-2478-8' +``` + +On first access the repository calls `get_post_meta( 42, 'isbn', true )` and caches the result on the model; later reads never hit the database until you call `refresh()` or `unset( $book->isbn )`. + +Assigning a new value only caches it on the model — for post models nothing is written until the repository saves. + +```php +$book->isbn = '978-80-257-0000-0'; // cached in memory only +$books->save( $book ); // result: meta row updated in wp_postmeta +``` + +`save()` collects all `#[Meta]` values into the `meta_input` argument of `wp_update_post()` (or `wp_insert_post()` for a new model), so the post fields and its meta are written in one call. + +## Choosing the meta key + +Pass the meta key as the first constructor argument — positionally or as the named argument `meta_key:` — whenever the stored key differs from the property name, for example the WordPress convention of prefixing hidden meta with `_`. + +```php +use Wpify\Model\Attributes\Meta; + +#[Meta( '_price' )] // positional +public float $price = 0.0; + +#[Meta( meta_key: '_stock' )] // named argument +public int $stock = 0; +``` + +> [!WARNING] +> With no explicit key, **renaming the property changes the meta key**: a refactor from `$isbn` to `$isbn_13` makes the model read and write `isbn_13` meta, and every value stored under `isbn` appears lost. Always pin `meta_key:` on production models so property names can change without touching stored data. + +### Parameters + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$meta_key` | `?string` | `null` | Meta key to read and write. When `null`, the property name is used. | +| `$single` | `bool` | `true` | Passed to the underlying `get_*_meta()` call. `false` returns every stored value for the key as an array. | + +## Typed properties and coercion + +Meta always comes out of the database loosely typed — numeric strings, `'true'`/`'false'`, serialized arrays. Every resolved value passes through the repository's `maybe_convert_to_type()`, so the property's declared PHP type decides what you get; the full flow is on the [property resolution](../concepts/property-resolution.md) page. + +| Declared type | Stored meta value | Property value | +|---|---|---| +| `int` | `'42'` | `42` | +| `float` | `'249.90'` | `249.9` | +| `bool` | `'true'` / `'false'` | `true` / `false` | +| `array` | serialized array (WP meta rules) | the array — WordPress unserializes before the model sees it | +| `array` | JSON string | decoded array | +| `array` | any non-JSON string | `null`, so the property falls back to its declared default | +| `object` | JSON string | decoded `stdClass` | + +Array and object values are serialized by WordPress itself: `meta_input` and the `update_*_meta()` functions run them through `maybe_serialize()` on write and unserialize on read, so arrays round-trip with no work on your side. The JSON branch only applies when the value reaches the model as a plain string — for example JSON stored by another plugin. + +```php +// On the Book model: +#[Meta( meta_key: '_book_formats' )] +public array $formats = array(); +``` + +Assign a PHP array and save — WordPress serializes it into a single meta row: + +```php +$book->formats = array( 'hardcover', 'ebook' ); +$books->save( $book ); // one serialized meta row in wp_postmeta +print_r( $book->formats ); // result: Array ( [0] => hardcover [1] => ebook ) +``` + +> [!NOTE] +> A non-JSON string in an `array`-typed property decodes to `null` and silently falls back to the property default. If a meta prop that "definitely has a value" reads as an empty array, check what is actually stored under that key. + +> [!NOTE] +> `UserRepository::save()` stores boolean user meta as the strings `'true'` / `'false'`; the coercion table above converts them back to `bool` on read, so boolean user meta props round-trip transparently. + +## Single vs multiple values + +By default `single: true` returns one value. Set `single: false` to read **all** rows stored under the key as an array — and type the property `array`. + +```php +use Wpify\Model\Attributes\Meta; +use Wpify\Model\Attributes\ReadOnlyProperty; + +#[ReadOnlyProperty] +#[Meta( meta_key: 'edition_year', single: false )] +public array $edition_years = array(); + +// result: [ '1998', '2004', '2011' ] — one entry per meta row +``` + +> [!WARNING] +> Treat `single: false` properties as read-only. On save, the repository collects **one value per meta key** and writes it through a single update call — and WordPress's `update_metadata()` overwrites **every** existing row for that key with the same value, so each row ends up holding the whole serialized array and the per-row values are gone. Stack `#[ReadOnlyProperty]` on the property (as above) to exclude it from persistence, or write the rows yourself with a `persist_*` method (see [below](#custom-storage-with-persist_-methods)). + +## When meta is written + +`#[Meta]` dispatches on the model's base class, and each family both reads through a different WordPress function and persists at a different moment. + +> [!IMPORTANT] +> The Product/Order/OrderItem rows require WooCommerce, and the Site row requires multisite with site-meta support (`is_site_meta_supported()`). See the [WooCommerce](woocommerce.md) and [multisite](multisite.md) guides. + +| Model family | Read via | Write happens | WP write call | +|---|---|---|---| +| `Post`, `Page`, `Attachment` (and subclasses) | `get_post_meta()` | Deferred until repository `save()` | `meta_input` on `wp_insert_post()` / `wp_update_post()` | +| `Term`, `Category`, `PostTag` (and subclasses) | `get_term_meta()` | Deferred until repository `save()` | `update_term_meta()` after `wp_insert_term()` / `wp_update_term()` | +| `User` | `get_user_meta()` | Deferred until repository `save()` | `meta_input` on `wp_insert_user()` / `wp_update_user()` | +| `Comment` | `get_comment_meta()` | Deferred until repository `save()` | `comment_meta` on `wp_insert_comment()` / `wp_update_comment()` | +| `Site` | `get_site_meta()` | **Immediately on assignment** (and again on `save()`) | `update_site_meta()` | +| `Product`, `Order`, `OrderItem` | `$model->source()->get_meta()` | On assignment, in memory only | The WC object's own `save()`, called by the repository's `save()` | +| Any other model (custom table models included) | — (resolves `null` → property default) | Never | — | + +> [!NOTE] +> `Site` is the odd one out: assigning to a site meta prop calls `update_site_meta()` right away, before any `save()`. Every other WordPress family defers to the repository, so an abandoned model changes nothing. + +> [!NOTE] +> Models outside the dispatch — custom table models, for example — silently read the property default, and their `#[Meta]` values are never written. Use [`#[Column]`](../reference/attributes.md) for custom table storage instead. + +> [!WARNING] +> On a WooCommerce model with no source object attached (a fresh `create()` result), reading or assigning a `#[Meta]` prop is a PHP fatal — reading fails with `Call to a member function get_meta() on null`, assigning with `Call to a member function update_meta_data() on null`. Attach the source first, e.g. `$product->source( new \WC_Product_Simple() )`; the [WooCommerce guide](woocommerce.md) shows the full creation flow. + +## Meta before the model has an ID + +A model returned by `create()` has `id === 0`, and `get_post_meta( 0, … )` returns nothing — so unsaved models read meta props as their declared defaults. Values you assign before the first save are cached on the model and written together with the insert. + +```php +$book = $books->create( array( 'title' => 'Vieweghova čítanka' ) ); +echo $book->isbn; // result: '' (no ID yet — the declared default) + +$book->isbn = '978-80-257-2478-8'; // cached on the model +$book = $books->save( $book ); // result: post inserted, meta written via meta_input +``` + +The insert path is safe because the meta travels inside the `wp_insert_post()` call itself — no ID is needed at assignment time. + +## Custom storage with `persist_*` methods + +When neither `SourceObject` nor `Meta` semantics fit, define a `persist_{prop}( $value )` method on the model: during `save()` the repository calls it instead of collecting the property into the data or meta buckets, so you control the storage completely. The WordPress-family repositories (Post, Term, User, Comment, Site) and the WooCommerce repositories honor `persist_*`; `CustomTableRepository` does not — it saves `#[Column]` properties only, so a `persist_*` method on a custom table model is never called. Pair it with a `get_{prop}()` accessor for reads — see [model properties](model-properties.md). + +This resolves the multi-value limitation from above: persist each array entry as its own meta row. + +```php +id, 'edition_year' ); + + foreach ( $years as $year ) { + add_post_meta( $this->id, 'edition_year', $year ); + } + } +} +``` + +On save, the repository calls `persist_edition_years()` instead of adding the property to `meta_input`: + +```php +$book->edition_years = array( 1998, 2004, 2011 ); +$books->save( $book ); // result: three separate edition_year rows in wp_postmeta +``` + +> [!WARNING] +> `persist_*` methods run **before** `wp_insert_post()`, so on a brand-new model `$this->id` is still `0` and any write keyed by the ID is silently lost — the same ordering trap as the featured image on first save (see [custom post types](custom-post-types.md)). Workaround: save the model once to get an ID, then set the property and save again. + +## Related + +- [Custom post types](custom-post-types.md) — the `Book` model and `BookRepository` used on this page +- [Custom taxonomies](custom-taxonomies.md) — term meta in context +- [Model properties](model-properties.md) — `get_*` / `set_*` / `persist_*` accessors, `#[ReadOnlyProperty]`, defaults +- [Persistence](../concepts/persistence.md) — what `save()` does step by step, per family +- [Property resolution](../concepts/property-resolution.md) — the full lazy `__get` flow and coercion rules +- [Attributes reference](../reference/attributes.md) — every attribute, including the full `#[Meta]` entry +- [Troubleshooting](troubleshooting.md) — "my meta prop is always empty" and friends diff --git a/docs/guides/model-properties.md b/docs/guides/model-properties.md new file mode 100644 index 0000000..f424fc3 --- /dev/null +++ b/docs/guides/model-properties.md @@ -0,0 +1,325 @@ +# Shaping model properties + +After this page you can give a model computed properties, normalized writes, custom save logic, aliases, and read-only guards — everything a property can do beyond plain source fields and meta. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Property resolution](../concepts/property-resolution.md), [Custom post types](custom-post-types.md) + +## Setup for the examples + +Every example below is a variation of the bookstore `Book` model (custom post type `book`) served by this repository, registered once with the Manager. + +```php +get_repository( BookRepository::class );`. + +## Defaults and nullability + +The model constructor records each declared public property's type, default value, and nullability. When [property resolution](../concepts/property-resolution.md) comes back with `null`, the property's declared default is returned instead — and on a nullable property, an empty string from the source also collapses to the default before any type coercion runs. + +```php +get( 42 ); +var_dump( $book->subtitle ); // result: NULL +var_dump( $book->isbn ); // result: string(0) "" +``` + +At the WordPress layer, `get( 42 )` wraps `get_post( 42 )`, and each meta property reads via `get_post_meta()` on first access. + +> [!NOTE] +> A resolved value of `null` is not treated as cached — the cache check is `isset()`-based. A nullable property that genuinely resolves to `null` re-runs its lookup on every read. Untyped properties are treated as `string` and are not nullable. + +## Computed properties with `get_{prop}()` + +Declare a public property and add a `get_{prop}()` method to compute its value; the repository checks for this method first, so it overrides any source attribute on the same property. The result still passes through type coercion and is cached after the first read — `unset( $book->citation )` or `$book->refresh()` forces a recompute. + +```php +title, $this->isbn ); + } +} +``` + +Reading the property looks exactly like reading a stored one. + +```php +$book = $books->get( 42 ); +echo $book->citation; // result: Dune (ISBN 9780441172719) +``` + +The built-in `Post` model uses this pattern for `$permalink` (`get_permalink()`), `$featured_image_id` (`get_featured_image_id()`), and `$rendered_excerpt`. + +> [!NOTE] +> A computed property with no source attribute and no `persist_{prop}()` hook is never written by `save()` — it exists only in memory. + +## Normalizing writes with `set_{prop}( $value )` + +Define `set_{prop}( $value )` to normalize a value on assignment; `__set` calls your method *instead of* the default assignment, so the method must store the value itself. Store it through array access — `$this['isbn'] = ...` — which writes directly into the property cache. + +```php +create( array( 'title' => 'Dune' ) ); +$book->isbn = '978-0-441-17271-9'; +echo $book->isbn; // result: 9780441172719 +``` + +Nothing touches the database here; the ISBN is written as `isbn` meta when `$books->save( $book )` runs `wp_insert_post()` with `meta_input`. + +> [!WARNING] +> Never assign `$this->isbn = ...` inside `set_isbn()` — that re-enters `__set`, which calls `set_isbn()` again, and the infinite recursion crashes PHP. Always store via `$this['isbn'] = ...`. + +> [!NOTE] +> A `set_{prop}()` hook bypasses automatic type coercion, so store an already-correct type. On model families where meta writes through immediately on assignment (Site, WooCommerce), the write-through receives the original raw value, not what your hook stored. + +## Custom persistence with `persist_{prop}( $value )` + +Define `persist_{prop}( $value )` to take full responsibility for writing a property during `save()`: the repository calls your hook with the current value and does *not* put the value into the post data or meta buckets — even when the property carries a `#[Meta]` or `#[SourceObject]` attribute. For term assignments the [relation attributes](relations.md) are usually the better tool; `persist_*` hooks shine for storage the library has no attribute for. + +```php +id, 'genre', array( 'fields' => 'slugs' ) ); + } + + public function persist_genre_slugs( array $genre_slugs ): void { + wp_set_object_terms( $this->id, $genre_slugs, 'genre' ); + } +} +``` + +Saving an existing book fires the hook as part of collecting the writable properties. + +```php +$book = $books->get( 42 ); +$book->genre_slugs = array( 'sci-fi', 'classics' ); +$books->save( $book ); // result: Book model — genres assigned, post row updated +``` + +At the WordPress layer, `save()` first collects the writable properties (your hook runs `wp_set_object_terms()` here), then calls `wp_update_post()` with the remaining data and meta. The built-in `Post` model uses this pattern for `$featured_image_id` (`persist_featured_image_id()` → `set_post_thumbnail()`). + +> [!WARNING] +> On a brand-new model, `persist_*` hooks fire *before* `wp_insert_post()` — `$this->id` is still `0`, so hooks that need the post row (like the one above, or the built-in featured-image hook) silently do nothing. Workaround: save once to get an ID, set the property, save again. See [Custom post types](custom-post-types.md). + +> [!NOTE] +> Properties marked `#[ReadOnlyProperty]` are skipped before the hook check, so a `persist_*` hook on a read-only property never runs. + +## Aliasing a property with `#[AliasOf]` + +`#[AliasOf]` makes a property a read-through alias of another property on the same model — useful for renaming a property while keeping the old name working. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$source_key` | `string` | — | Name of the property the alias reads from. | + +```php +get( 42 ); +echo $book->name; // result: Dune +``` + +The built-in `Menu` model uses this for its deprecated `$items` alias of `$children`. + +> [!NOTE] +> Aliasing is read-through only. Writing to the alias sets only the alias's own cached value — the original property is untouched — and the alias caches its own copy on the first read, so later changes to the original are invisible until `refresh()` or `unset()`. Aliases are never persisted by `save()`. + +## Read-only properties with `#[ReadOnlyProperty]` + +`#[ReadOnlyProperty]` is a marker attribute with no parameters and two effects: assigning to the property throws `ReadOnlyPropertyException`, and `save()` skips the property entirely. Stack it above a source attribute to expose a value without letting callers change it. + +```php +get( 42 ); +echo $book->legacy_sku; // result: BK-0042 +$book->legacy_sku = 'BK-9999'; // result: throws ReadOnlyPropertyException +``` + +The built-in models mark props like `Post::$comment_count`, `Post::$author`, and `Order::$line_items` this way. + +> [!NOTE] +> Any **non-empty** cached value arms the guard — whether it got there from a read or from a prior successful assignment. While the cache is empty (`''`, `0`, `false`, `null`, `[]`), assignment succeeds; once a read or a first write caches a non-empty value, the next assignment throws. Array access (`$book['legacy_sku'] = ...`) bypasses the check entirely; see the warning below. Read-only properties are safe from accidental persistence either way: `save()` never writes them. + +## WooCommerce getter/setter properties with `#[AccessorObject]` + +> [!IMPORTANT] +> Requires WooCommerce in practice. `#[AccessorObject]` calls getter/setter methods on the model's [source object](../concepts/architecture.md), so it needs a source with WC-style `get_*()`/`set_*()` methods — every shipped use targets WooCommerce CRUD objects (`WC_Product`, `WC_Abstract_Order`, `WC_Order_Item*`). On a plain `WP_Post` or `WP_Term` source it silently resolves to `null`. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$key` | `?string` | `null` | Overrides the property name when building method names (`get_{key}` / `set_{key}`). | +| `$getter` | `string` | `''` | Exact getter method name; overrides the naming convention. | +| `$setter` | `string` | `''` | Exact setter method name; overrides the naming convention. | + +Reads call `$getter` if given, else `get_{key}()`, else a method named exactly `{key}()`; writes fire **immediately on assignment**, mutating the in-memory WC object — missing methods fail silently with `null`. The built-in `Product` model (source object: `WC_Product`) maps its properties this way — bare `#[AccessorObject]` follows the naming convention, `key:` overrides it: + +| Property | Attribute | WC methods | +|---|---|---| +| `Product::$name` | `#[AccessorObject]` | `WC_Product::get_name()` / `set_name()` | +| `Product::$is_featured` | `#[AccessorObject( key: 'featured' )]` | `WC_Product::get_featured()` / `set_featured()` | + +Nothing reaches the database until the repository's `save()` calls the WC object's own `save()`. + +```php +use Wpify\Model\Product; + +$products = $manager->get_model_repository( Product::class ); +$product = $products->get( 123 ); +$product->name = 'Signed edition'; // WC_Product::set_name(), in memory only +$products->save( $product ); // result: Product model — WC_Product::save() wrote the change +``` + +See the [WooCommerce guide](woocommerce.md) for the full Product and Order workflow, including the create-then-save trap. + +## Serializing with `to_array()` + +`to_array()` converts a model to a plain `[ prop => value ]` array — pass an allow-list to control cost, and a `$recursive` list to convert related models too. + +| Argument | Type | Default | Description | +|---|---|---|---| +| `$props` | `array` | `array()` | Property names to include. Empty means **every** declared property. | +| `$recursive` | `array` | `array()` | Properties whose model values (or arrays of models) are converted to arrays as well. | + +An allow-list resolves only what you ask for. + +```php +$book = $books->get( 42 ); +$data = $book->to_array( array( 'id', 'title', 'isbn' ) ); +// result: [ 'id' => 42, 'title' => 'Dune', 'isbn' => '9780441172719' ] +``` + +Model-valued properties stay model objects unless listed in `$recursive`, which converts them with their own `to_array()`. + +```php +$data = $book->to_array( array( 'title', 'author' ), array( 'author' ) ); +// result: [ 'title' => 'Dune', 'author' => [ 'id' => 1, 'display_name' => 'admin', ... ] ] +``` + +> [!NOTE] +> Calling `to_array()` with no `$props` resolves **every** declared property, including relations — on a `Post` subclass that means author, parent, children, categories, and tags queries in one call. Use the allow-list for cheap serialization. + +## Array access and iteration + +Every model implements `ArrayAccess` and `IteratorAggregate`, so bracket syntax and `foreach` work — but each operation has different semantics than the arrow syntax. + +| Operation | Behavior | +|---|---| +| `$book['title']` | Lazy read like `$book->title`, but unknown keys return `null` instead of throwing `PropertyNotDefinedException`. | +| `$book['title'] = $value` | Writes the raw value straight into the property cache — see the warning below. | +| `isset( $book['title'] )` / `isset( $book->title )` | `true` when the property is declared — not whether it currently holds a value. | +| `unset( $book['title'] )` / `unset( $book->title )` | Clears the cached value only; the next read re-resolves from the source. | +| `foreach ( $book as $prop => $value )` | Iterates `to_array()` — fully resolves every property first. | + +Unsetting is the per-property version of `refresh()` — handy after something outside the model changed the data. + +```php +update_post_meta( $book->id, 'isbn', '9780593099322' ); +unset( $book->isbn ); +echo $book->isbn; // result: 9780593099322 — re-read via get_post_meta() +``` + +> [!WARNING] +> `$book['title'] = $value` bypasses everything: the read-only check, `set_{prop}()` hooks, type coercion, and the immediate meta/accessor write-through on Site and WooCommerce models. It is the intended escape hatch *inside* `set_{prop}()` hooks — avoid it everywhere else, or you can cache a wrongly-typed value or silently skip a write the model family expects. + +## Related + +- [Meta fields](meta-fields.md) — everything about `#[Meta]` storage and keys +- [Custom post types](custom-post-types.md) — the full `Book` model and repository walkthrough +- [Relations](relations.md) — relation attributes for linked models +- [WooCommerce](woocommerce.md) — Product and Order models in depth +- [Property resolution](../concepts/property-resolution.md) — the exact `__get`/`__set` pipeline +- [Persistence](../concepts/persistence.md) — what `save()` does per model family +- [Model reference](../reference/model.md) — the full `Model` API +- [Attributes reference](../reference/attributes.md) — all 17 attributes at a glance diff --git a/docs/guides/multisite.md b/docs/guides/multisite.md new file mode 100644 index 0000000..518ba50 --- /dev/null +++ b/docs/guides/multisite.md @@ -0,0 +1,237 @@ +# Working with sites in a multisite network + +After this page you can query, read, create, update, and delete the sites of a WordPress multisite network as `Site` models through the `SiteRepository`. + +> [!IMPORTANT] +> Requires WordPress multisite. On a single-site install, every `SiteRepository` method that touches the database — `get()`, `find()`, `find_all()`, `find_by_ids()`, `save()`, `delete()` — causes a PHP fatal error (`Call to undefined function get_site()` and friends), because WordPress only loads the site API when `is_multisite()` is true. There is no graceful `null`/`false` path. Only `model()`, `create()`, and repository registration are safe without multisite; guard everything else with `is_multisite()` yourself (see [Running on single site](#running-on-single-site)). + +**Prerequisites:** [Installation](../getting-started/installation.md), [Architecture](../concepts/architecture.md) + +## Getting the repository + +The Manager registers `SiteRepository` by default, so you only need to ask for it — no custom classes required to work with the built-in `Site` model. + +```php +use Wpify\Model\Manager; +use Wpify\Model\SiteRepository; + +$manager = new Manager(); +$sites = $manager->get_repository( SiteRepository::class ); +// result: a SiteRepository instance wired to the Manager +``` + +## Finding sites + +`find()` is a thin pass-through to `get_sites()` — every argument [`get_sites()`](https://developer.wordpress.org/reference/functions/get_sites/) accepts works unchanged, and each returned `WP_Site` is wrapped in a `Site` model. + +```php +$visible = $sites->find( array( 'public' => 1, 'archived' => 0 ) ); + +foreach ( $visible as $site ) { + echo $site->domain . $site->path . PHP_EOL; +} +// result: example.test/ +// shop.example.test/ +``` + +At the WordPress layer this runs one `get_sites( $args )` query against the `wp_blogs` table. + +| Method | Behavior | +| --- | --- | +| `find( array $args = array() )` | `get_sites( $args )` pass-through, each result wrapped in a `Site` model | +| `find_all( array $args = array() )` | Alias for `find()` — no extra defaults | +| `find_by_ids( array $ids )` | `find( array( 'site__in' => $ids ) )`; note there is no second `$args` parameter | + +## Getting one site + +`get()` accepts a `Site` model (returned as-is), a `WP_Site` object, or anything `get_site()` understands — typically a site ID. It returns `null` when no site matches. + +```php +$current = $sites->get( get_current_blog_id() ); + +echo $current->domain . $current->path; +// result: shop.example.test/ +``` + +At the WordPress layer this calls `get_site( $source )` and wraps the resulting `WP_Site`. + +## Reading site properties + +These properties resolve lazily from the wrapped `WP_Site` object. The full list, including everything below, is in the [Site model reference](../reference/models/site.md). + +| Property | Type | Source | Notes | +| --- | --- | --- | --- | +| `id` | `int` | `WP_Site->blog_id` | The site's own ID ("blog" is legacy naming) | +| `domain` | `string` | `WP_Site->domain` | | +| `path` | `string` | `WP_Site->path` | | +| `site_id` | `int` | `WP_Site->site_id` | The parent **network** ID, not this site's ID | +| `registered` | `string` | `WP_Site->registered` | `'0000-00-00 00:00:00'` until inserted | +| `last_updated` | `string` | `WP_Site->last_updated` | | +| `public` | `bool` | `WP_Site->public` | | +| `archived` | `bool` | `WP_Site->archived` | | +| `mature` | `bool` | `WP_Site->mature` | No core handling; kept for custom implementations | +| `spam` | `bool` | `WP_Site->spam` | | +| `deleted` | `bool` | `WP_Site->deleted` | | +| `lang_id` | `int` | `WP_Site->lang_id` | | + +> [!NOTE] +> `$site->site_id` is **not** the site's ID — it is the ID of the network the site belongs to, mirroring the legacy `WP_Site->site_id` naming. The site's own ID is `$site->id`. + +## Site meta + +The `Site` model also declares `#[Meta]` properties that read from site meta (the `wp_blogmeta` table) via `get_site_meta()`. Core does not maintain these keys for individual sites — they are conventions the model exposes, populated only if your code (or a plugin) writes them. + +| Property | Type | Source | Notes | +| --- | --- | --- | --- | +| `site_name` | `string` | site meta `site_name` | | +| `admin_email` | `string` | site meta `admin_email` | | +| `admin_user_id` | `int` | site meta `admin_user_id` | | +| `admin_user` | `?User` | relation via `admin_user_id` | Read-only `#[ManyToOneRelation]`, loads through `UserRepository` | +| `site_url` | `string` | site meta `siteurl` | | +| `site_admins` | `array` | site meta `site_admins` | | +| `is_main_site` | `bool` | site meta `main_site` | | +| `blog_count` | `int` | site meta `blog_count` | | +| `user_count` | `int` | site meta `user_count` | | + +> [!NOTE] +> Site meta writes through **immediately**. Unlike every other model family (post, term, user, comment meta all wait for `save()`), assigning a `#[Meta]` property on a `Site` calls `update_site_meta()` right away — `$site->admin_email = 'admin@example.test';` hits the database before you ever call `save()`. `save()` then writes the same values again. On an unsaved site (`id === 0`) the immediate write is a no-op at the database level; the values are persisted after the insert instead. + +> [!NOTE] +> Site meta requires multisite **and** the `wp_blogmeta` table (WordPress >= 5.1 installs, or upgraded networks — checked via `is_site_meta_supported()`). Where unsupported, every non-nullable `#[Meta]` property reads as its type's empty value (`''`, `0`, `false`, `array()`) — which for every built-in `Site` property happens to equal its declared default, but a custom property such as `public string $branch_city = 'Downtown';` reads as `''`, not `'Downtown'`. Only nullable properties fall back to their declared default. Assignments are kept in memory only. + +### Reading the site admin + +`admin_user` is a read-only relation that loads a full `User` model from the `admin_user_id` site meta through `UserRepository` — handy when your network provisioning writes that key. + +```php +$admin = $current->admin_user; + +echo $admin ? $admin->display_name : 'unknown'; +// result: Jane Admin (or "unknown" when admin_user_id meta is empty) +``` + +### Custom site meta + +To store your own per-site settings, subclass `Site` and add `#[Meta]` properties — always pin the meta key with `meta_key:` so a later property rename cannot orphan your data. Here a bookstore chain tracks which city each branch site serves. + +```php +get_repository( BranchSiteRepository::class ); + +$branch = $branches->get( 2 ); +$branch->branch_city = 'Prague'; +// result: update_site_meta( 2, 'branch_city', 'Prague' ) has already run +``` + +## Creating a site + +`create()` builds an in-memory model and never touches the database; persist it with `save()`. How the persistable properties are collected is covered in [Persistence](../concepts/persistence.md). + +```php +$site = $sites->create( array( + 'domain' => 'shop.example.test', + 'path' => '/', +) ); + +$sites->save( $site ); +echo $site->id; +// result: 3 (populated by the post-save refresh from get_site()) +``` + +At the WordPress layer, `save()` on a new site collects the writable properties, drops `blog_id`, renames `site_id` to `network_id` (the shape `wp_insert_site()` expects), calls `wp_insert_site( $data )`, writes each `#[Meta]` property via `update_site_meta()` (when site meta is supported), and refreshes the model from `get_site()`. + +## Updating a site + +Assign properties and call `save()` — a model with `id > 0` is updated in place. + +```php +$site->public = false; +$site->archived = true; + +$sites->save( $site ); +// result: wp_update_site( $site->id, array( ... ) ) ran; model refreshed +``` + +At the WordPress layer this calls `wp_update_site( $site->id, $data )` followed by the same `update_site_meta()` loop as on insert. + +## Deleting a site + +`delete()` calls `wp_delete_site( $model->id )` and returns `false` when WordPress reports a `WP_Error`. + +```php +$deleted = $sites->delete( $site ); +// result: true (wp_delete_site() succeeded) +``` + +> [!WARNING] +> Site deletion is always permanent — there is no trash for sites, and the `$force_delete` parameter on `SiteRepository::delete()` is unused. Cleanup of the site's tables and uploads is performed by WordPress core's own hooks on `wp_delete_site()`. + +## Handling save failures + +When `wp_insert_site()` / `wp_update_site()` fails, `save()` throws `CouldNotSaveModelException` with the underlying `WP_Error` attached — retrieve it via `get_wp_error()` (only the Term and Site families attach it). + +```php +use Wpify\Model\Exceptions\CouldNotSaveModelException; + +try { + $sites->save( $sites->create( array( 'domain' => '' ) ) ); +} catch ( CouldNotSaveModelException $e ) { + echo $e->get_wp_error()->get_error_code(); + // result: site_empty_domain +} +``` + +## Running on single site + +If your plugin can run on both single-site and multisite installs, gate all site operations behind `is_multisite()` — the repository does not guard for you, and the fatal errors described in the callout at the top of this page are not catchable as library exceptions. + +```php +if ( is_multisite() ) { + $current = $sites->get( get_current_blog_id() ); +} +// result: on single site the block is skipped instead of fataling +``` + +Safe without multisite: `new Manager()` (which registers `SiteRepository` unconditionally), `model()`, and `create()`. A `Site` model built with `create()` on single site is harmless — its `#[Meta]` properties read as their type's empty value (which for the built-in properties equals the declared default; see the callout in [Site meta](#site-meta)) and assignments stay in memory only. + +## Related + +- [Site model reference](../reference/models/site.md) — full property and method tables +- [User model reference](../reference/models/user.md) — the model behind `$site->admin_user` +- [Meta fields](meta-fields.md) — everything about `#[Meta]`, per-family write timing +- [Persistence](../concepts/persistence.md) — what `create()`, `save()`, and `delete()` do per family +- [Repository reference](../reference/repository.md) — the shared repository contract +- [Troubleshooting](troubleshooting.md) — error messages and fixes, including the single-site fatals diff --git a/docs/guides/querying.md b/docs/guides/querying.md new file mode 100644 index 0000000..f90d6f9 --- /dev/null +++ b/docs/guides/querying.md @@ -0,0 +1,220 @@ +# Querying models + +After this page you can fetch any model — one by ID, slug, or URL, many by arbitrary query arguments, or a paginated batch — from every repository family the library ships. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Architecture](../concepts/architecture.md). The examples reuse the bookstore domain: `Book`/`BookRepository` from the [custom post types guide](custom-post-types.md) and `Genre`/`GenreRepository` from the [custom taxonomies guide](custom-taxonomies.md). Every call shown works identically on the built-in `PostRepository`, `CategoryRepository`, and friends. + +All snippets assume this setup — one shared Manager with the custom repositories registered. + +```php +use Wpify\Model\Manager; +use Wpify\Model\UserRepository; + +$manager = new Manager( new BookRepository(), new GenreRepository() ); +$books = $manager->get_repository( BookRepository::class ); +$genres = $manager->get_repository( GenreRepository::class ); +$users = $manager->get_repository( UserRepository::class ); +``` + +## Getting one model with `get()` + +Every repository has `get( mixed $source ): ?ModelInterface`. It accepts an ID, the native WordPress object, a model instance (returned unchanged — safe to call idempotently), and per family one or more string lookups. It returns `null` when nothing matches — it never throws for a missing record. + +```php +$book = $books->get( 42 ); // by ID +$book = $books->get( 'dune' ); // by slug +$book = $books->get( 'https://example.com/book/dune/' ); // by URL +// result: ?Book — null when nothing matches +``` + +At the WordPress layer, a numeric input runs `get_post()`, a string tries a slug lookup via `get_posts()` first and then `url_to_postid()`. + +What `get()` accepts per family: + +| Repository | ID / native object | String input semantics | +|---|---|---| +| `PostRepository` (+ `PageRepository`, `AttachmentRepository`, custom CPT repositories) | ID, `WP_Post` | slug (within the repository's post types), then URL | +| `TermRepository` (+ `CategoryRepository`, `PostTagRepository`, custom taxonomy repositories) | ID, `WP_Term` | slug, then term name | +| `UserRepository` | ID, `WP_User` | login, then email, then nicename | +| `CommentRepository` | ID, `WP_Comment` | — (`get_comment()` handles IDs and objects only) | +| `SiteRepository` | ID, `WP_Site` | — | +| `MenuRepository` | ID, `WP_Term` | registered theme location key first, then slug or name — see the [menus guide](menus.md) | +| `ProductRepository` | ID, `WC_Product` | SKU, then product slug | +| `OrderRepository` | ID, `WC_Order` | order key | +| `CustomTableRepository` subclasses | primary key value, raw row object | — see the [custom tables guide](custom-tables.md) | + +> [!IMPORTANT] +> `ProductRepository` and `OrderRepository` require WooCommerce to be active, and `SiteRepository` requires multisite — their query methods call `wc_get_product()`/`wc_get_orders()`/`get_sites()`, which are undefined otherwise and fatal. See the [WooCommerce](woocommerce.md) and [multisite](multisite.md) guides. + +Numeric input is tried as an ID first; the string lookups (slug, login, SKU, …) run only as a fallback when no record with that ID exists. So `get( '123' )` does find a post slugged `'123'`, a user with login `'123'`, or a product with SKU `'123'` — but an existing record with ID 123 always shadows it. Here is the same call on the user family, which resolves strings differently. + +```php +$user = $users->get( 'daniel@example.com' ); +// result: ?User — tried as login first, then email, then nicename +``` + +> [!NOTE] +> `TermRepository::get( 0 )` does not return `null`: `get_term( 0 )` returns a `WP_Error`, which the repository wraps as the model's source, so you get a `Term` model whose properties all resolve to defaults (`id === 0`). Guard IDs before calling `get()` on term repositories. + +## Filtering with `find()` + +Every repository's `find( array $args = array() )` is a thin wrapper: your arguments are passed through to the underlying WordPress query API unchanged, with only the defaults below merged in. Anything `WP_Query`, `get_terms()`, `get_users()`, `get_comments()`, or `get_sites()` understands works here verbatim. + +| Family | Args passed to | Defaults merged by `find()` | +|---|---|---| +| Post family (`PostRepository` + subclasses) | `WP_Query` | `post_type` → the repository's `post_types()`, `post_status => 'any'`, `posts_per_page => -1` | +| Term family (`TermRepository` + subclasses) | `get_terms()` (`WP_Term_Query`) | `taxonomy` → the repository's `taxonomy()` | +| `UserRepository` | `get_users()` (`WP_User_Query`) | none | +| `CommentRepository` | `get_comments()` (`WP_Comment_Query`) | none | +| `SiteRepository` | `get_sites()` (`WP_Site_Query`) | none | +| `ProductRepository` | `wc_get_products()` | none | +| `OrderRepository` | `wc_get_orders()` | none | +| `CustomTableRepository` subclasses | its own SQL builder with an array where-syntax | see the [custom tables guide](custom-tables.md) | + +A post-family `find()` runs a real `WP_Query` loop (`have_posts()`/`the_post()`, followed by `wp_reset_postdata()`) and maps each `WP_Post` to a model. + +```php +$recent = $books->find( array( + 'posts_per_page' => 10, + 'orderby' => 'date', + 'order' => 'DESC', +) ); +// result: Book[] — the 10 newest books, drafts included +``` + +> [!WARNING] +> Post-family `find()` defaults to `post_status => 'any'` and `posts_per_page => -1`. A bare `find()` returns **every** book — drafts, pending, private, and scheduled included — in one unbounded query. For public-facing listings use `find_published()` or pass `post_status => 'publish'` explicitly, and always cap `posts_per_page`. + +Term-family `find()` calls `get_terms()`, which keeps WordPress's own `hide_empty => true` default. + +```php +$all_genres = $genres->find( array( 'hide_empty' => false ) ); +// result: Genre[] — including genres no book is assigned to +``` + +> [!NOTE] +> Term queries hide empty terms by default: a bare `find()` on a term repository silently omits every term with no assigned posts. Pass `hide_empty => false` (or call `find_all()`, which does it for you) to get them all. The same default hides empty terms in `find_by_ids()`. + +The families without changed defaults behave exactly like the WordPress function they wrap. For example, user queries take `WP_User_Query` arguments. + +```php +$editors = $users->find( array( 'role' => 'editor' ) ); +// result: User[] — via get_users( array( 'role' => 'editor' ) ) +``` + +## Convenience finders + +Beyond `find()`, each family ships named finders for the common cases. Only the methods listed below exist — they differ per family. + +Post family (`PostRepository`, `PageRepository`, `AttachmentRepository`, and your CPT repositories): + +| Method | Behavior | +|---|---| +| `find_all( array $args = array() )` | `find()` with `posts_per_page => -1`, `post_status => 'any'` — **includes drafts** | +| `find_published( array $args = array() )` | `find()` with `post_status => 'publish'`, `posts_per_page => -1` | +| `find_paginated( array $args = array() )` | Paged `WP_Query`; see [Pagination](#pagination) | +| `find_without_pagination( array $args = array() )` | Same defaults as `find()` but via `get_posts()` — does **not** feed `get_pagination()` | +| `find_by_ids( array $ids, array $args = array() )` | `find()` with `post__in => $ids`; results come back in `WP_Query` default order (date), not ID order, unless you pass `orderby => 'post__in'` | +| `find_all_by_term( ModelInterface $model )` | Posts assigned to the given **term model**, via a `tax_query` on `term_id` | +| `find_child_posts_of( ModelInterface $model )` | `find()` with `post_parent` set to the model's ID | + +Term family (`TermRepository`, `CategoryRepository`, `PostTagRepository`, `ProductCatRepository`, and your taxonomy repositories): + +| Method | Behavior | +|---|---| +| `find_all( array $args = array() )` | `find()` with `hide_empty => false` — includes empty terms | +| `find_not_empty( array $args = array() )` | `find()` with `hide_empty => true` | +| `find_children_of( int $parent_id = 0, array $args = array() )` | `find()` with `child_of => $parent_id` — recursive, so grandchildren are included; returns `array()` without querying when `$parent_id <= 0` | +| `find_terms_of_post( int $post_id )` | `get_the_terms( $post_id, taxonomy )` mapped to models | +| `find_child_terms_of( ModelInterface $model )` | Descendants of the given term model, with `hide_empty => false` | +| `find_by_ids( array $ids, array $args = array() )` | `find()` with `include => $ids` — subject to the `hide_empty` default | + +Other families: + +| Repository | Finders | +|---|---| +| `UserRepository` | `find_all( $args )` (alias of `find()`), `find_by_ids( array $ids )` — note: no second `$args` parameter | +| `CommentRepository` | `find_all( $args )` (alias), `find_by_post_id( int $post_id )`, `find_by_ids( array $ids, array $args = array() )` | +| `SiteRepository` | `find_all( $args )` (alias), `find_by_ids( array $ids )` — no second `$args` parameter | +| `ProductRepository` | `find_all( $args )` (adds `limit => -1`), `find_by_ids( array $ids, array $args = array() )` (also adds `limit => -1`), `find_all_by_term( $product_cat_model )` | +| `OrderRepository` | `find_all( $args )` (adds `limit => -1`), `find_by_ids( array $ids )` — fetches per ID, so ID order is preserved | +| `CustomTableRepository` | `find_all( $args )` (alias of `find()`), `find_by_ids( array $ids )` — see the [custom tables guide](custom-tables.md) | + +> [!NOTE] +> The WooCommerce order-item repositories (`OrderItemRepository` and its line/fee/shipping subclasses) deliberately return empty arrays from all `find*` methods — get items through an `Order` model instead. See the [WooCommerce guide](woocommerce.md). + +The public-listing counterpart to the permissive `find_all()` is `find_published()`. + +```php +$published = $books->find_published( array( 'posts_per_page' => 20 ) ); +// result: Book[] — post_status 'publish' only +``` + +And the term-side mirror image: `find_all()` is the permissive one there. + +```php +$every_genre = $genres->find_all(); +// result: Genre[] — empty genres included (get_terms with hide_empty => false) +``` + +## Pagination + +Pagination exists on the post family only. `find_paginated()` runs a paged `WP_Query` (defaulting `paged` to the `paged` query var, or `1`) and returns the items together with the pagination state and rendered links. + +```php +$result = $books->find_paginated( array( 'posts_per_page' => 12 ) ); + +foreach ( $result['items'] as $book ) { + echo $book->title; +} +echo $result['paginate_link']; +// result: array{ items: Book[], pagination: array, paginate_link: array|string|null } +``` + +> [!NOTE] +> The links key is the singular **`paginate_link`** — not `paginate_links`. It holds the output of WordPress's `paginate_links()`. + +After any `find()` or `find_paginated()` call, the repository keeps the `WP_Query` instance, and `get_pagination()` reads the totals from it. + +```php +$books->find( array( 'posts_per_page' => 12, 'paged' => 2 ) ); +$pagination = $books->get_pagination(); +// result: array( 'found_posts' => 138, 'current_page' => 2, 'total_pages' => 12, 'per_page' => 12 ) +``` + +> [!WARNING] +> Calling `get_pagination()` or `get_paginate_links()` before any `find()`/`find_paginated()` on that repository instance throws a PHP `Error` (typed property … must not be accessed before initialization) — not a library exception — and is fatal unless you catch `\Error`. Call a finder first. `find_without_pagination()` does not count — it uses `get_posts()` and never stores a query. + +`get_paginate_links( array $args = array() )` wraps WordPress's `paginate_links()`, defaulting `total` and `current` from `get_pagination()`; pass `type => 'array'` to get individual link strings. + +```php +$links = $books->get_paginate_links( array( 'type' => 'array' ) ); +// result: array of pagination link HTML strings +``` + +## Counting + +There is no dedicated `count()` method. On the post family, run a cheap limited `find()` and read `found_posts` — `WP_Query` counts all matching rows regardless of the page size. + +```php +$books->find( array( 'posts_per_page' => 1 ) ); +$total = $books->get_pagination()['found_posts']; +// result: 138 — all matching books, not just the one fetched +``` + +For every other family, count the result of a finder in PHP. + +```php +$genre_count = count( $genres->find_all() ); +// result: 12 +``` + +## Related + +- [Custom post types](custom-post-types.md) — the `Book` model and repository used above +- [Custom taxonomies](custom-taxonomies.md) — the `Genre` model and repository +- [Custom tables](custom-tables.md) — the array where-syntax for table queries +- [Relations](relations.md) — querying through model relations instead of finders +- [WooCommerce](woocommerce.md), [Menus](menus.md), [Multisite](multisite.md) — family-specific querying details +- [Repository reference](../reference/repository.md) — the shared repository contract +- Family references: [Post](../reference/models/post.md), [Term](../reference/models/term.md), [User](../reference/models/user.md), [Comment](../reference/models/comment.md), [Site](../reference/models/site.md), [Product](../reference/models/product.md), [Order](../reference/models/order.md) diff --git a/docs/guides/relations.md b/docs/guides/relations.md new file mode 100644 index 0000000..8611ae0 --- /dev/null +++ b/docs/guides/relations.md @@ -0,0 +1,448 @@ +# Working with relations + +After this page you can link models together — book to genres, genre to books, parent to children, order to items — using relation attributes, and you'll know exactly which of those links persist when you save. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Custom post types](custom-post-types.md), [Custom taxonomies](custom-taxonomies.md), [Property resolution](../concepts/property-resolution.md) + +## How relations work + +A relation is a source attribute placed on a model property: when you first read the property, the attribute runs a query through the related model's repository, and the result is cached on the model instance. Models hold the data, repositories talk to WordPress, the Manager wires them together — relation attributes are just properties whose source happens to be another repository. + +| Attribute | Resolves to | Backed by | Persists on save? | +|---|---|---|---| +| `ManyToOneRelation` | one model, loaded from an id property | target repository `get()` | No | +| `IdsRelation` | array of models, loaded from an id-array property | target repository `find_by_ids()` | No | +| `PostTermsRelation` | all terms of one taxonomy assigned to a post | `get_the_terms()` | **Yes** — via `PostRepository::save()` only | +| `TermPostsRelation` | all posts assigned to a term | `WP_Query` with `tax_query` | No | +| `PostTermRelation` | the first term of one taxonomy assigned to a post | `get_the_terms()` | **Yes** — via `PostRepository::save()` only | +| `ChildPostsRelation` | direct child posts | `WP_Query` on `post_parent` | No | +| `TopLevelPostParentRelation` | the top-most ancestor post | `get_ancestors()` | No | +| `ChildTermsRelation` | descendant terms | `get_terms()` with `child_of` | No | +| `TopLevelTermParentRelation` | the top-most ancestor term | `get_ancestors()` | No | +| `MenuItemsRelation` | nested tree of nav menu items | `wp_get_nav_menu_items()` | No | +| `OrderItemsRelation` | WooCommerce order items of one type | `WC_Abstract_Order::get_items()` | No | + +> [!WARNING] +> Only `PostTermRelation` and `PostTermsRelation` write anything back, and only when the post is saved through `PostRepository::save()` (or a subclass like your custom post repository). Every other relation is a read-only view — assigning to it changes the cached value in memory and nothing else, and relations additionally marked `#[ReadOnlyProperty]` (`Post::$author`, `Post::$featured_image`, the `Order` item relations) throw `ReadOnlyPropertyException` once a non-empty value has been resolved. To change what a read-only relation resolves to, set the underlying id property (`$book->sequel_id`, not `$book->sequel`) and save. + +> [!NOTE] +> Relation results are cached per model instance: the query runs once, on first read. If terms, children, or related posts change in the database afterwards, the model keeps returning the old value until you call `$model->refresh()` or `unset( $model->prop )`. See [Property resolution](../concepts/property-resolution.md). + +## The bookstore models + +The examples on this page use a bookstore plugin: a `Book` custom post type and a `Genre` custom taxonomy. Here is the complete `Book` model with every book-side relation used below, plus its repository. + +```php + true, /* … */ ) )` and `register_taxonomy( 'genre', 'book', array( 'hierarchical' => true, /* … */ ) )` as usual (hierarchical, so the parent/child examples below work). + +## ManyToOneRelation + +`ManyToOneRelation` resolves a single related model from a foreign-key property on the same model — the classic "belongs to" link. The attribute takes the name of the id property; the **declared PHP type of the annotated property** decides which repository loads the model. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$source_key` | `string` | — | Name of the property on the same model that holds the related model's id. | + +`Book::$sequel` (declared above) resolves the book stored in the `_sequel_id` meta field. + +```php +$books = $manager->get_repository( BookRepository::class ); +$book = $books->get( 42 ); + +echo $book->sequel?->title; +// result: "The Two Towers" +``` + +Reading `$book->sequel` calls `BookRepository::get( $book->sequel_id )`, which fetches the post via `get_post()`. An empty id (`0` or `''`) short-circuits to `null` with no query. + +The built-in models use this attribute heavily — your `Book` inherits `$author` (`?User`), `$parent` (`?Post`), and `$featured_image` (`?Attachment`) from `Post`, and `Genre` inherits `$parent` (`?Term`) from `Term`. + +> [!NOTE] +> The property's type declaration is load-bearing. It must be a single, registered model class (`?Book`, `?User`, …) — an untyped property throws `RepositoryNotFoundException` on first read, and a union type causes a fatal error. This is the same mechanism as the zero-config baseline: type coercion resolves *any* property typed with a registered model class through that class's repository, so `ManyToOneRelation` is simply the explicit "id property → model" form of it. + +To change the relation, set the id property and save — the relation itself is a read-only view. + +```php +$book->sequel_id = 77; +$books->save( $book ); +// result: _sequel_id meta is 77; $book->sequel now resolves book 77 +``` + +## IdsRelation + +`IdsRelation` is the many-model sibling of `ManyToOneRelation`: it loads an array of models from a property that holds an array of ids. Unlike `ManyToOneRelation`, the target model class is passed explicitly. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$source_key` | `string` | — | Property on the same model holding the array of ids. | +| `$target_entity` | `string` (class-string) | — | Model class to load the ids as. | +| `$args` | `array` | `array()` | Extra query args merged into the `find_by_ids()` lookup. | + +`Book::$related_books` (declared above) resolves the ids stored in the `_related_ids` meta field. + +```php +$book->related_ids = array( 7, 9 ); +$books->save( $book ); + +$fresh = $books->get( $book->id ); +echo count( $fresh->related_books ); +// result: 2 +``` + +Reading `$fresh->related_books` calls `BookRepository::find_by_ids()`, which runs a `WP_Query` with `post__in`. + +> [!NOTE] +> Results come back in `WP_Query`'s default order (date), not the order of your ids — pass `args: array( 'orderby' => 'post__in' )` to preserve it. The `$args` parameter only reaches repositories whose `find_by_ids( array $ids, array $args = array() )` accepts it (Post, Term, Comment, and Product families); the User, Site, Order, and custom-table repositories take only `$ids` and silently ignore it. + +## PostTermsRelation + +`PostTermsRelation` links a post to **all** its terms in one taxonomy — and it is one of the two relations that persist. Reading resolves the current term set; assigning an array of term models and saving the post writes the set back. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$target_entity` | `string` (class-string) | — | Term-side model class (`Genre::class`, `Category::class`, …). | + +Reading `Book::$genres` (declared above) fetches the assigned genre terms. + +```php +$book = $books->get( 42 ); + +foreach ( $book->genres as $genre ) { + echo $genre->name; +} +// result: "Fantasy", "Adventure" +``` + +Under the hood this calls `GenreRepository::find_terms_of_post( $book->id )`, a wrapper around `get_the_terms()`. + +To change the assignment, set the full array of term models and save the book. + +```php +$genres = $manager->get_repository( GenreRepository::class ); + +$book->genres = array( $genres->get( 'fantasy' ), $genres->get( 'adventure' ) ); +$books->save( $book ); +// result: the book now has exactly these two genre terms +``` + +On save, `PostRepository::save()` calls the relation's `persist()`, which runs `wp_set_post_terms()` with `$append = false` — the assigned set **replaces** the taxonomy's terms. To add a genre without dropping the others, merge with the current set first: `$book->genres = array_merge( $book->genres, array( $new_genre ) )`. + +The built-in `Post::$categories` and `Post::$tags` (inherited by `Book`) work exactly the same way. + +> [!NOTE] +> The relation re-persists on *every* save, even if you never touched it. If the property was never read, the save loop resolves the current terms at save time and writes the same set back — harmless. But once the property has been resolved, saving re-assigns the cached set, so term changes made in the database after that first read get overwritten. + +> [!WARNING] +> Persistence only runs in `PostRepository::save()` and its subclasses. In particular, assigning to `Product::$categories` (a `PostTermsRelation` on the WooCommerce product model) and saving through `ProductRepository` silently does **not** persist the categories — see the [WooCommerce guide](woocommerce.md). + +## TermPostsRelation + +`TermPostsRelation` is the inverse of `PostTermsRelation`: from a term model, it resolves every post assigned to that term. It is a read-only view. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$target_entity` | `string` (class-string) | — | Post-side model class (`Book::class`, `Post::class`, `Product::class`, …). | + +Reading `Genre::$books` (declared above) fetches all books in the genre. + +```php +$fantasy = $manager->get_repository( GenreRepository::class )->get( 'fantasy' ); + +foreach ( $fantasy->books as $book ) { + echo $book->title; +} +// result: "The Hobbit", "A Wizard of Earthsea" +``` + +Under the hood this calls `BookRepository::find_all_by_term( $fantasy )`, a `WP_Query` with a `tax_query` on the term id. + +The built-in `Category::$posts`, `PostTag::$posts`, and `ProductCat::$products` use this attribute. + +> [!NOTE] +> The query runs with `post_status => 'any'` and no pagination — on a large site a popular genre resolves *every* book, drafts included, in one query. For paginated or filtered listings, call `find()` on the post repository yourself instead (see [Querying models](querying.md)). + +To attach a book to a genre, work from the post side: assign `$book->genres` and save the book — saving a term never touches its posts. + +## PostTermRelation + +`PostTermRelation` is the single-term variant of `PostTermsRelation`: use it when each post should have exactly one term of a taxonomy — a primary genre, for example. Like its plural sibling, it persists via `PostRepository::save()`. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$target_entity` | `string` (class-string) | — | Term-side model class. | + +If each book had exactly one genre, you would declare `Book` with this property *instead of* the `$genres` property. + +```php +use Wpify\Model\Attributes\PostTermRelation; + +// In Book, replacing the $genres property: +#[PostTermRelation( Genre::class )] +public ?Genre $genre = null; +``` + +Assign a term model and save the post to persist it. + +```php +$fantasy = $manager->get_repository( GenreRepository::class )->get( 'fantasy' ); + +$book->genre = $fantasy; +$books->save( $book ); + +echo $books->get( $book->id )->genre?->name; +// result: "Fantasy" +``` + +On save this calls `wp_set_post_terms()` with `$append = false`, so the single assigned term replaces the taxonomy's entire term set for that post. No shipped model uses this attribute — it is for custom models like `Book`. + +> [!WARNING] +> If the post has more than one term of the taxonomy, reading the property silently returns whichever term `get_the_terms()` lists first — there is no ordering guarantee and no error. The other terms stay invisible, and the next save replaces them all with the one visible term. + +> [!WARNING] +> Never declare a `PostTermRelation` and a `PostTermsRelation` for the same taxonomy on one model. Both persist on every save with `$append = false`, so whichever property is declared last wins and overwrites the other's assignment. + +## ChildPostsRelation + +`ChildPostsRelation` resolves the direct children of a hierarchical post — every post whose `post_parent` is this model's id. It takes no parameters. Your `Book` model already inherits it from `Post`: + +```php +// From Wpify\Model\Post — inherited by Book +/** @var Post[] */ +#[ChildPostsRelation] +public array $children = array(); +``` + +With the `book` post type registered as hierarchical, a boxed set resolves its volumes. + +```php +$boxed_set = $books->get( 'lord-of-the-rings' ); + +foreach ( $boxed_set->children as $volume ) { + echo $volume->title; +} +// result: "The Fellowship of the Ring", "The Two Towers", "The Return of the King" +``` + +Under the hood this calls `BookRepository::find_child_posts_of( $boxed_set )` — a `WP_Query` with `post_parent => $boxed_set->id`. + +> [!NOTE] +> The repository is looked up by the model's **own** class, and it must implement `find_child_posts_of()`. `BookRepository` inherits it from `PostRepository`, but a fully custom repository without that method throws `RepositoryMethodNotImplementedException` on first read. Only direct children are returned (grandchildren are not) — the term-side sibling below behaves differently. + +## TopLevelPostParentRelation + +`TopLevelPostParentRelation` walks up the post hierarchy and resolves the top-most ancestor. It takes no parameters, and `Book` inherits it from `Post` as `$top_parent`: + +```php +// From Wpify\Model\Post — inherited by Book +#[TopLevelPostParentRelation] +public ?Post $top_parent = null; +``` + +From any volume deep in a series, jump straight to the root. + +```php +$volume = $books->get( 'the-two-towers' ); + +echo $volume->top_parent?->title; +// result: "The Lord of the Rings" +``` + +Under the hood this calls `get_ancestors( $volume->id, 'book', 'post_type' )` and loads the last ancestor through the repository. + +> [!NOTE] +> A top-level post resolves to `null`, not to itself. The relation also returns `null` whenever the model's repository handles anything other than exactly one post type — a custom repository spanning several post types silently yields `null` here. + +## ChildTermsRelation + +`ChildTermsRelation` is the term-side child relation: it resolves the children of a hierarchical term. It takes no parameters, and `Genre` inherits it from `Term` as `$children`: + +```php +// From Wpify\Model\Term — inherited by Genre +/** @var Term[] */ +#[ChildTermsRelation] +public array $children = array(); +``` + +A parent genre resolves its sub-genres. + +```php +$genres = $manager->get_repository( GenreRepository::class ); +$fiction = $genres->get( 'fiction' ); + +foreach ( $fiction->children as $sub_genre ) { + echo $sub_genre->name; +} +// result: "Fantasy", "Science fiction", "Sword and sorcery" +``` + +Under the hood this calls `GenreRepository::find_child_terms_of( $fiction )` — `get_terms()` with `child_of => $fiction->id`, `hierarchical => true`, and `hide_empty => false`. + +> [!NOTE] +> Because it queries with `child_of`, the term-side `$children` contains **all descendants** — children, grandchildren, and deeper (`"Sword and sorcery"` above is a child of `"Fantasy"`). The post-side `ChildPostsRelation` returns direct children only. Empty terms are included (`hide_empty => false`), unlike a bare term `find()`. + +## TopLevelTermParentRelation + +`TopLevelTermParentRelation` mirrors `TopLevelPostParentRelation` for terms: it resolves the top-most ancestor term. No parameters; `Genre` inherits it from `Term` as `$top_parent`: + +```php +// From Wpify\Model\Term — inherited by Genre +#[TopLevelTermParentRelation] +public ?Term $top_parent = null; +``` + +From a deeply nested sub-genre, jump to the root genre. + +```php +$sword = $genres->get( 'sword-and-sorcery' ); + +echo $sword->top_parent?->name; +// result: "Fiction" +``` + +Under the hood this calls `get_ancestors( $sword->id, 'genre', 'taxonomy' )` and loads the last ancestor through the repository. As on the post side, a top-level term resolves to `null`, not itself. + +## MenuItemsRelation + +`MenuItemsRelation` resolves a nav menu's items as a nested tree of `MenuItem` models — each item's own `children` property holds its sub-items. The built-in `Menu::$children` uses it; you rarely declare it yourself. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$target_entity` | `string` (class-string) | `MenuItem::class` | Model class each menu item is wrapped in. | + +Fetch a menu and walk the tree. + +```php +use Wpify\Model\MenuRepository; + +$menu = $manager->get_repository( MenuRepository::class )->get( 'primary' ); + +foreach ( $menu->children as $item ) { + echo $item->title; +} +// result: "Home", "Books", "About" +``` + +Under the hood this calls `wp_get_nav_menu_items( $menu->id )` and sorts the flat item list into a tree by `menu_item_parent`. The relation is read-only. + +> [!NOTE] +> Only read `$menu->children` on menus fetched through `MenuRepository` — for a nonexistent menu id, `wp_get_nav_menu_items()` returns `false`, which the relation iterates without a check: PHP emits a warning and the relation returns an empty array. `MenuRepository::get()` returns `null` for missing menus, so a null-check after `get()` keeps you safe. See the [Menus guide](menus.md) for rendering patterns. + +## OrderItemsRelation + +> [!IMPORTANT] +> Requires WooCommerce. The `Order` and `OrderItem*` models fatal without it — see the [WooCommerce guide](woocommerce.md). + +`OrderItemsRelation` resolves a WooCommerce order's items of one type as models. The built-in `Order` model declares all three variants — `$line_items`, `$shipping_items` (`#[OrderItemsRelation( 'shipping' )]`), and `$fee_items` (`#[OrderItemsRelation( 'fee' )]`), each also marked `#[ReadOnlyProperty]`. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$order_item_type` | `string` | `'line_item'` | One of `'line_item'` (→ `OrderItemLine`), `'shipping'` (→ `OrderItemShipping`), `'fee'` (→ `OrderItemFee`). Any other value throws an `UnhandledMatchError`. | + +Read a bookstore order's line items. + +```php +use Wpify\Model\OrderRepository; + +$order = $manager->get_repository( OrderRepository::class )->get( 456 ); + +foreach ( $order->line_items as $item ) { + echo $item->name; +} +// result: "The Hobbit (hardcover)", "A Wizard of Earthsea (paperback)" +``` + +Under the hood this calls `WC_Abstract_Order::get_items( 'line_item' )` on the order's source object and wraps each item via the matching repository. The relation is read-only — add or change items through the WooCommerce order object itself (`$order->get_wc_order()`). + +> [!NOTE] +> This relation is the only way to list an order's items: the `OrderItem*` repositories' `find()`/`find_all()` methods return empty arrays by design. + +## Related + +- [Custom post types](custom-post-types.md) — the full `Book` model walkthrough +- [Custom taxonomies](custom-taxonomies.md) — the full `Genre` model walkthrough +- [Meta fields](meta-fields.md) — the `#[Meta]` properties backing the id-based relations +- [Querying models](querying.md) — paginated and filtered alternatives to relation reads +- [Model properties](model-properties.md) — accessors, read-only props, `to_array()` +- [Persistence](../concepts/persistence.md) — what `save()` does per model family +- [Attributes reference](../reference/attributes.md) — every attribute's formal parameter list +- [Repository reference](../reference/repository.md) — the shared repository contract diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md new file mode 100644 index 0000000..1a040cb --- /dev/null +++ b/docs/guides/troubleshooting.md @@ -0,0 +1,275 @@ +# Troubleshooting + +Map any wpify/model error message — or "silently wrong" symptom — to its cause and fix. + +**Prerequisites:** [Installation](../getting-started/installation.md), [Architecture](../concepts/architecture.md) + +All library exceptions live in `Wpify\Model\Exceptions` and extend `ModelException`, so `catch ( ModelException $e )` catches everything the library throws. PHP fatal errors ("Call to undefined function …") are not library exceptions and cannot be caught this way — they mean a WordPress feature the code relies on is missing. + +## Error and symptom lookup + +| Error or symptom | Likely cause | Details | +| --- | --- | --- | +| ``Repository for model `Book` not found.`` | No repository registered for that exact model class | [`RepositoryNotFoundException`](#repositorynotfoundexception) | +| `Unable to find repository for Book:author` | Relation property has no class type | [`RepositoryNotFoundException`](#repositorynotfoundexception) | +| `Repository not initialized, use Wpify\Model\Manager->register_repository( … )` | Repository was never registered with the Manager | [`RepositoryNotInitialized`](#repositorynotinitialized) | +| `Property isbn in model Book is not defined` | Typo, or the property is not declared on the model | [`PropertyNotDefinedException`](#propertynotdefinedexception) | +| `Cannot set readonly property permalink` | Writing a `#[ReadOnlyProperty]` prop after it was read | [`ReadOnlyPropertyException`](#readonlypropertyexception) | +| `CouldNotSaveModelException` with a WordPress message | The underlying WP write function failed | [`CouldNotSaveModelException`](#couldnotsavemodelexception) | +| `Cannot create an item with no post types.` | Custom repository's `post_types()` does not return exactly one type | [`CouldNotSaveModelException`](#couldnotsavemodelexception) | +| PHP fatal: `Call to undefined function wc_get_product()` | WooCommerce model used without WooCommerce active | [Call to undefined function wc_get_product()](#call-to-undefined-function-wc_get_product) | +| PHP fatal: `Call to undefined function get_site()` | Site model used on a single-site install | [Call to undefined function get_site()](#call-to-undefined-function-get_site) | +| A `#[Meta]` property is always empty or its default | Unsaved model, wrong meta key, or stale cache | [A meta property is always empty](#a-meta-property-is-always-empty) | +| Featured image vanished after saving a new post | Thumbnail persisted before `wp_insert_post()` ran | [The featured image disappeared on first save](#the-featured-image-disappeared-on-first-save) | +| Term `get( 0 )` returned a model, not `null` | `get_term( 0 )` returns a truthy `WP_Error` | [A term lookup returned a model instead of null](#a-term-lookup-returned-a-model-instead-of-null) | +| Custom table save created a second row | `save()` INSERTs any model without a source row attached, regardless of primary key | [A custom table save inserted a duplicate row](#a-custom-table-save-inserted-a-duplicate-row) | + +## `RepositoryNotFoundException` + +**Message:** ``Repository for model `Book` not found.`` + +The Manager maps model classes to repositories by exact class name — there is no inheritance walking. Even though `Book extends Post` and `PostRepository` is registered by default, `Book` still needs its own repository whose `model()` returns `Book::class`. + +```php +use Wpify\Model\Manager; + +$manager = new Manager( new BookRepository() ); +// or after construction: +$manager->register_repository( new BookRepository() ); +``` + +A second common cause is mixing up the Manager's two getters: `get_repository()` takes a **repository** class, `get_model_repository()` takes a **model** class. + +```php +$books = $manager->get_repository( BookRepository::class ); // repository class +$books = $manager->get_model_repository( Book::class ); // model class +// result: both return the same BookRepository instance +``` + +> [!NOTE] +> `get_repository()` itself never checks registration — it blindly instantiates whatever class name you pass. Passing a model class by mistake therefore goes one of two ways: with no `BookRepository` registered, `get_repository( Book::class )` throws `RepositoryNotFoundException` anyway, because the `Book` constructor looks up its own repository; with `BookRepository` registered, it hands you a `Book` model instead of a repository and the failure surfaces later, somewhere confusing. + +**Message:** `Unable to find repository for Book:author` + +This variant comes from `#[ManyToOneRelation]`, which picks the target repository from the property's **declared class type**. An untyped (or scalar-typed) relation property has no class to look up, so reading it throws. Declare the property with the related model class. + +```php +use Wpify\Model\Attributes\ManyToOneRelation; +use Wpify\Model\User; + +#[ManyToOneRelation( 'author_id' )] +public ?User $author = null; // the ?User type routes resolution through UserRepository +``` + +## `RepositoryNotInitialized` + +**Message:** `Repository not initialized, use Wpify\Model\Manager->register_repository( BookRepository ) to initialize or add.` + +A repository only receives its Manager when it is registered. A repository you constructed with `new` and used directly — without passing it to the Manager constructor or `register_repository()` — throws this the moment it needs the Manager (which is almost every method). Query methods can mask the problem: `find_all()` only needs the Manager while hydrating result rows, so on an install with no matching posts it returns `array()` silently. + +```php +$books = new BookRepository(); +$books->create(); // result: RepositoryNotInitialized — never registered +``` + +The fix is always the same: register the repository before use, then fetch it from the Manager. + +```php +$manager->register_repository( new BookRepository() ); +$books = $manager->get_repository( BookRepository::class ); +$books->find_all(); // result: Book[] — runs WP_Query over post_type 'book' +``` + +> [!NOTE] +> Calling `get_repository()` with a repository class that was **never registered** does not fail immediately: the Manager instantiates and caches the class, but never injects itself into it. The broken instance then throws `RepositoryNotInitialized` on first real use. Registration via constructor arguments or `register_repository()` is the only safe path — see [the Manager reference](../reference/manager.md). + +## `PropertyNotDefinedException` + +**Message:** `Property isbn in model Book is not defined` + +Models expose exactly the properties declared on the class — reading anything else throws. The usual causes are a typo (`$book->isbnn`) or a property you meant to add but never declared as a typed public property. + +```php +use Wpify\Model\Attributes\Meta; + +// Declare the property on the model to make it readable: +#[Meta( meta_key: 'isbn' )] +public string $isbn = ''; +``` + +> [!NOTE] +> Only the first read of an undeclared, never-written property throws. Writing an undeclared property emits PHP "Undefined array key" warnings but still silently caches the value — subsequent reads return it without an exception, yet it is never persisted. Array-style reads return `null` silently: `$book['isbnn']` is `null`, no exception. See [property resolution](../concepts/property-resolution.md) for the full `__get`/`__set` flow. + +## `ReadOnlyPropertyException` + +**Message:** `Cannot set readonly property permalink` + +You assigned a `#[ReadOnlyProperty]` prop (such as `Post::$permalink`, `$author`, or the date fields) after it already held a resolved, non-empty value. Read-only props are never persisted anyway — write the underlying writable property instead. + +```php +$book->slug = 'dune-1965'; // writable source of the permalink +$books->save( $book ); // wp_update_post() writes post_name +echo $book->permalink; // result: https://example.com/book/dune-1965/ +``` + +> [!NOTE] +> The guard only arms after a non-empty value is cached: an unread (or empty) read-only prop accepts assignment without error, and array-style writes (`$book['permalink'] = …`) bypass the check entirely by writing straight into the cache. Neither path persists anything. + +## `CouldNotSaveModelException` + +Every repository throws this when the underlying WordPress write function (`wp_insert_post`, `wp_insert_term`, `wp_insert_user`, …) returns a `WP_Error` or `false`. The exception message is WordPress's own error message; for term and site saves the original `WP_Error` object is also attached and available via `get_wp_error()` (it is `null` for post, user, comment, and WooCommerce saves). + +```php +use Wpify\Model\Exceptions\CouldNotSaveModelException; + +try { + $genres->save( $genre ); +} catch ( CouldNotSaveModelException $e ) { + error_log( $e->getMessage() ); // e.g. "A term with the name provided already exists…" + $wp_error = $e->get_wp_error(); // WP_Error for term/site saves, null for other families +} +``` + +Two special messages come from `PostRepository::create()`, not from saving: `Cannot create an item with no post types.` and `Cannot create an item with multiple post types.` Both mean your custom repository's `post_types()` override does not return an array with exactly one post type — a missing `return` statement is the classic cause. See [Custom post types](./custom-post-types.md). + +```php + [!IMPORTANT] +> Requires WooCommerce. `Product`, `ProductCat`, `Order`, and `OrderItem*` models only work with WooCommerce active. + +The Manager registers the WooCommerce repositories unconditionally and registration itself is harmless — but the first real call (`get()`, `find()`, `save()`) reaches `wc_get_product()` / `wc_get_orders()` and dies with a PHP fatal `Error`, not a catchable library exception. Guard WooCommerce-dependent code yourself. + +```php +use Wpify\Model\ProductRepository; + +if ( class_exists( 'WooCommerce' ) ) { + $product = $manager->get_repository( ProductRepository::class )->get( 123 ); +} +``` + +See the [WooCommerce guide](./woocommerce.md) for the full list of WooCommerce-only classes. + +## Call to undefined function get_site() + +> [!IMPORTANT] +> Requires multisite. `Site` and `SiteRepository` only work on a multisite network. + +WordPress loads `get_site()`, `get_sites()`, `wp_insert_site()`, and the rest of the sites API only when `is_multisite()` is true, so every `SiteRepository` method that touches the database (`get()`, `find*()`, `save()`, `delete()`) is a PHP fatal error on a single-site install. Only `model()`, `create()`, and registration are safe there — guard everything else. + +```php +use Wpify\Model\SiteRepository; + +if ( is_multisite() ) { + $site = $manager->get_repository( SiteRepository::class )->get( get_main_site_id() ); +} +``` + +See the [Multisite guide](./multisite.md) for what works where. + +## A meta property is always empty + +A `#[Meta]` prop that keeps returning `''`, `0`, or its declared default usually has one of three causes. First: **the model has no ID yet.** Meta reads call `get_post_meta( $model->id, … )`, and an unsaved model has `id === 0`, so there is no meta row to find. (A value you assigned on the instance yourself reads back from the model's in-memory cache immediately — but it is not persisted, and no other instance sees it, until `save()`.) + +```php +$book = $books->create( array( 'title' => 'Dune' ) ); +echo $book->isbn; // result: '' — get_post_meta( 0, 'isbn' ), no row to find +$book->isbn = '978-0441172719'; +$book = $books->save( $book ); // wp_insert_post() writes the meta via meta_input +echo $book->isbn; // result: 978-0441172719 +``` + +Second: **the meta key does not match.** `#[Meta]` defaults its key to the property name, so renaming the property silently reads from (and writes to) a different key and the stored data appears lost. + +> [!WARNING] +> Always pin the key with `meta_key:` on production models — `#[Meta( meta_key: '_book_isbn' )]` keeps reading `_book_isbn` no matter what the property is later renamed to. See [Meta fields](./meta-fields.md). + +Third: **the value is cached.** Props resolve once and are memoized; if the meta row changed behind the model's back, drop the cache to re-read it. + +```php +unset( $book->isbn ); // clears the cached value only +echo $book->isbn; // result: re-read via get_post_meta() +``` + +## The featured image disappeared on first save + +> [!WARNING] +> Setting `featured_image_id` on a **new** post-family model is silently lost on the first save. `save()` collects props — which runs `persist_featured_image_id()` → `set_post_thumbnail( 0, … )` — *before* `wp_insert_post()` assigns a real ID, so the thumbnail call targets post `0` and does nothing. Updates of existing posts are unaffected. + +The workaround is to save twice: insert first so the model gets an ID, then set the featured image and save again. + +```php +$book = $books->create( array( 'title' => 'Dune' ) ); +$book = $books->save( $book ); // 1) wp_insert_post() — $book->id is now real +$book->featured_image_id = 42; +$book = $books->save( $book ); // 2) set_post_thumbnail( $book->id, 42 ) now sticks +``` + +## A term lookup returned a model instead of null + +`TermRepository::get( 0 )` (or any empty numeric ID) does not return `null`: WordPress's `get_term( 0 )` returns a `WP_Error`, which is truthy, so the repository wraps it as the model's source and hands you a `Term` whose props all resolve to defaults with `id === 0`. Guard IDs before the lookup, and check `id` after it. + +```php +$genre = $genre_id > 0 ? $genres->get( $genre_id ) : null; +if ( $genre && $genre->id > 0 ) { + echo $genre->name; // result: a real term +} +``` + +> [!WARNING] +> Reading `permalink` on such a model is a fatal `TypeError`: `get_term_link()` returns a `WP_Error` for a nonexistent term, which cannot be coerced to the declared `string`. Check `id > 0` before touching `permalink`. More term gotchas: [Term models](../reference/models/term.md). + +## A custom table save inserted a duplicate row + +`CustomTableRepository::save()` decides between `$wpdb->insert()` and `$wpdb->update()` by whether the model has a **source row attached** — not by its primary key value. A model built by hand always INSERTs: with the primary key left at its default `0`, auto-increment silently assigns a new id and a duplicate row appears. (Setting an existing primary key by hand does not sneak in an update either — the key is merged into the INSERT, which then collides with the existing row and throws `SqlException`, e.g. `Duplicate entry '42' for key 'PRIMARY'`.) + +```php +// WRONG: hand-built model, no source row — save() INSERTs a brand-new row. +$loan = $loans->create( array( 'returned_at' => current_time( 'mysql' ) ) ); // meant to update loan 42 +$loans->save( $loan ); // INSERT INTO wp_book_loans … — a second row appears +``` + +To update an existing row, fetch the model through the repository first — `get()` and `find()` attach the source row, so `save()` updates. + +```php +$loan = $loans->get( 42 ); // has a source row attached +$loan->returned_at = current_time( 'mysql' ); +$loans->save( $loan ); // result: UPDATE wp_book_loans SET … WHERE id = 42 +``` + +The full insert/update semantics and query syntax are in the [Custom tables guide](./custom-tables.md) and the [CustomTableRepository reference](../reference/custom-table-repository.md). + +## Related + +- [Quickstart](../getting-started/quickstart.md) — the happy path these errors deviate from +- [Property resolution](../concepts/property-resolution.md) — how `__get`/`__set`, caching, and coercion actually work +- [Persistence](../concepts/persistence.md) — what `save()` does per model family +- [Manager reference](../reference/manager.md) — registration and the two repository getters +- [Model reference](../reference/model.md) — the exceptions each model method can throw +- [Repository reference](../reference/repository.md) — the shared repository contract +- [Meta fields](./meta-fields.md) · [Custom post types](./custom-post-types.md) · [Custom tables](./custom-tables.md) · [WooCommerce](./woocommerce.md) · [Multisite](./multisite.md) + +## Transaction errors + +- **Migrate custom tables before starting a transaction.** A participating table needs schema preparation. Call its `migrate()` before the outer transaction starts. +- **Could not migrate a transaction repository.** Schema preparation failed; inspect the database error before retrying. +- **Transactions require a mysqli-backed wpdb connection.** The helper supports WordPress's mysqli connection, not alternative database adapters. +- **Transaction statement failed: …** Begin, savepoint, commit or rollback failed. Inspect the database message and reconcile uncertain commits before retrying. +- **Transaction was lost or the database connection changed.** The callback changed transaction state, the server aborted it or the connection was replaced. Do not treat the callback as committed. +- **The database connection changed during a transaction statement.** A reconnect interrupted transaction control. Reconcile the outcome before retrying. +- **Transaction rollback failed: …** Rollback could not complete; `getPrevious()` retains the original failure. The connection must be treated as requiring recovery. + +See [transactions](../reference/transactions.md) for supported operations and side-effect limits. diff --git a/docs/guides/woocommerce.md b/docs/guides/woocommerce.md new file mode 100644 index 0000000..bf28d82 --- /dev/null +++ b/docs/guides/woocommerce.md @@ -0,0 +1,362 @@ +# Working with WooCommerce models + +After this page you can read, query, create, update, and delete WooCommerce products, orders, order items, and product categories through the built-in `Product`, `Order`, `OrderItem*`, and `ProductCat` models. + +**Prerequisites:** [Installation](../getting-started/installation.md) · [Architecture](../concepts/architecture.md) + +> [!IMPORTANT] +> **Requires WooCommerce.** The Manager registers the seven WooCommerce repositories unconditionally — there is no `class_exists( 'WooCommerce' )` guard anywhere in the library. Constructing the Manager without WooCommerce works, but the first real call (anything that reaches `wc_get_product()`, `wc_get_orders()`, …) dies with a PHP `Error` — `Call to undefined function wc_get_product()` — not a catchable library exception. Guard WooCommerce-dependent code yourself. + +Wrap any code that touches the WooCommerce repositories in your own guard. + +```php +if ( ! class_exists( 'WooCommerce' ) ) { + return; // WooCommerce inactive — never touch the WC repositories. +} +``` + +All snippets below assume a shared `$manager` (`Wpify\Model\Manager`) instance, set up as shown in [Installation](../getting-started/installation.md). + +## Reading products + +Get `ProductRepository` from the Manager and fetch a product by ID. + +```php +use Wpify\Model\ProductRepository; + +$products = $manager->get_repository( ProductRepository::class ); +$product = $products->get( 123 ); // wc_get_product( 123 ) + +echo $product->name; // result: Hoodie with Logo +``` + +`get()` also accepts a `Product` model or `WC_Product` object (returned/wrapped as-is), a SKU, or a slug — it tries, in order: instance → numeric ID via `wc_get_product()` → SKU via `wc_get_products( array( 'sku' => … ) )` → slug via `get_page_by_path()`. It returns `null` when nothing matches. + +```php +$product = $products->get( 'MY-SKU-001' ); // by SKU +$product = $products->get( 'hoodie-with-logo' ); // by slug +// result: Wpify\Model\Product, or null if nothing matches +``` + +> [!NOTE] +> SKU lookup runs before slug lookup, and a numeric string that is not a product ID is still tried as a SKU and then as a slug. Keep that in mind if your SKUs are numeric. + +### Product properties + +Almost every `Product` property is an `#[AccessorObject]` property: reading it calls the matching getter on the underlying `WC_Product` source object, then coerces the value to the declared PHP type (see [property resolution](../concepts/property-resolution.md)). + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `WC_Product::get_id()` | `0` for unsaved products | +| `parent_id` | `int` | `WC_Product::get_parent_id()` | | +| `type` | `string` | `WC_Product::get_type()` | `simple`, `variable`, … | +| `name` | `string` | `WC_Product::get_name()` | | +| `slug` | `string` | `WC_Product::get_slug()` | | +| `sku` | `string` | `WC_Product::get_sku()` | | +| `price` | `float` | `WC_Product::get_price()` | WC's empty-string price coerces to `0.0` | +| `regular_price` | `float` | `WC_Product::get_regular_price()` | | +| `sale_price` | `float` | `WC_Product::get_sale_price()` | | +| `stock_quantity` | `int` | `WC_Product::get_stock_quantity()` | | +| `manage_stock` | `bool` | `WC_Product::get_manage_stock()` | | +| `stock_status` | `string` | `WC_Product::get_stock_status()` | | +| `is_in_stock` | `bool` | `WC_Product::is_in_stock()` | Method-name fallback — no `get_is_in_stock()` exists on `WC_Product` | +| `catalog_visibility` | `string` | `WC_Product::get_catalog_visibility()` | | +| `short_description` | `string` | `WC_Product::get_short_description()` | | +| `description` | `string` | `WC_Product::get_description()` | | +| `image_id` | `int` | `WC_Product::get_image_id()` | Featured image attachment ID | +| `gallery_image_ids` | `array` | `WC_Product::get_gallery_image_ids()` | | +| `is_featured` | `bool` | `WC_Product::get_featured()` | Declared as `#[AccessorObject( key: 'featured' )]` | +| `category_ids` | `array` | `WC_Product::get_category_ids()` | Writable; persists on save | +| `categories` | `ProductCat[]` | `get_the_terms( $id, 'product_cat' )` | Read-only in practice — see the warning under [Updating a product](#updating-a-product) | +| `permalink` | `string` | `WC_Product::get_permalink()` | `#[ReadOnlyProperty]` | +| `wc_product` | `WC_Product\|null` | `source()` | `#[ReadOnlyProperty]` — the raw source object | +| `featured_image` | `?Attachment` | — | Always `null` — see below | + +> [!NOTE] +> Known limitation: `Product::$featured_image` always resolves to `null`. Its `#[ManyToOneRelation( 'featured_image_id' )]` reads a `featured_image_id` property that does not exist on `Product` (the real property is `image_id`), so the relation silently short-circuits. Use `$product->image_id` and load the attachment yourself. + +### VAT rate + +`Product::get_vat_rate( string $country_code ): ?float` returns the product's tax rate for a country via `WC_Tax::find_rates()`, or `null` when the product is not taxable. + +```php +$rate = $product->get_vat_rate( 'CZ' ); +// result: 21.0 (float), or null for a non-taxable product +``` + +## Querying products + +`ProductRepository::find()` is a thin wrapper over `wc_get_products()` — pass any `WC_Product_Query` arguments and get `Product[]` back. Unlike plain `wc_get_products()`, a `tax_query` argument works: the repository temporarily registers the `woocommerce_product_data_store_cpt_get_products_query` filter to support it. + +```php +$on_sale = $products->find( array( + 'status' => 'publish', + 'limit' => 20, + 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'sale' ) ), +) ); +// result: Product[] (up to 20 published products in the "sale" category) +``` + +| Method | Signature | Notes | +|---|---|---| +| `find` | `find( array $args = array() ): array` | `wc_get_products( $args )`, each result wrapped as a `Product` | +| `find_all` | `find_all( array $args = array() ): array` | `find()` with default `limit => -1` | +| `find_by_ids` | `find_by_ids( array $ids, array $args = array() ): array` | `find()` with defaults `limit => -1`, `include => $ids` | +| `find_all_by_term` | `find_all_by_term( ModelInterface $model ): array` | Products in a term — pass a `ProductCat` (or any term model whose repository has a `taxonomy()` method); builds a `tax_query` by `term_id` | + +Use `find_all_by_term()` to list the products in a category without writing the `tax_query` yourself. + +```php +use Wpify\Model\ProductCatRepository; + +$cat = $manager->get_repository( ProductCatRepository::class )->get( 'accessories' ); +$in_cat = $products->find_all_by_term( $cat ); +// result: Product[] — products in "accessories", capped at WooCommerce's default query limit +``` + +> [!NOTE] +> Known limitation: despite its name, `find_all_by_term()` does not set `limit => -1` (unlike `find_all()`), so `wc_get_products()` applies its default limit — the `posts_per_page` option, typically 10. A category with more products silently returns a truncated list. When you need the full set, call `find_all()` with an explicit `tax_query` instead. + +> [!NOTE] +> `find( array( 'return' => 'ids' ) )` intentionally breaks the "always models" contract and returns a raw `int[]` of product IDs. + +## Creating a product + +`create()` builds an in-memory model without attaching any WooCommerce source object, and `save()` delegates to the source object's own `save()` method — so the order of operations matters. + +> [!WARNING] +> Calling `create( array( 'name' => … ) )` and then `save()` fatals with *"Call to a member function get_id() on null"* — the model has no `WC_Product` source. Worse, properties set before a source is attached are only cached on the model and are **never persisted**. Always attach the source object first, then set properties. + +This is the working creation sequence. + +```php +use Wpify\Model\ProductRepository; + +$products = $manager->get_repository( ProductRepository::class ); +$product = $products->create(); +$product->source( new \WC_Product_Simple() ); // attach the source FIRST +$product->name = 'New product'; // now writes through to the WC_Product +$product = $products->save( $product ); +echo $product->id; // result: 124 (the new product ID) +``` + +At the WordPress layer, `save()` runs your model's `persist_{prop}()` hooks (if any), then calls `WC_Product::save()`, which writes `wp_posts`, `wp_postmeta`, and WooCommerce's lookup tables, and finally refreshes the model from a freshly loaded `wc_get_product()`. + +## Updating a product + +Assigning to an `#[AccessorObject]` property writes through to the in-memory `WC_Product` immediately (`$product->name = 'X'` calls `WC_Product::set_name( 'X' )`); nothing touches the database until you call `save()`, which calls `WC_Product::save()`. + +```php +$product = $products->get( 123 ); +$product->stock_quantity = 5; // WC_Product::set_stock_quantity( 5 ), in memory +$product->sale_price = 19.99; +$products->save( $product ); // WC_Product::save() writes to the database +// result: the saved Product, refreshed from the database +``` + +> [!WARNING] +> `Product::$categories` does **not** persist on save. Its `#[PostTermsRelation]` only persists through `PostRepository::save()` (and its subclasses) — `ProductRepository::save()` never calls relation `persist()` — so category models assigned to `$product->categories` are silently dropped. Assign term IDs to `$product->category_ids` instead, which writes through to `WC_Product::set_category_ids()` and persists on save. + +Set categories the way that actually persists. + +```php +$product->category_ids = array( 15, 22 ); // WC_Product::set_category_ids() +$products->save( $product ); +// result: product assigned to product_cat terms 15 and 22 +``` + +## Deleting a product + +`delete()` calls `WC_Product::delete( $force_delete )` and returns a boolean. + +```php +$products->delete( $product ); // permanent delete (default) +$products->delete( $product, false ); // move to trash instead +// result: true +``` + +> [!WARNING] +> `$force_delete` defaults to `true` — the product is deleted permanently, skipping the trash. That is the opposite of WordPress's usual trash-first behavior; pass `false` to trash. + +## Orders + +### Getting an order + +`OrderRepository::get()` accepts an `Order` model, a `WC_Order` object, a numeric ID, or an **order key** string. + +```php +use Wpify\Model\OrderRepository; + +$orders = $manager->get_repository( OrderRepository::class ); +$order = $orders->get( 456 ); // wc_get_order( 456 ) +$order = $orders->get( 'wc_order_h9DpN3qXbXrWm' ); // by order key +// result: Wpify\Model\Order, or null if nothing matches +``` + +> [!NOTE] +> A string passed to `OrderRepository::get()` means an *order key* (resolved via `wc_get_order_id_by_order_key()`), not a slug — different semantics from `ProductRepository::get()`. Also, a `WC_Order_Refund` object is not accepted; only `WC_Order` instances resolve. + +### Querying orders + +`find()` passes its arguments straight to `wc_get_orders()`; `find_all()` adds a default `limit => -1`. + +```php +$processing = $orders->find( array( 'status' => 'processing', 'limit' => 10 ) ); +// result: Order[] — the 10 most recent processing orders +``` + +> [!NOTE] +> `OrderRepository::find_by_ids( array $ids )` loads each ID with `get()` and keeps unresolvable IDs as `null` entries in the returned array — filter the result before iterating. + +### Order properties + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `WC_Order::get_id()` | | +| `parent_id` | `int` | `WC_Order::get_parent_id()` | | +| `total` | `string` | `WC_Order::get_total()` | WC stores totals as strings — cast with `(float) $order->total` for math | +| `order_key` | `string` | `WC_Order::get_order_key()` | | +| `weight` | `string` | `Order::get_weight()` | The model getter wins over the accessor — computed sum of line-item product weights, coerced to string | +| `wc_order` | `?WC_Abstract_Order` | `source()` | `#[ReadOnlyProperty]` — the raw source object | +| `line_items` | `OrderItemLine[]` | `WC_Order::get_items( 'line_item' )` | `#[ReadOnlyProperty]` | +| `shipping_items` | `OrderItemShipping[]` | `WC_Order::get_items( 'shipping' )` | `#[ReadOnlyProperty]` | +| `fee_items` | `OrderItemFee[]` | `WC_Order::get_items( 'fee' )` | `#[ReadOnlyProperty]` | +| `items` | `array` | `Order::get_items()` | `#[ReadOnlyProperty]` — merge of the three collections above | + +### Order items + +Order items are resolved lazily by the `#[OrderItemsRelation]` source attribute (see [Relations](relations.md)): each `WC_Order_Item` of the requested type is wrapped in a typed model. + +| Order property | Model class | WC item type | Own properties beyond `OrderItem` | +|---|---|---|---| +| `$order->line_items` | `OrderItemLine` | `line_item` | `product`, `product_id`, `variation_id` | +| `$order->shipping_items` | `OrderItemShipping` | `shipping` | `method_id`, `instance_id`, `method_title` | +| `$order->fee_items` | `OrderItemFee` | `fee` | — (base properties only) | + +All three extend `OrderItem`, which contributes the shared properties. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `WC_Order_Item::get_id()` | | +| `type` | `string` | `WC_Order_Item::get_type()` | | +| `name` | `string` | `WC_Order_Item::get_name()` | | +| `quantity` | `string` | `WC_Order_Item::get_quantity()` | Coerced from WC's int — cast with `(int) $item->quantity` | +| `tax_total` | `float` | `WC_Order_Item::get_total_tax()` | Property name differs from WC's `total_tax` | +| `tax_class` | `string` | `WC_Order_Item::get_tax_class()` | | +| `unit_price_tax_included` | `float` | `OrderItem::get_unit_price_tax_included()` | `(total + tax) / quantity` | +| `unit_price_tax_excluded` | `float` | `OrderItem::get_unit_price_tax_excluded()` | `total / quantity` | +| `vat_rate` | `float` | `OrderItem::get_vat_rate()` | Rate percent from the order's tax lines | +| `vat_rate_id` | `int` | `OrderItem::get_vat_rate_id()` | | +| `wc_order_item` | `?WC_Order_Item` | `source()` | The raw source object | + +Iterate a collection like any array of models. + +```php +foreach ( $order->line_items as $item ) { + printf( "%s × %d = %.2f\n", $item->name, (int) $item->quantity, $item->get_unit_price() ); +} +// result: Hoodie with Logo × 2 = 22.50 +``` + +> [!NOTE] +> `OrderItemRepository::find()`, `find_all()`, and `find_by_ids()` always return empty arrays — by design (the repository is marked `@internal` and item queries won't be implemented). The only way to enumerate order items is through an `Order` model's `line_items` / `shipping_items` / `fee_items` / `items` properties. + +> [!NOTE] +> `OrderItemLine::$product` returns the raw `WC_Product` from `WC_Order_Item_Product::get_product()`, not a `Wpify\Model\Product`. Pass it (or `$item->product_id`) through `ProductRepository::get()` when you need the model. + +Convert a line item's product to a model when you want model semantics. + +```php +use Wpify\Model\ProductRepository; + +$products = $manager->get_repository( ProductRepository::class ); +$model = $products->get( $order->line_items[0]->product ); +// result: Wpify\Model\Product wrapping the same WC_Product +``` + +### Updating an order item + +Order item properties write through to the in-memory `WC_Order_Item` on assignment; save through the matching item repository, which calls `WC_Order_Item::save()` and refreshes the model's caches. + +```php +use Wpify\Model\OrderItemLineRepository; + +$item_repo = $manager->get_repository( OrderItemLineRepository::class ); +$item = $order->line_items[0]; +$item->name = 'Renamed line'; // writes through to WC_Order_Item_Product::set_name() +$item_repo->save( $item ); // WC_Order_Item::save() +// result: the item row in wp_woocommerce_order_items is updated +``` + +### Order helpers + +`Order::get_weight( string $unit = 'g' ): float` sums the weight of each line item's product, converting between the store weight unit and `$unit` for the `g`↔`kg` pair. + +```php +$kg = $order->get_weight( 'kg' ); +// result: 2.5 (float) +``` + +> [!NOTE] +> Known limitation: `get_weight()` ignores item quantities — three line items of a 2 kg product on one row count as 2 kg, not 6 kg. Sum `$item->product->get_weight() * (int) $item->quantity` over `$order->line_items` yourself if you need quantity-aware totals. + +`Order::has_shipping_method( $shipping_method_ids ): bool` checks the order's shipping items against `"{method_id}:{instance_id}"` strings — pass one string or an array of them. + +```php +if ( $order->has_shipping_method( array( 'flat_rate:3', 'local_pickup:1' ) ) ) { + // order ships via one of these method instances +} +// result: true when any shipping item matches +``` + +## Product categories + +`ProductCatRepository` is a `TermRepository` bound to WooCommerce's `product_cat` taxonomy; `ProductCat` extends `Term`, so it carries the full term property set (see [Term models](../reference/models/term.md)) plus a lazy `products` reverse relation. + +```php +use Wpify\Model\ProductCatRepository; + +$cats = $manager->get_repository( ProductCatRepository::class ); +$cat = $cats->get( 'accessories' ); // by slug — also accepts ID, name, or WP_Term +echo $cat->name; // result: Accessories +``` + +`ProductCat::$products` lazily loads the category's products via a `product_cat` tax query — cached after the first read, cleared by `$cat->refresh()`. + +```php +foreach ( $cat->products as $product ) { + echo $product->name; // Product[], loaded via ProductRepository::find_all_by_term() +} +// result: one name per product, capped at WooCommerce's default query limit +``` + +> [!NOTE] +> Known limitation: `$cat->products` goes through `ProductRepository::find_all_by_term()`, which does not set `limit => -1` — results are capped at WooCommerce's default query limit (the `posts_per_page` option, typically 10). Call `ProductRepository::find_all()` with an explicit `tax_query` when you need every product in the category. + +The repository's finders wrap `get_terms()` on the `product_cat` taxonomy. + +| Method | Signature | Behavior | +|---|---|---| +| `find` | `find( array $args = array() ): array` | `get_terms()` with default `taxonomy => 'product_cat'` | +| `find_all` | `find_all( array $args = array() ): array` | `find()` with `hide_empty => false` | +| `find_not_empty` | `find_not_empty( array $args = array() ): array` | `find()` with `hide_empty => true` | +| `find_children_of` | `find_children_of( int $parent_id = 0, array $args = array() ): array` | `find()` with `child_of => $parent_id`; empty array when `$parent_id <= 0` | +| `find_terms_of_post` | `find_terms_of_post( int $post_id ): array` | `get_the_terms( $post_id, 'product_cat' )` wrapped into models | +| `find_child_terms_of` | `find_child_terms_of( ModelInterface $model ): array` | `find()` with `hierarchical => true`, `hide_empty => false`, `child_of => $model->id` | +| `find_by_ids` | `find_by_ids( array $ids, array $args = array() ): array` | `find()` with `include => $ids` | + +Creating a category is safe with plain `create()` + `save()` — term repositories persist via `wp_insert_term()` and need no source object, unlike the product and order repositories. + +```php +$cat = $cats->create( array( 'name' => 'Sale', 'slug' => 'sale' ) ); +$cats->save( $cat ); // wp_insert_term( 'Sale', 'product_cat', … ) +echo $cat->id; // result: 87 (the new term ID) +``` + +## Related + +- [Querying models](querying.md) — `get()`/`find()` semantics across all model families +- [Relations](relations.md) — every relation attribute, including `OrderItemsRelation` and `PostTermsRelation` +- [Custom taxonomies](custom-taxonomies.md) — the term-model pattern `ProductCat` is built on +- [Troubleshooting](troubleshooting.md) — error messages and their fixes +- Reference: [Product models](../reference/models/product.md) · [Order models](../reference/models/order.md) · [Term models](../reference/models/term.md) · [Attributes](../reference/attributes.md) diff --git a/docs/reference/attributes.md b/docs/reference/attributes.md new file mode 100644 index 0000000..412600d --- /dev/null +++ b/docs/reference/attributes.md @@ -0,0 +1,592 @@ +# Attributes + +You'd land here to look up any of the 17 PHP attributes in `Wpify\Model\Attributes` — the annotations that tell a repository where a model property's value comes from and where it goes on save. + +All of them are declared `#[Attribute( Attribute::TARGET_PROPERTY )]`: they go on **public model properties only**. Most implement `SourceAttributeInterface` (a `get()` the repository calls during lazy [property resolution](../concepts/property-resolution.md)); `Meta` and `AccessorObject` additionally have a `set()` invoked on assignment; `PostTermRelation` and `PostTermsRelation` have a `persist()` invoked on save; `ReadOnlyProperty` is a bare marker with no interface. + +> [!NOTE] +> A property stores only the **last** source attribute declared on it — stacking two source attributes silently ignores the first. Stacking `#[ReadOnlyProperty]` on top of a source attribute is fine, because it is a marker, not a source. + +## At a glance + +| Attribute | Reads from | Write path | Built-in users | +|---|---|---|---| +| [`SourceObject`](#sourceobject) | property (dot-path) on the source object | `data` bucket on repository `save()` | Comment, MenuItem, Post, Term, Site, User | +| [`Meta`](#meta) | `get_post_meta` / `get_user_meta` / `get_term_meta` / `get_comment_meta` / `get_site_meta` / WC `get_meta` | varies by family (see table below) | Attachment, Post, Site, User | +| [`AccessorObject`](#accessorobject) | getter method on the source object | setter method, immediately on assignment (in memory) | Order, OrderItem, OrderItemLine, OrderItemShipping, Product | +| [`AliasOf`](#aliasof) | another property of the same model | none (read-through alias) | Menu | +| [`ManyToOneRelation`](#manytoonerelation) | target repository `get()` by foreign-key property | none | Post, Term, Site, Product | +| [`IdsRelation`](#idsrelation) | target repository `find_by_ids()` | none | custom models only | +| [`PostTermRelation`](#posttermrelation) | first term from `find_terms_of_post()` | `wp_set_post_terms()` via `PostRepository::save()` only | custom models only | +| [`PostTermsRelation`](#posttermsrelation) | `find_terms_of_post()` | `wp_set_post_terms()` via `PostRepository::save()` only | Post, Product | +| [`TermPostsRelation`](#termpostsrelation) | target repository `find_all_by_term()` | none | Category, PostTag, ProductCat | +| [`ChildPostsRelation`](#childpostsrelation) | own repository `find_child_posts_of()` | none | Post | +| [`ChildTermsRelation`](#childtermsrelation) | own repository `find_child_terms_of()` | none | Term | +| [`TopLevelPostParentRelation`](#toplevelpostparentrelation) | `get_ancestors()` by post type | none | Post | +| [`TopLevelTermParentRelation`](#topleveltermparentrelation) | `get_ancestors()` by taxonomy | none | Term | +| [`MenuItemsRelation`](#menuitemsrelation) | `wp_get_nav_menu_items()` | none | Menu | +| [`OrderItemsRelation`](#orderitemsrelation) | `WC_Abstract_Order::get_items()` | none | Order | +| [`ReadOnlyProperty`](#readonlyproperty) | — (marker) | blocks overwrite of a non-empty cached value; excluded from save | MenuItem, Order, Term, Post, Site, Product, User | +| [`Column`](#column) | column of a custom table row | `CustomTableRepository::save()` | custom models only | + +## Source attributes + +### SourceObject + +Maps a property to a (possibly dotted) property path on the model's raw source object — the `WP_Post`, `WP_Term`, `WP_User`, `WP_Comment`, or `WP_Site` the model wraps. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `key` | `?string` | `null` | Property name or dot-path (`'nested.value'`) on the source object. The model property's own name is used when `null`. | + +This is how the built-in `Post` model renames raw `WP_Post` fields to friendlier property names: + +```php +use Wpify\Model\Attributes\SourceObject; + +#[SourceObject( 'ID' )] +public int $id = 0; + +#[SourceObject( 'post_title' )] +public string $title = ''; + +#[SourceObject] // key defaults to the property name: 'ping_status' +public string $ping_status = 'open'; +``` + +**Used by built-in models:** Comment, MenuItem, Post, Term, Site, User. + +`SourceObject` has no `set()` — assigning to the property only caches the value on the model. On repository `save()`, `collect_persistable_props()` puts the value into the `data` bucket under `key ?? property name`, which is how `$post->title` becomes `post_title` in `wp_update_post()`. See [persistence](../concepts/persistence.md) for the per-family write calls. + +> [!NOTE] +> A dotted `key` (`'nested.value'`) works for reading, but on save it becomes a literal `'nested.value'` data key — effectively read-only for the Post, Term, Comment, and Site families. The exception is User: its `data.*` keys do persist, because `UserRepository::save()` strips the `data.` prefix from every collected data key before calling `wp_insert_user()` / `wp_update_user()`. + +### Meta + +Maps a property to WordPress or WooCommerce metadata, dispatching on the model's base class (`Post` → `get_post_meta()`, `User` → `get_user_meta()`, `Term` → `get_term_meta()`, `Comment` → `get_comment_meta()`, `Site` → `get_site_meta()`, WooCommerce models → the WC object's `get_meta()`). + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `meta_key` | `?string` | `null` | Meta key to read/write. The property name is used when `null`. | +| `single` | `bool` | `true` | Passed to the `get_*_meta()` call; `false` returns all values of the key as an array. | + +A typical custom-model property — here on a `Book` model extending `Post`: + +```php +use Wpify\Model\Attributes\Meta; + +#[Meta( meta_key: '_price' )] +public float $price = 0.0; + +#[Meta] // meta key defaults to the property name: 'isbn' +public string $isbn = ''; +``` + +Reading resolves the meta lazily and caches it; writing is deferred to the repository for most families: + +```php +use Wpify\Model\User; + +$users = $manager->get_model_repository( User::class ); +$user = $users->get( 1 ); +$user->nickname = 'danny'; // cached on the model only +$users->save( $user ); // result: meta persisted via wp_update_user() with meta_input +``` + +**Used by built-in models:** Attachment, Post, Site, User — and the dispatch also covers Term, Comment, Product, Order, and OrderItem subclasses. + +> [!IMPORTANT] +> The Site branch requires multisite with the blogmeta table (`is_site_meta_supported()`) — on single-site, site meta reads return `null`. The WooCommerce branch requires WooCommerce. + +**When the meta is actually written** differs by model family: + +| Model family | When meta is written | Via | +|---|---|---| +| Post / Page / Attachment | on repository `save()` | `meta_input` of `wp_insert_post()` / `wp_update_post()` | +| Comment | on repository `save()` | `comment_meta` of `wp_insert_comment()` / `wp_update_comment()` | +| Term | on repository `save()` | `update_term_meta()` | +| User | on repository `save()` | `meta_input` of `wp_insert_user()` / `wp_update_user()` | +| Site | **immediately on assignment** | `update_site_meta()` (and again on `save()`) | +| Product / Order / OrderItem | on assignment, in memory only | WC `update_meta_data()`; hits the DB when `save()` calls the WC object's `save()` | + +> [!NOTE] +> `UserRepository` stores boolean meta values as the strings `'true'` / `'false'`; type coercion converts them back to `bool` on read. Models outside the dispatch (for example custom table models) silently read and write `null` — use [`Column`](#column) there instead. + +Renaming a property with a defaulted meta key changes the key it reads, so existing data appears lost — pin `meta_key:` explicitly for production models. The full story lives in the [meta fields guide](../guides/meta-fields.md). + +### AccessorObject + +Maps a property to getter/setter method calls on the model's source object — in practice the WooCommerce CRUD objects (`WC_Product`, `WC_Abstract_Order`, `WC_Order_Item*`), which is why every shipped use lives in the WooCommerce models. + +> [!IMPORTANT] +> Requires WooCommerce in practice: no WordPress core object exposes the `get_*()` / `set_*()` CRUD convention this attribute calls. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `key` | `?string` | `null` | Overrides the property name used to build the method names (`get_{key}` / `set_{key}`). | +| `getter` | `string` | `''` | Exact getter method name; overrides the convention entirely. | +| `setter` | `string` | `''` | Exact setter method name; overrides the convention entirely. | + +From the built-in `Product` model, including the `key:` override: + +```php +use Wpify\Model\Attributes\AccessorObject; + +#[AccessorObject] +public string $name = ''; // WC_Product::get_name() / set_name() + +#[AccessorObject( key: 'featured' )] +public bool $is_featured = false; // WC_Product::get_featured() / set_featured() +``` + +Assignment calls the setter immediately, mutating the in-memory WC object; nothing touches the database until the repository saves: + +```php +use Wpify\Model\Product; + +$products = $manager->get_model_repository( Product::class ); +$product = $products->get( 123 ); +$product->name = 'New name'; // WC_Product::set_name() runs now, in memory +$products->save( $product ); // result: persisted via WC_Product::save() +``` + +**Used by built-in models:** Order, OrderItem, OrderItemLine, OrderItemShipping, Product. + +> [!NOTE] +> If the source object is missing or the resolved method does not exist, `get()`/`set()` return `null` silently — no exception is thrown. + +### AliasOf + +Makes a property a read-through alias of another property on the same model. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `source_key` | `string` | — (required) | Name of the aliased property. | + +The only shipped use is `Menu::$items`, kept as a deprecated alias of `$children`: + +```php +use Wpify\Model\Attributes\AliasOf; +use Wpify\Model\Attributes\MenuItemsRelation; +use Wpify\Model\MenuItem; + +#[MenuItemsRelation( MenuItem::class )] +public array $children = array(); + +/** @deprecated Use $children instead. */ +#[AliasOf( 'children' )] +public array $items = array(); +``` + +**Used by built-in models:** Menu. + +> [!NOTE] +> Aliasing is read-only: writing to the alias only writes the alias's own cached value and never touches the original property. The alias also caches its own copy on first read, so later changes to the original are not reflected until `refresh()`. + +## Relation attributes + +Relations resolve other models lazily and cache the result on first read — they are re-queried only after `refresh()` or `unset( $model->prop )`. **Only `PostTermRelation` and `PostTermsRelation` persist on save, and only through `PostRepository::save()`** (and its Page/Attachment subclasses); every other relation is a read-only view. Realistic end-to-end examples for each live in the [relations guide](../guides/relations.md). + +### ManyToOneRelation + +Resolves a single related model from a foreign-key property, inferring the target model class from the annotated property's declared PHP type. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `source_key` | `string` | — (required) | Property on the same model holding the related model's id. | + +From the built-in `Post` model — the `?User` type declaration decides which repository loads it: + +```php +use Wpify\Model\Attributes\ManyToOneRelation; +use Wpify\Model\Attributes\ReadOnlyProperty; +use Wpify\Model\Attributes\SourceObject; +use Wpify\Model\User; + +#[SourceObject( 'post_author' )] +public int $author_id = 0; + +#[ReadOnlyProperty] +#[ManyToOneRelation( 'author_id' )] +public ?User $author = null; +``` + +Reading the property triggers one `get()` on the target repository: + +```php +use Wpify\Model\Post; + +$post = $manager->get_model_repository( Post::class )->get( 42 ); +echo $post->author->display_name; // result: "Jane Doe" — loaded once via UserRepository::get() +``` + +**Used by built-in models:** Post (`$author`, `$parent`, `$featured_image`), Term (`$parent`), Site (`$admin_user`), Product (`$featured_image`). + +> [!WARNING] +> The property's type declaration is load-bearing. An untyped property (or a type that is not a class) throws `RepositoryNotFoundException` on first read, and a union type causes a PHP fatal. A foreign-key value of `0` or `''` short-circuits to `null` without querying. + +### IdsRelation + +Resolves a list of models from an array of ids stored in another property, via the target repository's `find_by_ids()`. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `source_key` | `string` | — (required) | Property on the same model holding the id array. | +| `target_entity` | `string` (class-string) | — (required) | Model class to load. | +| `args` | `array` | `array()` | Extra query args merged into the lookup. | + +A `Book` model exposing hand-picked related books: + +```php +use Wpify\Model\Attributes\IdsRelation; +use Wpify\Model\Attributes\Meta; + +#[Meta( meta_key: '_related_book_ids' )] +public array $related_book_ids = array(); + +/** @var Book[] */ +#[IdsRelation( 'related_book_ids', Book::class )] +public array $related_books = array(); +``` + +**Used by custom models only.** + +> [!NOTE] +> `args` only has an effect for repositories whose `find_by_ids( array $ids, array $args = array() )` accepts it — Post, Term, Comment, and Product. The User, Site, Order, OrderItem, and custom table repositories take only `$ids` and silently ignore `args`. + +### PostTermRelation + +Resolves a **single** term (the first one) of a taxonomy assigned to a post, and persists it back on save. Read: first result of the term repository's `find_terms_of_post()` (wrapping `get_the_terms()`); persist: `wp_set_post_terms()`. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `target_entity` | `string` (class-string) | — (required) | Term-side model class (for example a custom `Genre extends Term`). | + +A `Book` model with a primary genre (`Genre` being a custom term model from the [custom taxonomies guide](../guides/custom-taxonomies.md)): + +```php +use Wpify\Model\Attributes\PostTermRelation; + +#[PostTermRelation( Genre::class )] +public ?Genre $primary_genre = null; +``` + +Assign a term model and save through the post's repository to persist it: + +```php +$book = $book_repository->get( 42 ); +$book->primary_genre = $genre_repository->get( 7 ); +$book_repository->save( $book ); // result: wp_set_post_terms() replaces the book's genre set +``` + +**Used by custom models only.** + +> [!WARNING] +> `persist()` runs only from `PostRepository::save()` (and its Page/Attachment subclasses), and it **replaces all terms** of that taxonomy with the single assigned one (`wp_set_post_terms()` with `$append = false`). "First term" means whatever `get_the_terms()` returns first — there is no ordering guarantee. + +### PostTermsRelation + +Resolves **all** terms of a taxonomy assigned to a post, and persists the set back on save. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `target_entity` | `string` (class-string) | — (required) | Term-side model class. | + +A `Book` model listing its genres: + +```php +use Wpify\Model\Attributes\PostTermsRelation; + +/** @var Genre[] */ +#[PostTermsRelation( Genre::class )] +public array $genres = array(); +``` + +Assign an array of term models and save through the post's repository: + +```php +$book = $book_repository->get( 42 ); +$book->genres = array( $genre_repository->get( 7 ) ); +$book_repository->save( $book ); // result: wp_set_post_terms() replaces the book's genres +``` + +**Used by built-in models:** Post (`$categories` → `Category`, `$tags` → `PostTag`), Product (`$categories` → `ProductCat`). + +> [!WARNING] +> `persist()` fires only in `PostRepository::save()`. `ProductRepository::save()` never calls attribute `persist()`, so assigning to `Product::$categories` and saving the product does **not** persist the categories — see the [WooCommerce guide](../guides/woocommerce.md) for the workaround. + +> [!NOTE] +> The resolved term list is cached on the model; call `refresh()` or `unset( $model->prop )` to see term changes made outside the model. + +### TermPostsRelation + +From a term model, resolves all posts of the target model's post type assigned to that term, via the target repository's `find_all_by_term()` (a tax-query `WP_Query` for posts, the WC product query for products). + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `target_entity` | `string` (class-string) | — (required) | Post-side model class (for example `Post::class`, `Product::class`, or a custom `Book`). | + +The inverse side of the book–genre pairing, on the `Genre` term model: + +```php +use Wpify\Model\Attributes\TermPostsRelation; + +/** @var Book[] */ +#[TermPostsRelation( Book::class )] +public array $books = array(); +``` + +**Used by built-in models:** Category and PostTag (`$posts` → `Post`), ProductCat (`$products` → `Product`). + +Read-only — assigning to the property never persists anything. `PostRepository::find_all_by_term()` throws `IncorrectRepositoryException` if the term model's repository has no `taxonomy()` method. + +### ChildPostsRelation + +Resolves all posts whose `post_parent` is this model's id, by calling `find_child_posts_of()` on the model's **own** repository (a `WP_Query` under the hood). No parameters. + +From the built-in `Post` model: + +```php +use Wpify\Model\Attributes\ChildPostsRelation; + +/** @var Post[] */ +#[ChildPostsRelation] +public array $children = array(); +``` + +**Used by built-in models:** Post (inherited by Page and Attachment). + +Read-only. The repository is looked up by the model's own class, so a custom model needs its repository to implement `find_child_posts_of( ModelInterface $model ): array` — `PostRepository` subclasses inherit it; anything else throws `RepositoryMethodNotImplementedException` on first read. + +### ChildTermsRelation + +Resolves all child terms of this term, by calling `find_child_terms_of()` on the model's own repository (wrapping `get_terms()` with `child_of` and `hide_empty => false`). No parameters. + +From the built-in `Term` model: + +```php +use Wpify\Model\Attributes\ChildTermsRelation; + +/** @var Term[] */ +#[ChildTermsRelation] +public array $children = array(); +``` + +**Used by built-in models:** Term (inherited by Category, PostTag, ProductCat, Menu). + +Read-only. Like `ChildPostsRelation`, it throws `RepositoryMethodNotImplementedException` if the model's repository lacks `find_child_terms_of()`. + +### TopLevelPostParentRelation + +Resolves the top-most ancestor of a hierarchical post via `get_ancestors()`. No parameters. + +From the built-in `Post` model: + +```php +use Wpify\Model\Attributes\TopLevelPostParentRelation; + +#[TopLevelPostParentRelation] +public ?Post $top_parent = null; +``` + +**Used by built-in models:** Post. + +> [!NOTE] +> It returns `null` unless the model's repository handles **exactly one** post type — a custom repository spanning several CPTs silently yields `null`. A top-level post (no ancestors) also yields `null`, not itself. + +### TopLevelTermParentRelation + +Resolves the top-most ancestor of a hierarchical term via `get_ancestors()`, using the repository's `taxonomy()`. No parameters. + +From the built-in `Term` model: + +```php +use Wpify\Model\Attributes\TopLevelTermParentRelation; + +#[TopLevelTermParentRelation] +public ?Term $top_parent = null; +``` + +**Used by built-in models:** Term (inherited by Category, PostTag, ProductCat, Menu). + +Read-only. A top-level term yields `null`, not itself; unlike the post variant there is no multi-taxonomy guard — the repository's single `taxonomy()` is used as-is. + +### MenuItemsRelation + +Resolves a nav menu's items as a **nested tree** of `MenuItem` models: `wp_get_nav_menu_items()` fetches the flat list, each item is wrapped via the target repository, and items are nested into each parent's `children` property. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `target_entity` | `string` (class-string) | `MenuItem::class` | Model class for each menu item. | + +From the built-in `Menu` model: + +```php +use Wpify\Model\Attributes\MenuItemsRelation; +use Wpify\Model\MenuItem; + +/** @var MenuItem[] */ +#[MenuItemsRelation( MenuItem::class )] +public array $children = array(); +``` + +Walk the tree level by level: + +```php +use Wpify\Model\Menu; + +$menu = $manager->get_model_repository( Menu::class )->get( 'main-menu' ); +foreach ( $menu->children as $item ) { + echo $item->title; // result: top-level item titles; nested items in $item->children +} +``` + +**Used by built-in models:** Menu. + +> [!WARNING] +> If the menu does not exist, `wp_get_nav_menu_items()` returns `false`, `get()` raises a PHP warning iterating over it, and the property resolves to an empty array — no exception is thrown. Only access `$menu->children` on menus fetched through `MenuRepository`. See the [menus guide](../guides/menus.md). + +### OrderItemsRelation + +Resolves a WooCommerce order's items of one type as an array of `OrderItemLine`, `OrderItemShipping`, or `OrderItemFee` models, reading `$model->wc_order->get_items()`. Requires WooCommerce (flagged [above](#accessorobject)). + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `order_item_type` | `string` | `'line_item'` | One of `'line_item'`, `'shipping'`, `'fee'` — mapped to `OrderItemLine`, `OrderItemShipping`, `OrderItemFee`. | + +From the built-in `Order` model — all three shipped uses: + +```php +use Wpify\Model\Attributes\OrderItemsRelation; +use Wpify\Model\Attributes\ReadOnlyProperty; + +#[ReadOnlyProperty] +#[OrderItemsRelation] +public array $line_items = array(); + +#[ReadOnlyProperty] +#[OrderItemsRelation( 'shipping' )] +public array $shipping_items = array(); + +#[ReadOnlyProperty] +#[OrderItemsRelation( 'fee' )] +public array $fee_items = array(); +``` + +Iterate an order's line items: + +```php +use Wpify\Model\Order; + +$order = $manager->get_model_repository( Order::class )->get( 456 ); +foreach ( $order->line_items as $item ) { + echo $item->name; // result: product names of the order's line items (OrderItemLine[]) +} +``` + +**Used by built-in models:** Order. See the [Order reference](models/order.md). + +> [!NOTE] +> Any `order_item_type` other than the three accepted values throws `\UnhandledMatchError` on first read — the internal `match` has no default arm. + +## Behavior attributes + +### ReadOnlyProperty + +Marker attribute that flags a property as read-only and excludes it from persistence. It has no parameters and no methods — the behavior lives in `Model::__set` and the repositories' save loops. + +From the built-in `Post` model, stacked with a source attribute: + +```php +use Wpify\Model\Attributes\ReadOnlyProperty; +use Wpify\Model\Attributes\SourceObject; + +#[SourceObject] +#[ReadOnlyProperty] +public int $comment_count = 0; +``` + +**Used by built-in models:** MenuItem, Order, Term, Post, Site, Product, User. + +> [!WARNING] +> The guard is "can't overwrite a resolved non-empty value", not "can never set": `Model::__set` throws `ReadOnlyPropertyException` only when the property already has a **non-empty cached value** — assignment succeeds while the value is unset or empty (`0`, `''`, `null`, `[]`). ArrayAccess writes (`$model['prop'] = …`) bypass the readonly check entirely. Either way, `collect_persistable_props()` and the family save loops skip readonly properties, so the value is never persisted. + +## Custom table attributes + +### Column + +Maps a property to a database column of a custom table, carrying both the value resolution (reading the field off the fetched row, with `maybe_unserialize()`) and the DDL definition `CustomTableRepository` uses for auto-migration. This section covers the parameters; the walkthrough is in the [custom tables guide](../guides/custom-tables.md) and the repository half in the [CustomTableRepository reference](custom-table-repository.md). + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `name` | `string` | `''` | Column name; the property name is used when empty. | +| `type` | `string` | `''` | One of the type constants below; inferred from the PHP type when empty (`bool` → BOOLEAN, `int` → INT, `float` → DECIMAL, `string` → VARCHAR, `array`/`object` → TEXT). | +| `params` | mixed | `null` | Length/precision — scalar (`params: 100`) or array (`params: array( 10, 2 )`). | +| `unsigned` | `bool` | `false` | Adds `UNSIGNED`. | +| `nullable` | `bool` | `false` | Emits `NULL` instead of `NOT NULL` (only when `default` is empty). | +| `default` | `string` | `''` | `DEFAULT` clause; double-quoted for VARCHAR/TEXT, raw otherwise — so `default: 'CURRENT_TIMESTAMP'` works for timestamps. | +| `on_update` | `string` | `''` | Adds `ON UPDATE `; such columns are skipped by `save()` (the database maintains them). | +| `auto_increment` | `bool` | `false` | Adds `AUTO_INCREMENT`. | +| `primary_key` | `bool` | `false` | Marks the primary key — used in the `WHERE` for updates and populated with `$wpdb->insert_id` after insert. | +| `unique` | `bool` | `false` | Creates a unique index during migration. | +| `foreign_key` | `array` | empty definition | Foreign key as `array( Column::FOREIGN_TABLE => …, Column::FOREIGN_COLUMN => …, Column::FOREIGN_SETTINGS => … )`; the table name gets `$wpdb->prefix` prepended by the repository. | + +Column type constants, with the length applied when `params` is omitted: + +| Constant | SQL type | Default params | +|---|---|---| +| `Column::TINYINT` | `tinyint` | 4 | +| `Column::INT` | `int` | 11 | +| `Column::BIGINT` | `bigint` | 21 | +| `Column::BOOLEAN` | `boolean` | — | +| `Column::DECIMAL` | `decimal` | (65, 10) | +| `Column::DATE` | `date` | — | +| `Column::DATETIME` | `datetime` | — | +| `Column::TIMESTAMP` | `timestamp` | — | +| `Column::TIME` | `time` | — | +| `Column::CHAR` | `char` | 1 | +| `Column::VARCHAR` | `varchar` | 255 | +| `Column::BLOB` | `blob` | — | +| `Column::TEXT` | `text` | — | +| `Column::ENUM` | `enum` | — | +| `Column::SET` | `set` | — | +| `Column::JSON` | `json` | — | + +Properties of a `BookLoan` custom table model, including a primary key, a foreign key into `wp_posts`, and a database-maintained timestamp: + +```php +use Wpify\Model\Attributes\Column; + +#[Column( type: Column::INT, unsigned: true, auto_increment: true, primary_key: true )] +public int $id = 0; + +#[Column( type: Column::BIGINT, unsigned: true, foreign_key: array( + Column::FOREIGN_TABLE => 'posts', + Column::FOREIGN_COLUMN => 'ID', +) )] +public int $book_id = 0; + +#[Column( type: Column::DATETIME )] +public string $loaned_at = ''; + +#[Column( type: Column::TIMESTAMP, default: 'CURRENT_TIMESTAMP', on_update: 'CURRENT_TIMESTAMP' )] +public string $updated_at = ''; +``` + +**Used by custom models only** — no shipped model uses it; it is consumed by `CustomTableRepository` for schema generation, reads, and writes. + +> [!WARNING] +> `get()` looks the value up on the row object by the **property name**, while `save()` writes using `name`. If `name:` differs from the property name, reads resolve the wrong (or missing) field — keep them identical, or alias the column in SQL. + +> [!NOTE] +> JSON columns (`type: Column::JSON`) are `wp_json_encode()`d on save and decoded to associative arrays on read; every other column value goes through `maybe_serialize()` / `maybe_unserialize()`. Columns with `on_update` set are never written by `save()`. After an insert, the model's primary-key property is set to `$wpdb->insert_id`. + +## Related + +- [Property resolution](../concepts/property-resolution.md) — where attribute `get()` sits in the lazy `__get` flow +- [Persistence](../concepts/persistence.md) — what `save()` does with each attribute's values, per model family +- [Relations guide](../guides/relations.md) — tutorial-style examples for every relation attribute +- [Meta fields guide](../guides/meta-fields.md) — everything `#[Meta]` +- [Model properties guide](../guides/model-properties.md) — accessor methods, aliases, readonly, defaults +- [Custom tables guide](../guides/custom-tables.md) and [CustomTableRepository](custom-table-repository.md) — the `#[Column]` ecosystem +- [Repository](repository.md) — `resolve_property()`, `maybe_convert_to_type()`, `collect_persistable_props()` diff --git a/docs/reference/custom-table-repository.md b/docs/reference/custom-table-repository.md new file mode 100644 index 0000000..afdc461 --- /dev/null +++ b/docs/reference/custom-table-repository.md @@ -0,0 +1,352 @@ +# CustomTableRepository reference + +You land here when you need the exact API of `Wpify\Model\CustomTableRepository` — the abstract base repository that maps a model with `#[Column]`-attributed properties to its own `$wpdb` database table. It handles schema generation, dbDelta-based migration, CRUD, and a structured query builder. For the step-by-step tutorial, see the [custom tables guide](../guides/custom-tables.md); for the `#[Column]` attribute parameters, see the [attributes reference](attributes.md). + +All examples on this page use this bookstore setup — a `BookLoan` model stored in the `wp_book_loans` table: + +```php + 'posts', + Column::FOREIGN_COLUMN => 'ID', + Column::FOREIGN_SETTINGS => 'ON DELETE CASCADE', + ) )] + public int $book_id = 0; + + #[Column( type: Column::VARCHAR, params: 100 )] + public string $borrower_email = ''; + + #[Column( type: Column::DATETIME )] + public string $loaned_at = ''; + + #[Column( type: Column::DATETIME, nullable: true )] + public ?string $returned_at = null; +} + +class BookLoanRepository extends CustomTableRepository { + public function model(): string { + return BookLoan::class; + } + + public function table_name(): string { + return 'book_loans'; + } +} + +$manager = new Manager( new BookLoanRepository() ); +$repo = $manager->get_repository( BookLoanRepository::class ); +``` + +## Constructor + +```php +public function __construct( + private bool $auto_migrate = true, + private bool $use_prefix = true, +) +``` + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `auto_migrate` | `bool` | `true` | Run `migrate()` lazily before every `save()`, `delete()`, and `find()` call (and therefore before `get()`/`query_single()`, which go through `find()`). Pass `false` to control migration yourself. | +| `use_prefix` | `bool` | `true` | Prepend `$wpdb->prefix` to `table_name()` when building SQL. On multisite `$wpdb->prefix` is per-site, so each site gets its own table and its own version option. | + +Disable auto-migration when you want to run the schema migration once, on plugin activation, instead of checking on every request. + +```php +$repo = new BookLoanRepository( auto_migrate: false ); +$manager->register_repository( $repo ); +register_activation_hook( __FILE__, fn () => $repo->migrate() ); +// result: table is created/updated only during activation +``` + +## Abstract methods + +A subclass must implement exactly two methods. + +| Signature | Meaning | +|---|---| +| `table_name(): string` | Table name **without** the WordPress prefix (`'book_loans'`, not `'wp_book_loans'`). | +| `model(): string` | Inherited abstract from [`Repository`](repository.md) — the FQCN of the model class whose `#[Column]` properties define the schema. | + +## Schema and migration + +### `prefixed_table_name(): string` + +Returns `$wpdb->prefix . table_name()` when the repository was constructed with `use_prefix: true` (the default), otherwise the bare `table_name()`. + +```php +echo $repo->prefixed_table_name(); +// result: wp_book_loans +``` + +### `columns(): array` + +Returns (and caches per instance) the column map built by reflecting `#[Column]` attributes (including `Column` subclasses) on the model's properties (all visibilities, not just public): `array`, where `name` falls back to the property name when the attribute's `name` parameter is empty and `type` is the declared PHP type. + +```php +$columns = $repo->columns(); +echo $columns['borrower_email']['name']; +// result: borrower_email +``` + +### `primary_key( ?ModelInterface $model = null ): mixed` + +Without an argument, returns the primary key **column name**; with a model, returns the primary key **value** read from the model's property. Exactly one column must be marked `primary_key: true`, otherwise `PrimaryKeyException` is thrown — composite primary keys are not supported. + +```php +echo $repo->primary_key(); +// result: id +``` + +Unique indexes use the column name as their explicit SQL index name (`UNIQUE KEY code (code)`). This lets `dbDelta()` recognize existing indexes during later schema migrations, including indexes originally created without an explicit name. + +### `migrate(): void` + +Generates a dbDelta-compatible `CREATE TABLE` statement from the `#[Column]` attributes and runs `dbDelta()` when the schema has changed. The version is not a number — it is the `md5()` hash of the generated SQL, stored in the option `custom_table_{table_name}_version` (note: the **unprefixed** table name in the option key). Any change to a `Column` attribute changes the hash and triggers `dbDelta()` on next use. + +```php +$repo->migrate(); +// result: dbDelta() runs CREATE TABLE wp_book_loans (...) if the schema hash changed +``` + +Behavior in detail: + +- Skips silently when the table was already migrated during this request, or when the stored hash matches the current one. +- Loads `wp-admin/includes/upgrade.php` on demand if `dbDelta()` is not defined yet (safe to call on the front end). +- After a successful upgrade, both the stored version and the repository’s cached version reflect the new schema in the same request. +- If `$wpdb->last_error` is non-empty after `dbDelta()`, the new version is **not** stored and **no exception is thrown** — the migration silently retries on the next request. +- All dbDelta quirks apply: removed columns and keys are never dropped, and foreign keys through dbDelta are historically fragile. + +### `transaction( callable $operation ): mixed` + +Prepares this repository's schema, then commits the callback's database writes or rolls them back on a thrown `Throwable`. Existing transactions are joined using a savepoint. Prepare other participating tables before entry. Pending migrations inside a library-managed transaction are refused with `SqlException`. + +See [transactions](transactions.md) for nesting, errors, migration requirements and cache/side-effect limits. + +### `drop_table(): bool` + +Runs `DROP TABLE IF EXISTS` on the prefixed table — typically wired into your plugin's uninstall routine. + +```php +$repo->drop_table(); +// result: true — wp_book_loans is gone +``` + +> [!NOTE] +> `drop_table()` does **not** delete the `custom_table_{table_name}_version` option. If the plugin is reinstalled, the stored hash still matches and `migrate()` skips recreating the table. Delete the option alongside the table: `delete_option( 'custom_table_book_loans_version' )`. + +## CRUD methods + +`create( array $data = array() ): ModelInterface` and `manager( ?Manager $manager = null ): Manager` are inherited unchanged from the base [`Repository`](repository.md) — `create()` builds an in-memory model and never touches the database. + +### `get( mixed $source ): ?ModelInterface` + +Resolves one model. An empty `$source` returns `null`; an instance of the model class is returned as-is; any scalar is treated as a primary-key value and looked up via `query_single()`; an object is trusted as a raw database row and used directly as the model's source — it must expose the primary-key column or `PrimaryKeyException` is thrown. + +```php +$loan = $repo->get( 42 ); +// result: BookLoan with id 42, or null — SQL: SELECT ... FROM wp_book_loans WHERE `id` = '42' LIMIT 1 +``` + +> [!NOTE] +> `get()` never queries the database when given an object — a `stdClass` row is trusted as the source after only a primary-key presence check. A wrong-shaped object yields a model whose properties resolve to null-ish defaults. + +### `query_single( mixed $source ): ?object` + +Fetches the single row whose primary key equals `$source` (`esc_sql()`-escaped, `LIMIT 1`), or `null` when `$source` is empty or no row matches. + +```php +$loan = $repo->query_single( 42 ); +// result: the first find() result for `id` = '42', or null +``` + +> [!NOTE] +> Known limitation: despite the `?object` return type, `query_single()` returns the first element of `find()` — a hydrated **model instance**, not a raw row, because `find()` maps every row through `get()`. + +### `save( ModelInterface $model ): ModelInterface` + +Persists the model as one row: `$wpdb->update()` when the model has a source object (it came from `get()`/`find()`), `$wpdb->insert()` otherwise. Throws `SqlException` with `$wpdb->last_error` when the write fails. + +```php +$loan = $repo->create( array( 'book_id' => 7, 'borrower_email' => 'jane@example.com', 'loaned_at' => '2026-07-26 10:00:00' ) ); +$loan = $repo->save( $loan ); +echo $loan->id; +// result: 1 — SQL: INSERT INTO wp_book_loans (id, book_id, borrower_email, loaned_at, returned_at) VALUES (...) +``` + +Step by step: + +1. Runs `auto_migrate()` first (no-op when constructed with `auto_migrate: false`). +2. Collects column values from the model's properties: the primary-key value goes into the `WHERE` data; `Column::JSON` columns are `wp_json_encode()`d; every other value is `maybe_serialize()`d. Columns with a non-empty `on_update` parameter are **skipped entirely** (intended for database-managed timestamps). +3. `$model->source()` set → `$wpdb->update( $table, $data, $where )`; no source → `$wpdb->insert( $table, array_merge( $where, $data ) )`, and the model's primary-key property is set to `$wpdb->insert_id`. +4. A `false` result throws `SqlException( $wpdb->last_error )`. +5. Unless the `wpify_model_refresh_model_after_save` filter returns `false`, the model is refreshed from a fresh `query_single()` of its primary key — so database-generated values (e.g. `DEFAULT CURRENT_TIMESTAMP`) appear on the returned model. +6. Fires `do_action( 'wpify_model_repository_save_insert' | 'wpify_model_repository_save_update', $model, $repository )`. + +> [!WARNING] +> Insert-vs-update is decided by `$model->source()`, **not** by the primary-key value. A model built by hand (via `create()` or `new`) with an existing primary key still INSERTs — the key is merged into the insert data, producing a duplicate-key error or a duplicate row. Always fetch existing rows through `get()`/`find()` before updating them. + +> [!NOTE] +> After an insert, the new ID is assigned via the primary-key **column** name: `$model->{$repo->primary_key()} = $wpdb->insert_id`. If your primary-key `Column` has a `name` different from the property name, the value lands under the wrong key — keep the primary-key property name and column name identical. + +### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Deletes the model's row by primary key via `$wpdb->delete()`. Returns `false` — without an exception — when the model's primary-key value is empty (e.g. an unsaved model); returns `true` when at least one row was deleted; throws `SqlException` on a SQL error. The `$force_delete` parameter is **unused**. + +```php +$repo->delete( $loan ); +// result: true — SQL: DELETE FROM wp_book_loans WHERE id = 1 +``` + +## Query methods + +### `find( array $args = array() ): array` + +Builds one `SELECT`, runs it through `$wpdb->get_results()`, and hydrates every returned row into a model via `get()` (the row object becomes the model's lazy source). A non-empty `$wpdb->last_error` raises `SqlException`. + +```php +$loans = $repo->find( array( + 'where' => array( 'returned_at' => null ), + 'order_by' => 'loaned_at DESC', + 'limit' => 10, +) ); +// result: BookLoan[] — SQL: SELECT ... FROM wp_book_loans WHERE returned_at IS NULL ORDER BY loaned_at DESC LIMIT 10 +``` + +Recognized argument keys, in the order the SQL is assembled: + +| Key | Type | Effect | +|---|---|---| +| `select` | `string` | Replaces the default `SELECT FROM ` with a custom SELECT (useful together with `join`). Raw SQL. | +| `count` | truthy | Literal `str_replace()` of `SELECT` with `SELECT COUNT(*)` — the generated column list stays in place, so `COUNT(*)` is prepended to it. See the known limitation below. | +| `distinct` | truthy | Rewrites `SELECT` → `SELECT DISTINCT`. | +| `join` | `string` | Raw SQL appended after the SELECT, e.g. `'LEFT JOIN wp_posts ON ...'`. | +| `where` | `string\|array` | Filter conditions — see [the `where` grammar](#the-where-array-grammar). Strings are used verbatim. | +| `order_by` | `string\|array` | `ORDER BY` clause; arrays are joined with `', '` (e.g. `array( 'loaned_at DESC', 'id ASC' )`). Raw SQL. | +| `limit` | `int` | `LIMIT n`. | +| `offset` | `int` | `OFFSET n` — combine with `limit` for pagination. | +| `group_by` | `string\|array` | `GROUP BY`; arrays joined with `', '`. Raw SQL. See the known limitation below. | +| `having` | `string\|array` | `HAVING`, same grammar as `where`. | + +Pagination is plain `limit` + `offset` — there is no `find_paginated()` on custom table repositories. + +```php +$page_2 = $repo->find( array( 'order_by' => 'id ASC', 'limit' => 25, 'offset' => 25 ) ); +// result: rows 26-50 as BookLoan[] +``` + +> [!WARNING] +> The string forms of `where` and `having`, plus `select`, `join`, `order_by`, and `group_by`, are raw SQL — **nothing is escaped**. Only array-form `where`/`having` values go through `esc_sql()`. Never interpolate untrusted input into the raw-string arguments; prefer the array `where` grammar, and `esc_sql()` anything you must pass raw. + +> [!NOTE] +> Known limitation: `group_by` and `having` are appended **after** `ORDER BY`/`LIMIT`/`OFFSET` in the generated SQL, so combining them with ordering or pagination produces invalid MySQL. Use `group_by`/`having` alone, or fall back to a raw `select`. + +> [!NOTE] +> Known limitation: the `count` flag string-replaces `SELECT` with `SELECT COUNT(*)` while keeping the generated column list, producing `SELECT COUNT(*) wp_book_loans.id,... FROM ...` — invalid MySQL. With the built-in select, `find( array( 'count' => true ) )` therefore always throws `SqlException`. Even with a custom `select` whose rewrite happens to stay valid, the rows are still mapped through `get()` — you never receive an integer. For a real count, run raw SQL in a repository subclass via the protected `db()` helper (returns the global `wpdb`). + +### `find_all( array $args = array() ): array` + +Alias for `find( $args )` — identical behavior and arguments. + +```php +$all = $repo->find_all(); +// result: every row in wp_book_loans as BookLoan[] +``` + +### `find_by_ids( array $ids ): array` + +Runs `find()` with `where` set to `" IN (id1,id2,...)"`. + +```php +$loans = $repo->find_by_ids( array( 1, 2, 3 ) ); +// result: BookLoan[] — SQL: ... WHERE (id IN (1,2,3)) +``` + +> [!WARNING] +> The IDs are joined into the SQL **unescaped** — pass trusted integers only, never request input. (The docblock mentions composite keys, but `primary_key()` enforces exactly one primary-key column, so composite keys are not actually supported.) + +## The `where` array grammar + +The `where` (and `having`) argument is transformed into SQL by these rules. Clauses are joined with `AND` by default. + +| Entry shape | Interpreted as | Emitted SQL | +|---|---|---| +| whole value is a `string` | raw SQL | used verbatim, unescaped | +| int key ⇒ `'AND'` / `'OR'` | glue token | switches the glue for the *next* clause; when it is the first entry, it becomes the default glue for the whole group | +| int key ⇒ other `string` | raw SQL fragment | wrapped in `( ... )` | +| int key ⇒ `array` | nested condition group | transformed recursively, wrapped in `( ... )` | +| string key ⇒ value | column condition | key is split on the first whitespace into `column` and `operator` (upper-cased); no operator defaults to `=`, or `IN` when the value is an array | + +Values in column conditions are converted as follows: + +| Value | Conversion | +|---|---| +| `bool` | `TRUE` / `FALSE` | +| `string` | quoted and `esc_sql()`-escaped | +| string starting with `SELECT` | treated as a subquery, wrapped in `( ... )`; when the "column" is `EXISTS`/`NOT EXISTS`, the operator is dropped | +| string with `LIKE` operator | `%` wildcards preserved; the segments between them are `esc_sql()`-escaped | +| `array` | `(v1,v2,...)`, each element converted recursively — enables `IN` / `NOT IN` | +| 2-element `array` with `BETWEEN` / `NOT BETWEEN` | `v1 AND v2`; any other value shape throws `SqlException` | +| `null` | `NULL`, and the operator is switched to `IS` unless it is already `IS` / `IS NOT` | +| numeric | passed through as-is | +| anything else | `''` | + +One expression covering most of the grammar: + +```php +$loans = $repo->find( array( + 'where' => array( + 'borrower_email LIKE' => '%@example.com', + 'book_id' => array( 7, 8, 9 ), + 'returned_at' => null, + 'loaned_at BETWEEN' => array( '2026-01-01', '2026-06-30' ), + array( 'OR', 'id >' => 100, 'book_id' => 7 ), + ), +) ); +// result: ... WHERE borrower_email LIKE '%@example.com' AND book_id IN (7,8,9) +// AND returned_at IS NULL AND loaned_at BETWEEN '2026-01-01' AND '2026-06-30' +// AND (id > 100 OR book_id = 7) +``` + +## Hooks + +| Hook | Type | Signature | +|---|---|---| +| `wpify_model_refresh_model_after_save` | filter | `( bool $refresh = true, ModelInterface $model, CustomTableRepository $repo )` — return `false` to skip the post-save re-query. | +| `wpify_model_repository_save_insert` | action | `( ModelInterface $model, CustomTableRepository $repo )` — after a successful insert. | +| `wpify_model_repository_save_update` | action | `( ModelInterface $model, CustomTableRepository $repo )` — after a successful update. | + +## Exceptions + +All library exceptions live in the `Wpify\Model\Exceptions` namespace. + +| Exception | Thrown when | +|---|---| +| `SqlException` | `$wpdb` reports an error during `find()`, `save()`, or `delete()`; also for a malformed `BETWEEN` value (not a 2-element array). Carries `$wpdb->last_error` as the message for database errors; the malformed-`BETWEEN` case carries its own descriptive message. | +| `PrimaryKeyException` | The model does not have exactly one `#[Column( primary_key: true )]` property, or an object passed to `get()` lacks the primary-key column. | +| `RepositoryNotInitialized` | `manager()` is called (directly or during model hydration) on a repository that was never registered with [the Manager](manager.md). | +| `KeyNotFoundException` | Declared in the `@throws` docblocks of `get()`, `find()`, and `save()`, but no current code path raises it. | +| `ReflectionException` | PHP core exception — the model class cannot be reflected (e.g. `model()` returns a nonexistent class). | + +## Related + +- [Custom tables guide](../guides/custom-tables.md) — the full `BookLoan` walkthrough, including the `#[Column]` type constants +- [Attributes reference](attributes.md) — the `#[Column]` parameter table +- [Repository reference](repository.md) — the shared `create()` / `manager()` / coercion contract +- [Manager reference](manager.md) — registering the repository +- [Model reference](model.md) — the model API the hydrated instances expose +- [Persistence concepts](../concepts/persistence.md) — how `save()` works across all model families +- [Troubleshooting](../guides/troubleshooting.md) — including "insert created a duplicate row" + +When reusing a repository across `switch_to_blog()` calls, schema SQL, version and migration caches reset when its physical table changes. Each shop therefore checks/migrates its own prefixed table. Prepare the participating shop’s tables before entering a transaction. diff --git a/docs/reference/manager.md b/docs/reference/manager.md new file mode 100644 index 0000000..c54cd2b --- /dev/null +++ b/docs/reference/manager.md @@ -0,0 +1,148 @@ +# The Manager + +`Wpify\Model\Manager` is the registry that wires model classes to their repositories: models hold the data, repositories talk to WordPress, the Manager wires them together. Every model resolves its repository (and its relations' repositories) through the Manager, so you create one shared instance early in your plugin and pass it around. + +## Constructor + +```php +public function __construct( ...$dependencies ) +``` + +The constructor is variadic: it first instantiates and registers the 18 built-in repositories (see the table below), then registers every argument that implements `RepositoryInterface`. Constructing a Manager makes no database or WordPress calls — repositories hold no state until used. + +```php +use Wpify\Model\Manager; + +$manager = new Manager(); // result: Manager with the 18 built-in repositories registered +``` + +To use custom models, pass their repositories as constructor arguments — because they register after the defaults, a custom repository whose `model()` returns a built-in model class overrides the default mapping for that model. + +```php +use Wpify\Model\Manager; + +$manager = new Manager( new BookRepository(), new GenreRepository() ); // result: Manager with 18 built-in + 2 custom repositories +``` + +> [!NOTE] +> Arguments that do not implement `RepositoryInterface` are silently ignored. This is convenient when a DI container sprays dependencies into the constructor, but it also means a typo'd argument (say, a model instance instead of a repository) fails without any error — the repository simply never gets registered. + +### Built-in repositories + +These 18 repositories are registered by the constructor, each keyed both by its own class name and by the model class its `model()` method returns. All classes live in the `Wpify\Model` namespace. + +| Repository | Model class | Requires | +|---|---|---| +| `AttachmentRepository` | [`Attachment`](models/post.md) | — | +| `CategoryRepository` | [`Category`](models/term.md) | — | +| `CommentRepository` | [`Comment`](models/comment.md) | — | +| `MenuItemRepository` | [`MenuItem`](models/menu.md) | — | +| `MenuRepository` | [`Menu`](models/menu.md) | — | +| `OrderRepository` | [`Order`](models/order.md) | WooCommerce | +| `OrderItemRepository` | [`OrderItem`](models/order.md) | WooCommerce | +| `OrderItemLineRepository` | [`OrderItemLine`](models/order.md) | WooCommerce | +| `OrderItemShippingRepository` | [`OrderItemShipping`](models/order.md) | WooCommerce | +| `OrderItemFeeRepository` | [`OrderItemFee`](models/order.md) | WooCommerce | +| `PageRepository` | [`Page`](models/post.md) | — | +| `PostRepository` | [`Post`](models/post.md) | — | +| `PostTagRepository` | [`PostTag`](models/term.md) | — | +| `ProductRepository` | [`Product`](models/product.md) | WooCommerce | +| `ProductCatRepository` | [`ProductCat`](models/product.md) | WooCommerce | +| `SiteRepository` | [`Site`](models/site.md) | Multisite | +| `TermRepository` | [`Term`](models/term.md) | — | +| `UserRepository` | [`User`](models/user.md) | — | + +> [!IMPORTANT] +> Requires WooCommerce / multisite: the flagged repositories are registered unconditionally — instantiation is harmless — but *using* them requires WooCommerce (respectively multisite) to be active. Without it, the first repository call fails with a PHP fatal error (e.g. `Call to undefined function wc_get_product()`), not a catchable library exception. See the [WooCommerce guide](../guides/woocommerce.md) and the [multisite guide](../guides/multisite.md). + +`CustomTableRepository` is **not** auto-registered — pass a configured instance to the constructor or `register_repository()` yourself. See the [CustomTableRepository reference](custom-table-repository.md). + +## register_repository() + +```php +public function register_repository( RepositoryInterface $repository ): void +``` + +Registers a repository after the Manager has been constructed — the equivalent of passing it as a constructor argument. The Manager injects itself into the repository via `$repository->manager( $this )`, then indexes the repository under both its own class name and the model class returned by `$repository->model()`. + +```php +use Wpify\Model\Manager; + +$manager = new Manager(); +$manager->register_repository( new BookRepository() ); + +echo get_class( $manager->get_repository( BookRepository::class ) ); // result: BookRepository +``` + +> [!NOTE] +> One repository per model class, last registration wins. Registering a second repository whose `model()` returns the same model class replaces the model mapping (the previous repository stays reachable via `get_repository()`). This is also how you override a built-in: register your own repository whose `model()` returns e.g. `Wpify\Model\Post::class`. + +## get_repository() + +```php +public function get_repository( string $repository_class ) +``` + +Looks up a registered repository by its **repository** class name and returns it (no return type is declared; the docblock templates it, so IDEs infer the concrete class from the `::class` argument). Use it whenever you need a repository and you know which class you want. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); + +echo $posts->get( 1 )->title; // result: Hello world! +``` + +At the WordPress layer, `$posts->get( 1 )` loads the post via `get_post()` — the Manager itself never touches the database. + +> [!WARNING] +> If the class was never registered, `get_repository()` lazily does `new $repository_class( $this )` and caches the instance — **without** calling `register_repository()`. The base `Repository` has no constructor, so the Manager is never injected: the instance throws `RepositoryNotInitialized` the moment it needs its Manager, and models cannot find it via `get_model_repository()`. Always register custom repositories first, via constructor arguments or `register_repository()`, and treat `get_repository()` purely as a lookup. + +## get_model_repository() + +```php +public function get_model_repository( string $model ): RepositoryInterface +``` + +Returns the repository responsible for the given **model** class — the lookup every model performs internally in its constructor and that relation attributes use to load related models. The match is an exact string comparison with no inheritance walking, so a model subclass (e.g. `Book extends Post`) needs its own registered repository. + +```php +use Wpify\Model\Manager; +use Wpify\Model\Post; + +$manager = new Manager(); + +echo get_class( $manager->get_model_repository( Post::class ) ); // result: Wpify\Model\PostRepository +``` + +When no repository is registered for the class, it throws `RepositoryNotFoundException` with the message ``Repository for model `X` not found.`` — see [troubleshooting](../guides/troubleshooting.md). + +> [!NOTE] +> The two getters take different arguments: `get_repository()` takes a **repository** class (`BookRepository::class`), `get_model_repository()` takes a **model** class (`Book::class`). Swapping them is a common mistake — a repository class passed to `get_model_repository()` throws `RepositoryNotFoundException`, and a model class passed to `get_repository()` does not fail at all: the lazy instantiation above happily constructs the model (the Manager is accepted as its first constructor argument), caches it, and returns a **model** instance where you expected a repository. The first repository method you then call on it fails. + +## get_repositories() + +```php +public function get_repositories(): array +``` + +Returns all registered repositories as an array keyed by repository class name — useful for debugging what a given Manager instance knows about. + +```php +use Wpify\Model\Manager; + +$manager = new Manager(); + +echo count( $manager->get_repositories() ); // result: 18 +``` + +## Related + +- [Repository reference](repository.md) — the shared repository contract (`model()`, `create()`, property resolution, coercion) +- [Model reference](model.md) — the abstract model API and why models require a registered repository +- [Installation](../getting-started/installation.md) — bootstrapping one shared Manager in a plugin +- [Custom post types guide](../guides/custom-post-types.md) — writing and registering `BookRepository` +- [CustomTableRepository reference](custom-table-repository.md) — the one repository you register yourself +- [Troubleshooting](../guides/troubleshooting.md) — `RepositoryNotFoundException`, `RepositoryNotInitialized` and friends diff --git a/docs/reference/model.md b/docs/reference/model.md new file mode 100644 index 0000000..42f20fc --- /dev/null +++ b/docs/reference/model.md @@ -0,0 +1,232 @@ +# Model + +Reference for the abstract `Wpify\Model\Model` class — the base class every model extends. Models hold the data, repositories talk to WordPress, the Manager wires them together: a model never queries the database itself; it resolves its properties lazily through its [repository](repository.md). + +This page is a lookup reference. For the full explanation of how lazy properties resolve, see [Property resolution](../concepts/property-resolution.md); for shaping properties with accessors and attributes, see [Model properties](../guides/model-properties.md). + +## Class overview + +`Wpify\Model\Model` is abstract — you always work with a subclass (built-in models like `Post` and `Term`, or your own). It implements three interfaces: + +| Interface | What it provides | +|---|---| +| `Wpify\Model\Interfaces\ModelInterface` | The model contract: `manager()`, `source()`, `reflection()`, `props()`, `refresh()`, `to_array()` | +| `IteratorAggregate` | `foreach ( $model as $prop => $value )` iteration | +| `ArrayAccess` | `$model['title']` style access | + +The class declares no public properties of its own. Subclasses declare typed public properties decorated with [source attributes](attributes.md); the constructor reads every declared property via reflection — with no visibility filter — and unsets each one, so every later read and write goes through the magic `__get`/`__set` accessors. + +## Constructor + +#### `__construct( Manager $repository_manager, array $data = array() )` + +Builds the per-property metadata registry from the subclass's declared properties and looks up the model's repository from [the Manager](manager.md). The reflection loop applies no visibility filter, so protected and private properties are registered too — model properties are public by convention, not because the constructor skips anything else. Throws `RepositoryNotFoundException` when the exact model class is not registered — a model cannot exist without a registered repository. + +> [!WARNING] +> The `$data` parameter is accepted but **completely ignored** — `new Book( $manager, array( 'title' => 'Dune' ) )` produces an empty model and silently discards the array. Always hydrate through the repository's `create()` instead. + +You rarely construct models directly; let the repository do it. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$repository = $manager->get_repository( PostRepository::class ); +$post = $repository->create( array( 'title' => 'Hello' ) ); +// result: unsaved Post model, $post->title === 'Hello' +``` + +`create()` builds the model in memory only — nothing is written to WordPress until you call the repository's `save()` (see [Persistence](../concepts/persistence.md)). + +## Methods + +### `source( mixed $source = null ): mixed` + +Combined getter/setter for the source object — the raw WordPress object the model wraps (`WP_Post`, `WP_Term`, `WC_Product`, a custom-table row…). Passing a non-null value replaces the source; the current source is always returned. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$source` | `mixed` | `null` | New source object to set; `null` leaves the current one in place | + +Use it when you need the underlying WP object for an API the model does not expose. + +```php +$post = $repository->get( 123 ); // PostRepository::get() loads the post via get_post() +$wp_post = $post->source(); +// result: the WP_Post object for post 123 +``` + +> [!NOTE] +> You cannot reset the source back to `null` through this method — `source( null )` is a read, not a write. + +### `props(): array` + +Returns the model's internal property registry: one metadata array per declared property, including any cached value. Repository authors consume this shape in `resolve_property()` and `collect_persistable_props()` (see [Repository](repository.md)). + +| Key | Meaning | +|---|---| +| `name` | Property name | +| `type` | Declared PHP type name; `'string'` when the property is untyped | +| `readonly` | `true` when the property carries `#[ReadOnlyProperty]` | +| `default` | The property's declared default value (or `null`) | +| `allows_null` | Whether the declared type is nullable; `false` for untyped properties | +| `source` | The property's source attribute instance (`#[SourceObject]`, `#[Meta]`, a relation…); absent when it has none. Only the last source attribute on a property wins | +| `value` | The resolved, cached value; absent until first read, cleared by `refresh()`/`unset()` | + +```php +$props = $post->props(); +echo $props['title']['type']; +// result: 'string' +``` + +### `manager(): Manager` + +Returns [the Manager](manager.md) the model was constructed with. Handy inside `get_*` accessor methods that need another repository. + +```php +use Wpify\Model\UserRepository; + +$users = $post->manager()->get_repository( UserRepository::class ); +// result: the registered UserRepository instance +``` + +### `reflection( ?ReflectionObject $reflection = null ): ReflectionObject` + +Combined getter/setter for the `ReflectionObject` the constructor uses to discover properties. Subclasses can override it to supply a different reflection (for example to expose a parent class's private properties); most code never touches it. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$reflection` | `?ReflectionObject` | `null` | Reflection to set; `null` returns the current one | + +### `refresh( mixed $source = null ): void` + +Clears every cached property value, forcing lazy re-resolution on next access — the documented way to re-read a model after something changed it outside the library. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$source` | `mixed` | `null` | Optional replacement source object; a falsy value keeps the current source | + +```php +update_post_meta( $post->id, 'isbn', '978-0441172719' ); +$post->refresh(); +// result: caches dropped; next property read re-resolves from WordPress +``` + +Pass a fresh source object to swap the underlying WP object at the same time. + +```php +$post->refresh( get_post( $post->id ) ); +// result: caches dropped and the source WP_Post replaced with a fresh copy +``` + +### `to_array( array $props = array(), array $recursive = array() ): array` + +Converts the model to a plain `[ prop => value ]` array. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `$props` | `array` | `array()` | Property names to include; empty means **all** declared properties | +| `$recursive` | `array` | `array()` | Properties whose model values (or arrays of models) are themselves converted via `to_array()` | + +```php +$data = $post->to_array( array( 'id', 'title' ) ); +// result: [ 'id' => 123, 'title' => 'Hello world' ] +``` + +Listing a relation property in `$recursive` converts the related model too, instead of returning a model object. + +```php +$data = $post->to_array( array( 'id', 'title', 'author' ), array( 'author' ) ); +// result: [ 'id' => 123, 'title' => 'Hello world', 'author' => [ 'id' => 1, ... ] ] +``` + +> [!NOTE] +> Calling `to_array()` with no `$props` resolves **every** declared property, including relations — each unresolved property can trigger WordPress queries (`get_post_meta`, term lookups, related-model loads). Pass an explicit `$props` allow-list for cheap serialization. + +## Magic property access + +### `__get( string $name )` + +Reading a property returns the cached value if present; otherwise it asks the repository to resolve it (accessor method → source attribute → type coercion), falls back to the declared default when resolution yields `null`, and caches the result. The full pipeline is documented in [Property resolution](../concepts/property-resolution.md). + +```php +echo $post->title; +// result: 'Hello world' — resolved from WP_Post->post_title on first read, cached after +``` + +Reading a property that is not declared on the model throws `PropertyNotDefinedException`. + +> [!NOTE] +> A resolved value of `null` is not treated as cached (the cache check uses `isset()`), so a property whose value and default are both `null` re-resolves on every read. + +### `__set( string $name, mixed $value )` + +Writing a property checks the `#[ReadOnlyProperty]` guard, calls a `set_{$name}()` method if the model defines one, otherwise coerces the value to the declared type and caches it. `#[AccessorObject]` properties additionally write through to the source object immediately on assignment. `#[Meta]` write-through depends on the model family: WooCommerce models (`Product`, `Order`, `OrderItem`) stage the value into the WC source object via `update_meta_data()` and `Site` writes to the database immediately via `update_site_meta()`, while for post, user, term, and comment models the assignment only updates the cache — their meta is persisted when the repository's `save()` runs. + +```php +$post->title = 'New title'; +// result: cached on the model; written to wp_posts only after $repository->save( $post ) +``` + +> [!NOTE] +> The readonly guard throws `ReadOnlyPropertyException` only when the property already holds a non-empty cached value — an unresolved (or empty) readonly property accepts writes. Details in [Property resolution](../concepts/property-resolution.md). + +### `__isset( $prop )` and `__unset( $prop )` + +`isset()` reports whether the property is **declared** on the model — not whether it currently holds a value. `unset()` clears only the cached value; the property stays declared and re-resolves on the next read. + +```php +isset( $post->title ); // result: true — 'title' is a declared property +unset( $post->title ); // result: cache cleared; next read re-resolves from the source +``` + +## ArrayAccess and iteration + +Models can be read and written with array syntax and iterated with `foreach`. + +| Operation | Behavior | +|---|---| +| `$model['title']` | Same lazy resolution as `$model->title`; unknown keys return `null` instead of throwing | +| `$model['title'] = $v` | Writes the raw value straight into the cache — **bypasses** readonly checks, `set_*` setters, type coercion, and meta/accessor write-through | +| `isset( $model['title'] )` | `true` when the property is declared, regardless of value | +| `unset( $model['title'] )` | Clears the cached value only | +| `foreach ( $model as $k => $v )` | Iterates over `to_array()` — fully resolves the model first | + +```php +echo $post['title']; +// result: 'Hello world' — same value as $post->title +``` + +> [!WARNING] +> `$model['prop'] = $value` skips every guard the object syntax enforces: no readonly check, no type coercion, no `set_*` hook, no write-through. Prefer `$model->prop = $value` unless you deliberately need a raw cache write. + +> [!NOTE] +> Iterating a model (`foreach`, `iterator_to_array()`) calls `to_array()` with no allow-list, resolving every property and relation — potentially many queries per model. + +## Exceptions + +All library exceptions extend `Wpify\Model\Exceptions\ModelException`, so `catch ( ModelException $e )` catches everything. `Model` itself throws: + +| Exception | Thrown by | When | +|---|---|---| +| `RepositoryNotFoundException` | `__construct` | The model class has no registered repository in the Manager | +| `PropertyNotDefinedException` | `__get` | Reading a property that is not declared on the model | +| `ReadOnlyPropertyException` | `__set` | Writing a `#[ReadOnlyProperty]` property that already holds a non-empty cached value | + +> [!NOTE] +> Known limitation: writing to an *undeclared* property does not throw `PropertyNotDefinedException` — only reads do. The write emits "Undefined array key" PHP warnings but silently succeeds, creating a phantom cache entry for the misspelled name; later reads of that name return the stored value instead of throwing, so the typo is masked rather than reported. Only reading an undeclared property that was never written throws. + +See [Troubleshooting](../guides/troubleshooting.md) for the error-message-to-fix map. + +## Related + +- [Property resolution](../concepts/property-resolution.md) — the full `__get`/`__set` pipeline +- [Persistence](../concepts/persistence.md) — what `save()`/`delete()` do per model family +- [Architecture](../concepts/architecture.md) — how models, repositories, and the Manager fit together +- [Repository](repository.md) — the shared repository contract (`create()`, `resolve_property()`, coercion) +- [Manager](manager.md) — registering and looking up repositories +- [Attributes](attributes.md) — every source and relation attribute +- [Model properties](../guides/model-properties.md) — accessors, readonly, defaults, `to_array()` patterns + +`ModelException` also accepts an optional fourth constructor argument, `?Throwable $previous`, without changing the existing third `WP_Error` argument. Transaction rollback errors use it to retain the original failure through `getPrevious()`. diff --git a/docs/reference/models/comment.md b/docs/reference/models/comment.md new file mode 100644 index 0000000..6f09fd6 --- /dev/null +++ b/docs/reference/models/comment.md @@ -0,0 +1,154 @@ +# Comment models + +You land here when you read, create, or moderate WordPress comments through wpify/model. The `Comment` model wraps a `WP_Comment` object (a row in `wp_comments`) and is served by `CommentRepository`. + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Comment` | `Wpify\Model\CommentRepository` | `WP_Comment` | `wp_comments` (+ `wp_commentmeta` for subclasses with `#[Meta]` props) | + +## Properties + +`Comment` flattens and renames the `WP_Comment` fields (`comment_author` becomes `author_name`, and so on). All properties resolve lazily from the source object — see [property resolution](../../concepts/property-resolution.md). + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `comment_ID` | No declared default; coerces to `0` on an unsaved model. | +| `post_id` | `int = 0` | `comment_post_ID` | ID of the post the comment belongs to. | +| `author_name` | `string = ''` | `comment_author` | | +| `author_email` | `string = ''` | `comment_author_email` | | +| `author_url` | `string = ''` | `comment_author_url` | | +| `author_ip` | `string = ''` | `comment_author_IP` | | +| `date` | `string = '0000-00-00 00:00:00'` | `comment_date` | `YYYY-MM-DD HH:MM:SS`. Reads `''` on an unsaved model — see [Gotchas](#gotchas). | +| `date_gmt` | `string = '0000-00-00 00:00:00'` | `comment_date_gmt` | Reads `''` on an unsaved model. | +| `content` | `string` | `comment_content` | No declared default; coerces to `''` on an unsaved model. | +| `karma` | `int = 0` | `comment_karma` | | +| `approved` | `bool = false` | `comment_approved` | Lossy — see the note below. | +| `http_agent` | `string = ''` | `comment_agent` | Author's HTTP user agent. | +| `type` | `string = 'comment'` | `comment_type` | E.g. `comment`, `pingback`, `trackback`. | +| `comment_parent_id` | `int = 0` | `comment_parent` | Parent comment ID for threaded comments. | +| `author_user_id` | `int = 0` | `user_id` | ID of the registered user who wrote the comment; `0` for guests. | +| `children` | `array = []` (protected) | `children` | Effectively dead — see [Gotchas](#gotchas). | + +> [!NOTE] +> **`$approved` conflates spam and trash with `true`.** WordPress stores `comment_approved` as `'0'`, `'1'`, `'spam'`, or `'trash'`; the `bool` coercion maps both `'spam'` and `'trash'` to `true` (any non-empty string except `'false'` is truthy). Do not use `$approved` to distinguish approved comments from spammed or trashed ones — read `$comment->source()->comment_approved` for the raw status. + +To store comment meta, subclass `Comment` and add `#[Meta]` properties; they are read via `get_comment_meta()` and written at save time. See the [meta fields guide](../../guides/meta-fields.md). + +## Repository methods + +Only comment-specific behavior is documented here; `create()`, `model()`, and the shared contract live on the [Repository reference](../repository.md). Get the repository from [the Manager](../manager.md), which registers `CommentRepository` by default. + +```php +use Wpify\Model\CommentRepository; +use Wpify\Model\Manager; + +$manager = new Manager(); +$comments = $manager->get_repository( CommentRepository::class ); +// result: CommentRepository instance wired to the Manager +``` + +#### `find( array $args = array() ): array` + +Passes `$args` straight through to `get_comments()` — every argument WordPress supports works here, with no changed defaults — and wraps each result in a `Comment` model. See the [querying guide](../../guides/querying.md) for cross-family patterns. + +```php +$pending = $comments->find( array( 'status' => 'hold' ) ); + +echo count( $pending ); // result: 3 +``` + +> [!WARNING] +> Do not pass `count => true` or `fields => 'ids'` in `$args`. `get_comments()` then returns an integer or a list of IDs instead of `WP_Comment` objects: a count makes the wrapping loop emit a warning and `find()` silently return an empty array, and an ID list triggers one extra `get_comment()` query per result. Use `find()` only for full model results. + +#### `find_all( array $args = array() ): array` + +Alias for `find()` with no extra defaults; call it with no arguments to fetch every approved and pending comment — `get_comments()` defaults to status `'all'`, which includes `comment_approved` `'0'` and `'1'` and excludes spam and trash. + +```php +$all = $comments->find_all(); + +echo count( $all ); // result: 27 +``` + +#### `find_by_post_id( int $post_id ): array` + +Shorthand for `find( array( 'post_id' => $post_id ) )` — all comments on one post. + +```php +foreach ( $comments->find_by_post_id( 42 ) as $comment ) { + echo $comment->author_name . ': ' . $comment->content; +} +// result: Jane: Nice post! +``` + +#### `find_by_ids( array $ids, array $args = array() ): array` + +Runs `find()` with `comment__in => $ids` merged over `$args`, so the ID list always wins. + +```php +$picked = $comments->find_by_ids( array( 3, 7, 15 ) ); + +echo count( $picked ); // result: 3 +``` + +#### `get( mixed $source ): ?ModelInterface` + +Returns one `Comment`. Accepts an existing `Comment` model (returned as-is), a `WP_Comment` object, or anything `get_comment()` accepts — an ID or numeric string. Returns `null` when nothing matches. + +```php +$comment = $comments->get( 15 ); + +echo $comment->author_name; // result: Jane +``` + +#### `save( ModelInterface $model ): ModelInterface` + +Persists the model: `wp_update_comment()` when the model has an ID, `wp_insert_comment()` otherwise. Meta properties of subclasses ride along in the `comment_meta` key of the insert/update array. Throws `CouldNotSaveModelException` on failure. + +```php +$comment = $comments->create( array( + 'post_id' => 42, + 'author_name' => 'Jane', + 'content' => 'Nice post!', + 'approved' => true, +) ); +$comments->save( $comment ); + +echo $comment->id; // result: 16 +``` + +> [!WARNING] +> `wp_insert_comment()` is WordPress's low-level API — unlike `wp_new_comment()` it performs **no validation, sanitization, flood check, or moderation**. Whatever you put in the model lands in the database as-is. Sanitize untrusted input yourself before saving. + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Calls `wp_delete_comment( $model->id, $force_delete )`. Unlike `TermRepository`, `UserRepository`, and `SiteRepository` — which accept `$force_delete` but ignore it — this repository passes it through: `true` (the default) deletes permanently, `false` moves the comment to trash. + +```php +$comments->delete( $comment, false ); // result: true (comment moved to trash) +``` + +## Behavior notes + +What `save()` does, step by step: + +- Collects writable properties: `#[SourceObject]` values into the insert/update array keyed by their WordPress field names (`comment_ID`, `comment_post_ID`, …), `#[Meta]` values (subclasses only) into `$data['comment_meta']`. See [persistence](../../concepts/persistence.md) for the shared collection flow. +- Casts every boolean in the array to `int` — `wpdb` stringifies `false` to `''` instead of `'0'`, which breaks comment status queries. `approved => true` is therefore saved as `comment_approved = 1`. +- Dispatches: collected `comment_ID > 0` → `wp_update_comment( $data, true )` (second argument makes it return `WP_Error` on failure); otherwise `wp_insert_comment( $data )`. +- Throws `CouldNotSaveModelException` on a `WP_Error` or a `false` result. The exception carries the message only — `get_wp_error()` returns `null` (unlike Term and Site saves). +- On insert, assigns `$model->id` directly from the return value — the new ID is on the model even when the post-save refresh is disabled. +- Refreshes the model from a fresh `get_comment( $model->id )` unless the `wpify_model_refresh_model_after_save` filter returns `false`. +- Fires `do_action( 'wpify_model_repository_save_insert' )` or `…_save_update` with the model and repository. + +Property reads are cached per model after first resolution; `unset( $comment->prop )` clears one cached value, `$comment->refresh()` clears them all. See the [Model reference](../model.md). + +## Gotchas + +- **`$approved` is a lossy bool** — spam and trash read as `true` (see the note under [Properties](#properties)). Fix: read the raw status from `$comment->source()->comment_approved`. +- **`$children` always resolves to `array()`.** The property is declared `protected` (still readable via magic `__get`), but `WP_Comment` keeps its own `children` protected and its `__isset()` only answers for post fields, so the source lookup always misses. It is still a writable `#[SourceObject]` prop, so `save()` includes a `children` key in the data array — WordPress ignores it harmlessly. Fix: query replies yourself with `find( array( 'parent' => $comment->id ) )`. +- **`get( null )` may not return `null`.** `get_comment( null )` falls back to the global `$comment` when one is set, so in template contexts `get( null )` can return the "current" comment. Fix: guard your input before calling `get()`. +- **`save()` on a new comment persists an empty date.** An unsaved model reads `date`/`date_gmt` as `''` (not the declared default — non-nullable string props coerce a missing source value to `''`), and `wp_insert_comment()` only fills `current_time( 'mysql' )` when `comment_date` is absent from the data array. The repository always sends it, so the row ends up with the zero date `'0000-00-00 00:00:00'`. Fix: set `date` and `date_gmt` explicitly (e.g. `current_time( 'mysql' )` / `current_time( 'mysql', true )`) before saving a new comment. +- **No `WP_Error` on save failure** — `CouldNotSaveModelException::get_wp_error()` returns `null` for comments. Fix: rely on `getMessage()`. +- **Unvalidated inserts** — `save()` uses `wp_insert_comment()`, which skips all of `wp_new_comment()`'s checks. Fix: sanitize and validate untrusted data before assigning it to the model. diff --git a/docs/reference/models/menu.md b/docs/reference/models/menu.md new file mode 100644 index 0000000..cd80d62 --- /dev/null +++ b/docs/reference/models/menu.md @@ -0,0 +1,154 @@ +# Menu models + +You'd land here to look up the API of navigation menu models: `Menu`, `MenuItem`, and their repositories. For a task-oriented walkthrough (fetching a menu by theme location, rendering a nav), see the [menus guide](../../guides/menus.md). + +`Menu` wraps a `WP_Term` in the `nav_menu` taxonomy and is served by `MenuRepository`. `MenuItem` wraps a `nav_menu_item` post (decorated by WordPress core's `wp_setup_nav_menu_item()`) and is served by the internal `MenuItemRepository`. Both need only WordPress core — no WooCommerce, no multisite. + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Menu` | `Wpify\Model\MenuRepository` | `WP_Term` (taxonomy `nav_menu`) | `wp_terms` + `wp_term_taxonomy` | +| `Wpify\Model\MenuItem` | `Wpify\Model\MenuItemRepository` (internal) | decorated `WP_Post` (post type `nav_menu_item`) | `wp_posts` + `wp_postmeta` | + +> [!NOTE] +> `MenuItemRepository` is marked `@internal` — don't use it directly, use `MenuRepository` instead. The Manager registers it by default alongside the other built-in repositories, and it must stay registered: resolving `Menu::$children` looks up the repository for `MenuItem::class` and throws `RepositoryNotFoundException` without it. + +## Properties + +### Menu + +`Menu` extends `Term` — it inherits all its properties (`id`, `name`, `slug`, `taxonomy`, `description`, `count`, `permalink`, …); see [Term models](term.md) for the full list. `Menu` adds and overrides: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `children` | `MenuItem[]` | `#[MenuItemsRelation( MenuItem::class )]` | The menu's items as a nested tree. Overrides `Term::$children`. Lazy — resolved on first access, then cached on the model instance. | +| `items` | `MenuItem[]` | `#[AliasOf( 'children' )]` | **Deprecated.** Alias that returns `$menu->children` — use `$children` instead. | + +Reading `$children` is the main reason to fetch a `Menu` — each element is a top-level `MenuItem` whose own `$children` hold the deeper levels. + +```php +$menu = $menu_repo->get( 'primary' ); +foreach ( $menu->children as $item ) { + echo $item->title, ' -> ', $item->url, PHP_EOL; +} +// result: Home -> https://example.com/ (one line per top-level item) +``` + +At the WordPress layer, the first access to `$children` calls `wp_get_nav_menu_items( $menu->id )` once; every raw item is then wrapped as a `MenuItem` model. + +`Menu` also overrides `to_array( array $props = array(), array $recursive = array() ): array` so that `'children'` is always merged into `$recursive` — serializing a menu always produces the item tree as nested plain arrays. + +### MenuItem + +`MenuItem` extends `Post` — it inherits all its properties (`id`, `slug`, `menu_order`, `post_type`, `permalink`, …); see [Post models](post.md) for the full list. `menu_order` is the item's ordering field within the menu. `MenuItem` adds and overrides: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `db_id` | `int` | `#[SourceObject]` | The menu item's own post ID (same value as `id` in practice). | +| `menu_item_parent` | `int` | `#[SourceObject]` | DB ID of the parent menu item; `0` for top-level items. | +| `object_id` | `int` | `#[SourceObject]` | ID of the represented object — a post ID, `term_id`, etc. | +| `object` | `string` | `#[SourceObject]` | Type of the represented object, e.g. `"page"`, `"category"`, `"custom"`. | +| `custom` | `string` | `#[SourceObject]` | The decorated source's `custom` field. | +| `type_label` | `string` | `#[SourceObject]` | Human-readable label of the item type. | +| `title` | `string` | `#[SourceObject]` | The **navigation label**. Overrides `Post::$title`. | +| `url` | `string` | `#[SourceObject]` | The URL the item points to. | +| `target` | `string` | `#[SourceObject]` | Link `target` attribute. | +| `attr_title` | `string` | `#[SourceObject]` | Link `title` attribute. | +| `description` | `string` | `#[SourceObject]` | The menu item's description. | +| `classes` | `array` | `#[SourceObject]` | CSS classes for the item's `
  • ` element. | +| `xfn` | `string` | `#[SourceObject]` | Link relationship (XFN). | +| `children` | `MenuItem[]` | `#[ReadOnlyProperty]` | Child items, one level down. Not resolved from the source — populated once when the parent `Menu::$children` tree is built. Overrides `Post::$children`. | +| `item_children` | `MenuItem[]` | `#[ReadOnlyProperty]` | **Deprecated and non-functional** — always resolves to `array()`. Use `$children`. | +| `is_current` | `bool` | `#[ReadOnlyProperty]`, computed by `get_is_current()` | `true` when `object_id` strictly equals `get_the_ID()`. | +| `is_highlighted` | `bool` | `#[ReadOnlyProperty]`, computed by `get_is_highlighted()` | `true` when the item `is_current` or any descendant (via `$children`) is highlighted. | + +> [!NOTE] +> On every other `Post` subclass, `$title` maps to `post_title`. On `MenuItem` it is the navigation label from the decorated nav item — which is what you want when rendering a menu, but different from the underlying post's `post_title`. + +> [!NOTE] +> `$item_children` is deprecated and always empty: it has no source attribute, no getter, and the tree builder never assigns it. Use `$children`. + +`is_highlighted` is the property to use for "active trail" styling — it bubbles up from the current item through its ancestors. + +```php +foreach ( $menu->children as $item ) { + $class = $item->is_highlighted ? 'current' : ''; +} +// result: $class === 'current' when the item or any of its descendants points at the queried post +``` + +At the WordPress layer, `is_current` compares `object_id` against `get_the_ID()`, so it only works inside the loop and only for post-type items (see [Gotchas](#gotchas)). + +## Repository methods + +The shared repository surface (`create()`, `save()`, `delete()`, `manager()`, property coercion) is documented once on the [Repository reference](../repository.md). `MenuRepository` also inherits every `TermRepository` finder — `find()`, `find_all()`, `find_not_empty()`, `find_children_of()`, `find_child_terms_of()`, `find_terms_of_post()`, `find_by_ids()` — typed to return `Menu[]`; their semantics are documented on [Term models](term.md). Listed below are only the members `MenuRepository` adds or overrides. + +`model()` returns `Menu::class` and `taxonomy()` returns `'nav_menu'` — that's the whole wiring of the repository to its model and taxonomy. + +#### `get( mixed $source ): ?Menu` + +Resolves a `Menu`, trying in order: an existing `Menu` instance (returned as-is), a **theme location key** (a string matched against `get_nav_menu_locations()` and resolved via `wp_get_nav_menu_object()`), then anything `TermRepository::get()` accepts — a `WP_Term`, term ID, slug, or name. Returns `null` when nothing matches. Throws `RepositoryNotInitialized` when the repository was never registered with the Manager. + +```php +use Wpify\Model\Manager; +use Wpify\Model\MenuRepository; + +$menu_repo = ( new Manager() )->get_repository( MenuRepository::class ); +$menu = $menu_repo->get( 'primary' ); // theme location key wins first +$menu = $menu_repo->get( 'main-menu' ); // then term slug or name +$menu = $menu_repo->get( 42 ); // or term ID +// result: Wpify\Model\Menu instance, or null when nothing matches +``` + +At the WordPress layer, a location lookup calls `get_nav_menu_locations()` (cached per repository instance) and `wp_get_nav_menu_object()`; all other sources go through the normal term lookup. + +#### `items( mixed $source, string $return = self::RETURN_OBJECTS ): array` + +Convenience shortcut: calls `get( $source )` and returns the menu's `children`. Returns an empty array when the menu is not found, so you can iterate the result without a null check. The `$return` argument takes one of two class constants: + +| Constant | Value | Meaning | +|---|---|---| +| `MenuRepository::RETURN_OBJECTS` | `'objects'` | `items()` returns `MenuItem[]` models (default). | +| `MenuRepository::RETURN_ARRAY` | `'array'` | `items()` returns nested plain arrays via `to_array()`. | + +```php +$items = $menu_repo->items( 'primary' ); +// result: MenuItem[] — top-level items, deeper levels in each item's ->children +``` + +With `RETURN_ARRAY` you get the whole tree as nested plain arrays — handy for a REST response, but heavier: it runs a full `to_array()` pass that force-resolves every lazy property of the menu and every item. + +```php +use Wpify\Model\MenuRepository; + +$items = $menu_repo->items( 'footer', MenuRepository::RETURN_ARRAY ); +// result: array of nested associative arrays, ready for wp_send_json() +``` + +### MenuItemRepository + +Internal repository binding `MenuItem` to the `nav_menu_item` post type: `model()` returns `MenuItem::class`, `post_types()` returns `array( 'nav_menu_item' )`. It inherits the full `PostRepository` API (see [Post models](post.md)), but you should not call it directly — get items through `Menu::$children` or `MenuRepository::items()`, because items fetched directly lack tree data (see [Gotchas](#gotchas)) and saving them does not round-trip nav fields. + +## Behavior notes + +- **Children tree resolution**, step by step: first access to `Menu::$children` calls `wp_get_nav_menu_items( $menu->id )`; each raw item is wrapped as a `MenuItem` via `MenuItemRepository::get()`; items are then nested by `menu_item_parent` — top-level items (`menu_item_parent == 0`) get their descendants filled recursively into `$children` — and the result is cached on the model instance. +- The one-time write to the read-only `MenuItem::$children` works because read-only enforcement only blocks writes once a non-empty value is cached; see [property resolution](../../concepts/property-resolution.md). +- **Location cache:** `get_nav_menu_locations()` is cached on the repository instance once it returns a non-empty result. While the lookup comes back empty (no menu assigned to any location yet), every `get()` call re-fetches; after the first non-empty fetch, locations registered later are invisible to that instance. +- **`Menu::to_array()`** always serializes `'children'` recursively, regardless of the `$recursive` argument you pass. +- **Saving:** `MenuRepository::save()` (inherited from `TermRepository`) persists term fields only, via `wp_update_term()` / `wp_insert_term()`. `$children` carries a relation attribute, not `#[SourceObject]` or `#[Meta]`, so menu items are never persisted by saving the menu. +- `is_current` and `is_highlighted` are cached on first read, like every model property — evaluate them in the template context where they should be computed, and use `refresh()` to re-evaluate. +- The `#[MenuItemsRelation]` and `#[AliasOf]` attributes used here are documented on the [attributes reference](../attributes.md). + +## Gotchas + +> [!WARNING] +> Menus are effectively read-only through this library. Saving a `Menu` never persists its items (see behavior notes), and saving a `MenuItem` does not round-trip nav-specific fields (`url`, `target`, `attr_title`, …): WordPress core stores them in post meta (`_menu_item_url` etc.), but these props are `#[SourceObject]`, so `PostRepository::save()` passes them as top-level `wp_insert_post()` args, which ignores them. Manage menu contents in wp-admin; use the models for reading and rendering. + +- **A theme location key wins over a slug or name.** If a menu's slug collides with a registered location key, `get()` returns the menu *assigned to that location*, not the menu with that slug. Fix: fetch by term ID when names collide. +- **A location with no menu assigned falls through** to the normal term lookup with the original string, which usually returns `null`. Fix: always null-check the result of `get()`. +- **The location cache is per repository instance** — once a `get()` has fetched a non-empty locations array, locations registered later are not seen by that instance. Fix: register locations (`register_nav_menus()`) before the first lookup, on `after_setup_theme` as usual. +- **`MenuItem::$children` is only filled through the menu tree.** An item fetched directly via `MenuItemRepository` has an empty `$children`, which also makes `is_highlighted` degrade to `is_current`. Fix: always obtain items via `Menu::$children` or `MenuRepository::items()`. +- **`$item_children` is deprecated and always empty.** Fix: use `$children`. +- **`is_current` only makes sense for post-type items inside the loop.** It compares `object_id` to `get_the_ID()`: for a taxonomy item, `object_id` is a `term_id` that can coincidentally equal a post ID (false positive), and outside the loop `get_the_ID()` returns `false`, so `is_current` is always `false`. Fix: for taxonomy items, compare `object_id` against `get_queried_object_id()` yourself. +- **`items( ..., RETURN_ARRAY )` is noticeably heavier** than the default — it force-resolves every lazy property of every item. Fix: stick with `RETURN_OBJECTS` unless you need serializable output. diff --git a/docs/reference/models/order.md b/docs/reference/models/order.md new file mode 100644 index 0000000..480c1b5 --- /dev/null +++ b/docs/reference/models/order.md @@ -0,0 +1,291 @@ +# Order models + +You'll land here when you work with WooCommerce orders and their line, fee, and shipping items as wpify models. `Order` wraps a `WC_Order` and is served by `OrderRepository`; each order item wraps a `WC_Order_Item` subclass and is served by its own repository. + +> [!IMPORTANT] +> Requires WooCommerce. The Manager registers these repositories even when WooCommerce is not active, and the first real call then dies with a PHP `Error` (`Call to undefined function wc_get_order()`) — not a catchable library exception. Guard with `class_exists( 'WooCommerce' )` yourself. See the [WooCommerce guide](../../guides/woocommerce.md). + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Order` | `OrderRepository` | `WC_Order` (source typed `WC_Abstract_Order`) | HPOS order tables (`wp_wc_orders`) or legacy `wp_posts`, whichever the store uses | +| `OrderItem` | `OrderItemRepository` (internal) | `WC_Order_Item` | `wp_woocommerce_order_items` + `wp_woocommerce_order_itemmeta` | +| `OrderItemLine` | `OrderItemLineRepository` | `WC_Order_Item_Product` | same as `OrderItem` | +| `OrderItemFee` | `OrderItemFeeRepository` | `WC_Order_Item_Fee` | same as `OrderItem` | +| `OrderItemShipping` | `OrderItemShippingRepository` | `WC_Order_Item_Shipping` | same as `OrderItem` | + +The repositories only use WooCommerce CRUD functions (`wc_get_order()`, `wc_get_orders()`, `WC_Order::save()`), so they work identically with HPOS and legacy post storage. + +> [!NOTE] +> `OrderItemRepository` is marked `@internal`. The public entry points for order items are the three subclass repositories and — for reading — the `Order` model's relation properties below. + +## Properties + +### Order + +All `#[AccessorObject]` properties resolve from the source `WC_Order`, and assigning them writes through to the matching in-memory `WC_Order` setter immediately when one exists (nothing touches the database until `save()`). `WC_Order` has no `set_weight()`, so assigning `weight` only caches a value on the model and is never persisted. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `#[AccessorObject]` → `WC_Order::get_id()` | `0` for an unsaved order. | +| `parent_id` | `int` | `#[AccessorObject]` → `WC_Order::get_parent_id()` | | +| `weight` | `string` | getter `get_weight()` (wins over its `#[AccessorObject]`) | Computed sum of line-item product weights coerced to string — **not** stored order meta. See gotchas. | +| `total` | `string` | `#[AccessorObject]` → `WC_Order::get_total()` | WooCommerce stores totals as strings; cast with `(float) $order->total` for math. | +| `order_key` | `string` | `#[AccessorObject]` → `WC_Order::get_order_key()` | E.g. `wc_order_h9DpN3qXbXrWm`. | +| `wc_order` | `?WC_Abstract_Order` | getter `get_wc_order()` → `source()` | Read-only. The raw underlying WooCommerce object. | +| `line_items` | `OrderItemLine[]` | `#[OrderItemsRelation]` | Read-only, cached after first read. | +| `shipping_items` | `OrderItemShipping[]` | `#[OrderItemsRelation( 'shipping' )]` | Read-only, cached. | +| `fee_items` | `OrderItemFee[]` | `#[OrderItemsRelation( 'fee' )]` | Read-only, cached. | +| `items` | `array` | getter `get_items()` | Read-only merge of the three collections above. | + +The item collections resolve lazily through `WC_Order::get_items( $type )`, wrapping each raw item via the matching item repository. + +```php +use Wpify\Model\OrderRepository; + +$orders = $manager->get_repository( OrderRepository::class ); +$order = $orders->get( 456 ); + +foreach ( $order->line_items as $item ) { + echo $item->name . ' × ' . (int) $item->quantity . PHP_EOL; +} +// result: Blue T-shirt × 2 +``` + +#### `get_weight( string $unit = 'g' ): float` + +Sums `WC_Product::get_weight()` across the order's line items, converting between the store unit (`get_option( 'woocommerce_weight_unit' )`) and `$unit` for the `g`↔`kg` pair only. + +```php +$kg = $order->get_weight( 'kg' ); +// result: 2.5 +``` + +> [!WARNING] +> Known limitation: `get_weight()` ignores item quantities — three units of a 2 kg product count as 2 kg, not 6 kg. Sum `$item->product->get_weight() * (int) $item->quantity` yourself if you need quantity-aware totals. + +#### `has_shipping_method( $shipping_method_ids ): bool` + +Checks the order's shipping items against one `"{method_id}:{instance_id}"` string or an array of them. + +```php +if ( $order->has_shipping_method( array( 'flat_rate:3', 'local_pickup:1' ) ) ) { + // offer pickup instructions +} +// result: true when any shipping item matches +``` + +#### `get_items(): array` + +Returns `array_merge( $order->line_items, $order->shipping_items, $order->fee_items )` — the same value the lazy `items` property caches. + +```php +$count = count( $order->get_items() ); +// result: 4 (2 line items + 1 shipping + 1 fee) +``` + +### OrderItem + +Base class for all item types. `#[AccessorObject]` properties resolve from the source `WC_Order_Item`. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `#[AccessorObject]` → `WC_Order_Item::get_id()` | `0` for an unsaved item. | +| `type` | `string` | `#[AccessorObject]` → `WC_Order_Item::get_type()` | `line_item`, `shipping`, or `fee`. | +| `name` | `string` | `#[AccessorObject]` → `WC_Order_Item::get_name()` | | +| `quantity` | `string` | `#[AccessorObject]` → `WC_Order_Item::get_quantity()` | WooCommerce returns an int; the declared type coerces it to string — cast with `(int) $item->quantity`. | +| `tax_total` | `float` | `#[AccessorObject( 'total_tax' )]` → `WC_Order_Item::get_total_tax()` | Property name differs from the WooCommerce key. | +| `tax_class` | `string` | `#[AccessorObject]` → `WC_Order_Item::get_tax_class()` | | +| `unit_price_tax_included` | `float` | getter `get_unit_price_tax_included()` | See the `TypeError` gotcha for zero-quantity items. | +| `unit_price_tax_excluded` | `float` | getter `get_unit_price_tax_excluded()` | Same gotcha. | +| `vat_rate` | `float` | getter `get_vat_rate()` | Resolved from the order's tax lines, with arithmetic fallbacks. | +| `vat_rate_id` | `int` | getter `get_vat_rate_id()` | First non-zero tax rate id on the item, else `0`. | +| `wc_order_item` | `?WC_Order_Item` | getter `get_wc_order_item()` → `source()` | Not marked `#[ReadOnlyProperty]`, but assigning it only caches a value and never swaps `source()` — treat it as read-only. | + +#### `get_unit_price( bool $inc_tax = true ): ?float` + +Computes `(total [+ tax]) / quantity` from the source item; returns `null` when the item has no `get_total()` or its quantity is `0`. Prefer this over the two typed properties when a zero-quantity item is possible. + +```php +$item = $order->line_items[0]; +$price = $item->get_unit_price( false ); +// result: 12.5 (or null for a zero-quantity item) +``` + +### OrderItemLine + +Extends `OrderItem` — inherits all its properties. Represents `line_item` rows (products). + +| Property | Type | Source | Notes | +|---|---|---|---| +| `product` | `?WC_Product` | `#[AccessorObject]` → `WC_Order_Item_Product::get_product()` | Raw WooCommerce object — see the note below. | +| `product_id` | `int` | `#[AccessorObject]` → `WC_Order_Item_Product::get_product_id()` | | +| `variation_id` | `int` | `#[AccessorObject]` → `WC_Order_Item_Product::get_variation_id()` | `0` for non-variable products. | + +> [!NOTE] +> `$line->product` is a raw `WC_Product`, not a wpify [`Product`](product.md) model — no repository is registered for the `WC_Product` class, so type coercion returns the WooCommerce object as-is. Wrap it yourself when you need the model API. + +```php +use Wpify\Model\ProductRepository; + +$products = $manager->get_repository( ProductRepository::class ); +$product = $products->get( $order->line_items[0]->product ); +// result: Wpify\Model\Product wrapping the same WC_Product +``` + +### OrderItemFee + +Extends `OrderItem` — inherits all its properties and adds nothing of its own. It exists so fee rows get their own type via `Order::$fee_items`. On a fee, `quantity` resolves to `'1'` (WooCommerce's fixed fee quantity). + +### OrderItemShipping + +Extends `OrderItem` — inherits all its properties. Represents `shipping` rows. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `method_id` | `string` | `#[AccessorObject]` → `WC_Order_Item_Shipping::get_method_id()` | E.g. `flat_rate`. | +| `instance_id` | `string` | `#[AccessorObject]` → `WC_Order_Item_Shipping::get_instance_id()` | Numeric string. | +| `method_title` | `string` | `#[AccessorObject]` → `WC_Order_Item_Shipping::get_method_title()` | Customer-facing label. | + +`Order::has_shipping_method()` matches against `"{method_id}:{instance_id}"` built from these two properties. + +## Repository methods + +Only the methods that differ from the shared contract are listed; `create()`, `manager()`, and property resolution are documented once on the [Repository reference](../repository.md). + +### OrderRepository + +#### `get( mixed $source ): ?Order` + +Resolves, in order: an `Order` model (returned as-is), a `WC_Order` instance, a numeric ID via `wc_get_order()`, and finally a string treated as an **order key** via `wc_get_order_id_by_order_key()`. Returns `null` when nothing matches. + +```php +$order = $orders->get( 456 ); // wc_get_order( 456 ) +$order = $orders->get( 'wc_order_h9DpN3qXbXrWm' ); // by order key +// result: Wpify\Model\Order, or null if not found +``` + +> [!NOTE] +> A string means order key here — not a slug or URL, unlike `PostRepository::get()` or `ProductRepository::get()`. Also, the instance check is against `WC_Order` specifically, so passing a `WC_Order_Refund` object returns `null`. + +#### `find( array $args = array() ): Order[]` + +Passes `$args` straight to `wc_get_orders()` (see WooCommerce's order-query docs for the argument list) and wraps each result via `get()`. + +```php +$processing = $orders->find( array( 'status' => 'processing', 'limit' => 10 ) ); +// result: array of up to 10 Wpify\Model\Order +``` + +#### `find_all( array $args = array() ): Order[]` + +Calls `find()` with a default of `array( 'limit' => -1 )` — every order in the store. + +```php +$all = $orders->find_all(); +// result: Wpify\Model\Order[] — unbounded; avoid on large stores +``` + +#### `find_by_ids( array $ids ): array` + +Calls `get()` once per ID. Unlike `ProductRepository::find_by_ids()`, it takes no `$args` parameter, and IDs that don't resolve produce `null` entries in the result. + +```php +$some = array_filter( $orders->find_by_ids( array( 456, 999999 ) ) ); +// result: [ Order ] — the unknown ID yielded null, removed by array_filter +``` + +#### `save( ModelInterface $model ): Order` + +Runs `persist_{prop}()` hooks for non-readonly properties, then calls `$model->source()->save()` — `WC_Order::save()` writes the order to the database. The model is refreshed from a freshly loaded `wc_get_order()` unless the `wpify_model_refresh_model_after_save` filter returns falsy, then `wpify_model_repository_save_insert` or `_update` fires. + +```php +$order = $orders->get( 456 ); +$order->total = '99.00'; // writes through to WC_Order::set_total() in memory +$orders->save( $order ); // WC_Order::save() persists it +// result: Wpify\Model\Order refreshed from the database +``` + +Throws `CouldNotSaveModelException` when the save result is a `WP_Error` (rare — `WC_Order::save()` normally returns an int). + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Calls `$model->source()->delete( $force_delete )` on the `WC_Order`. + +> [!WARNING] +> The default is `$force_delete = true` — the order is deleted permanently, skipping trash. Pass `false` to trash instead. + +```php +$orders->delete( $order, false ); // moves the order to trash +// result: true +``` + +### Order item repositories + +`OrderItemLineRepository`, `OrderItemFeeRepository`, and `OrderItemShippingRepository` each extend the internal `OrderItemRepository` and override only `model()`. All four share these methods: + +#### `get( mixed $source ): ?OrderItem` + +Accepts a model instance, a `WC_Order_Item`, or a numeric item ID resolved via `WC_Order_Factory::get_order_item()`. There is no string lookup. + +```php +use Wpify\Model\OrderItemLineRepository; + +$items = $manager->get_repository( OrderItemLineRepository::class ); +$item = $items->get( 789 ); // WC_Order_Factory::get_order_item( 789 ) +// result: Wpify\Model\OrderItemLine, or null +``` + +#### `save( ModelInterface $model ): OrderItem` + +Runs `persist_{prop}()` hooks, then `$model->source()->save()` — `WC_Order_Item::save()` writes to `wp_woocommerce_order_items` — and calls `$model->refresh()` to clear cached values. Unlike the order and product repositories, it fires no save actions and skips the refresh filter. + +```php +$item = $order->line_items[0]; +$item->name = 'Renamed line'; // writes through to WC_Order_Item_Product::set_name() +$items->save( $item ); // WC_Order_Item::save() +// result: Wpify\Model\OrderItemLine with caches cleared +``` + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Calls `$model->source()->delete( $force_delete )` on the `WC_Order_Item`, removing the row from the order-items tables. + +```php +$items->delete( $item ); +// result: true +``` + +#### `find()`, `find_all()`, `find_by_ids()` + +> [!NOTE] +> All three always return an empty array — by design, marked `@internal` and "won't be implemented". They are not broken queries to debug. To enumerate items, read them through an `Order` model's `line_items`, `shipping_items`, `fee_items`, or `items` properties. + +```php +$items->find_all(); +// result: array() — always; use $order->line_items instead +``` + +## Behavior notes + +- Assigning an `#[AccessorObject]` property calls the matching WooCommerce setter on the in-memory source object immediately, when one exists — `WC_Order` has no `set_weight()`, so assigning `weight` is a silent no-op at the source level. The database is only touched by `save()`. See [persistence](../../concepts/persistence.md). +- `save()` decides between the `wpify_model_repository_save_insert` and `_update` actions by checking `$model->source()->get_id()` before saving. +- `create()` builds a model **without** a WooCommerce source object — see the warning in the gotchas below before saving one. +- The item collections (`line_items`, `shipping_items`, `fee_items`, `items`) are cached after first read; call `$order->refresh()` after mutating the underlying `WC_Order` to re-resolve them. +- Readonly properties (`wc_order`, the item collections) are never persisted by any save loop. +- Property reads follow the standard lazy flow — cache, `get_*` getter, source attribute, type coercion — described in [property resolution](../../concepts/property-resolution.md). + +## Gotchas + +> [!WARNING] +> `create()` + `save()` fatals. `OrderRepository::create()` returns a model with no source object, and `save()` then dereferences the missing source — a PHP fatal (`Call to a member function get_id() on null`, from the insert/update check that runs before `WC_Order::save()`). Attach a source first (`$order->source( new WC_Order() );`) and set properties *after* attaching, or the values never reach WooCommerce. Details in the [WooCommerce guide](../../guides/woocommerce.md). + +- **`get_weight()` ignores quantities** (known limitation) — multiply by `(int) $item->quantity` yourself. The lazy `weight` property is this same computed sum coerced to string, not WooCommerce order meta. +- **`delete()` is permanent by default** on both orders and items — pass `false` as `$force_delete` to trash an order instead. +- **`$line->product` is a raw `WC_Product`** — wrap it via `ProductRepository::get()` to get a [`Product`](product.md) model. +- **`unit_price_tax_included` / `unit_price_tax_excluded` throw `TypeError` on zero-quantity items** — their getters declare `: float` but delegate to `?float`; call `get_unit_price()` directly and handle `null`. +- **`get_vat_rate()` can throw `DivisionByZeroError`** when the item's total is `0` and a fallback branch runs — guard totals before reading `vat_rate` on free items. +- **`total` and `quantity` are strings** — cast with `(float)` / `(int)` before doing math. +- **`find_by_ids()` returns `null` entries** for unresolvable IDs — wrap it in `array_filter()`. +- **`wc_order_item` looks writable but isn't effectively** — assigning it caches a value without swapping `source()`; treat it as read-only. diff --git a/docs/reference/models/post.md b/docs/reference/models/post.md new file mode 100644 index 0000000..110e38f --- /dev/null +++ b/docs/reference/models/post.md @@ -0,0 +1,303 @@ +# Post models + +You are on this page because you work with posts, pages, or media library items through wpify/model. These models wrap a `WP_Post` source object and are served by `PostRepository` (backed by `WP_Query` and the core post functions), with one repository subclass per post type. + +Looking for `Category` or `PostTag`? Those are term models — see [Term models](term.md). + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Post` | `Wpify\Model\PostRepository` | `WP_Post` (`post_type = post`) | `wp_posts` + `wp_postmeta` | +| `Wpify\Model\Page` | `Wpify\Model\PageRepository` | `WP_Post` (`post_type = page`) | `wp_posts` + `wp_postmeta` | +| `Wpify\Model\Attachment` | `Wpify\Model\AttachmentRepository` | `WP_Post` (`post_type = attachment`) | `wp_posts` + `wp_postmeta` (files on disk are not managed) | + +All three repositories are registered by the Manager's constructor — see [Manager](../manager.md). `PageRepository` and `AttachmentRepository` extend `PostRepository` and override only `model()` and `post_types()`; every method documented below behaves identically on all three. The `@method` docblocks on the subclasses are IDE typing hints only — no `__call` magic is involved. To model your own custom post type the same way, see the [custom post types guide](../../guides/custom-post-types.md). + +## Properties + +All properties resolve lazily through the flow described in [property resolution](../../concepts/property-resolution.md): cached value → `get_*` method → source attribute → type coercion. The source attributes themselves are documented on the [attributes reference](../attributes.md). + +### Post + +| Property | Type | Source | Notes | +|---|---|---|---| +| `$id` | `int` | `#[SourceObject( 'ID' )]` | `0` while unsaved; decides insert vs. update on save | +| `$author_id` | `int` | `#[SourceObject( 'post_author' )]` | Persisted as `post_author` | +| `$author` | `?User` | `#[ManyToOneRelation( 'author_id' )]` | Read-only; loaded via `UserRepository` | +| `$post_date` | `string` | `#[SourceObject]` | Read-only; not persisted | +| `$post_date_gmt` | `string` | `#[SourceObject]` | Read-only; not persisted | +| `$content` | `string` | `#[SourceObject( 'post_content' )]` | Raw DB value — `the_content` filters not applied | +| `$title` | `string` | `#[SourceObject( 'post_title' )]` | Raw DB value — `the_title` filters not applied | +| `$excerpt` | `string` | `#[SourceObject( 'post_excerpt' )]` | Raw stored excerpt | +| `$rendered_excerpt` | `string` | `get_rendered_excerpt()` | Filtered/generated excerpt via `get_the_excerpt()`; not persisted | +| `$post_status` | `string` | `#[SourceObject]` | Default `'publish'` | +| `$comment_status` | `string` | `#[SourceObject]` | Default `'open'` | +| `$ping_status` | `string` | `#[SourceObject]` | Default `'open'` | +| `$password` | `string` | `#[SourceObject( 'post_password' )]` | Persisted as `post_password` | +| `$slug` | `string` | `#[SourceObject( 'post_name' )]` | Persisted as `post_name` | +| `$to_ping` | `string` | `#[SourceObject]` | URLs queued to be pinged | +| `$pinged` | `string` | `#[SourceObject]` | URLs already pinged | +| `$post_modified` | `string` | `#[SourceObject]` | Read-only; not persisted | +| `$post_modified_gmt` | `string` | `#[SourceObject]` | Read-only; not persisted | +| `$content_filtered` | `string` | `#[SourceObject( 'post_content_filtered' )]` | Read-only; not persisted | +| `$parent_id` | *(untyped)* | `#[SourceObject( 'post_parent' )]` | No declared PHP type, so the resolver falls back to `string` — comes back as a numeric string, not an `int` | +| `$parent` | `?Post` | `#[ManyToOneRelation( 'parent_id' )]` | Settable but never persisted — set `$parent_id` instead | +| `$top_parent` | `?Post` | `#[TopLevelPostParentRelation]` | Last ancestor via `get_ancestors()`; not persisted | +| `$children` | `array` (`Post[]`) | `#[ChildPostsRelation]` | `find_child_posts_of()` query on first read; not persisted | +| `$guid` | `string` | `#[SourceObject]` | Feed GUID, not necessarily a URL | +| `$menu_order` | `int` | `#[SourceObject]` | Ordering field | +| `$post_type` | `string` | `#[SourceObject]` | Set automatically by `create()` from the repository | +| `$mime_type` | `string` | `#[SourceObject( 'post_mime_type' )]` | Meaningful for attachments | +| `$comment_count` | `int` | `#[SourceObject]` | Read-only; not persisted | +| `$filter` | `string` | `#[SourceObject]` | Read-only; sanitization level, not a DB field | +| `$permalink` | `string` | `get_permalink()` | Read-only; `get_permalink( $id )` | +| `$featured_image_id` | `int` | `get_featured_image_id()` | Reads `get_post_thumbnail_id()`; persisted via `persist_featured_image_id()` → `set_post_thumbnail()` | +| `$featured_image` | `?Attachment` | `#[ManyToOneRelation( 'featured_image_id' )]` | Read-only; loaded via `AttachmentRepository` | +| `$page_template` | `string` | `#[Meta( '_wp_page_template' )]` | Post meta; written via `meta_input` on save | +| `$categories` | `array` (`Category[]`) | `#[PostTermsRelation( target_entity: Category::class )]` | Persisted on save via `wp_set_post_terms()` | +| `$tags` | `array` (`PostTag[]`) | `#[PostTermsRelation( target_entity: PostTag::class )]` | Persisted on save via `wp_set_post_terms()` | + +Beyond the inherited [Model](../model.md) API, `Post` declares four public methods backing lazy properties: `get_permalink(): string`, `get_featured_image_id(): int`, `get_rendered_excerpt()`, and `persist_featured_image_id( int $featured_image_id ): void` (called automatically during save). + +> [!NOTE] +> All four date properties (`post_date`, `post_date_gmt`, `post_modified`, `post_modified_gmt`) are `#[ReadOnlyProperty]` and skipped on save — you cannot schedule or backdate a post through this model. + +### Page + +`Page extends Post` — inherits all its properties and methods and adds nothing; it exists as a distinct class so the Manager maps it to `PageRepository` (`post_type = page`). Since pages are hierarchical, `$parent`, `$top_parent`, and `$children` are genuinely useful here, and `$page_template` holds the page's template file. + +> [!NOTE] +> `$categories` and `$tags` exist on `Page` (inherited) even though core pages are not registered for those taxonomies. Reading them runs the term query anyway and returns an empty array; assigning non-empty values still triggers `wp_set_post_terms()` on save. + +### Attachment + +`Attachment extends Post` — inherits all its properties and adds: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `$file` | `string` | `#[Meta( '_wp_attached_file' )]` | Relative path under the uploads directory | +| `$metadata` | `?array` | `#[Meta( '_wp_attachment_metadata' )]` | WP's unserialized size/dimension array | +| `$alt` | `?string` | `#[Meta( '_wp_attachment_image_alt' )]` | Image alt text | +| `$url` | `string` | `get_url()` | `wp_get_attachment_url( $id )`; settable but never persisted | + +`Attachment` declares one method, `get_url()`, backing the `$url` property. The inherited `$mime_type` property carries the attachment's MIME type. + +> [!NOTE] +> `$file`, `$metadata`, and `$alt` are declared without default values, so their recorded default is `null`. Missing meta resolves to `''` for the non-nullable `$file` and to `null` for the nullable `$metadata` and `$alt`. + +## Repository methods + +`PostRepository` extends the abstract `Repository`; the shared contract — `create()` hydration, `resolve_property()`, type coercion, `collect_persistable_props()` — is documented once on the [Repository reference](../repository.md). Everything below is what `PostRepository` adds or specializes. + +All snippets assume a repository obtained from the Manager: + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); +``` + +#### `get( mixed $source ): ?Post` + +Loads one post. Resolution order: a `Post` instance is returned as-is → `WP_Post` object → any numeric value (`int` or numeric string, per `is_numeric()`) as an ID via `get_post()` → string as slug via `get_posts( array( 'name' => ... ) )` restricted to the repository's post types → string as URL via `url_to_postid()`. The ID check runs before the slug lookup, so a numeric string like `'2024'` is treated as an ID and a post with a purely numeric slug can never be fetched by slug. Returns `null` when nothing matches — it never throws for a missing post. + +```php +$post = $posts->get( 42 ); +$post = $posts->get( 'hello-world' ); +$post = $posts->get( 'https://example.com/hello-world/' ); +// result: ?Post — null when no post matches +``` + +#### `post_types(): array` + +Returns the post types this repository queries — `array( 'post' )` here, `array( 'page' )` on `PageRepository`, `array( 'attachment' )` on `AttachmentRepository`. This is the override point for [custom post type repositories](../../guides/custom-post-types.md); an override must `return` the array. + +```php +$types = $posts->post_types(); +// result: array( 'post' ) +``` + +#### `create( array $data = array() ): Post` + +Builds an in-memory model, assigns each `$data` key through `__set`, and sets `$post_type` from the repository's single post type. Nothing is written to the database until you call `save()`. Throws `CouldNotSaveModelException` when `post_types()` returns anything other than exactly one type. + +```php +$draft = $posts->create( array( + 'title' => 'Hello', + 'post_status' => 'draft', +) ); +// result: unsaved Post — $draft->id === 0, $draft->post_type === 'post' +``` + +#### `save( ModelInterface $model ): Post` + +Persists the model: calls `wp_insert_post()` when `$model->id` is `0`, otherwise `wp_update_post()`, passing all writable `#[SourceObject]` props as post fields and all `#[Meta]` props as `meta_input`. See [Behavior notes](#behavior-notes) for the full step list. Throws `CouldNotSaveModelException` when WordPress returns a `WP_Error`. + +```php +$draft->content = 'Body text.'; +$saved = $posts->save( $draft ); +// result: wp_insert_post() ran — $saved->id > 0, model refreshed from DB +``` + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Deletes the post — `wp_delete_post( $id, true )` by default, or `wp_trash_post( $id )` when `$force_delete` is `false`. Returns boolean success. + +```php +$posts->delete( $post, false ); // wp_trash_post() — recoverable +$posts->delete( $post ); // result: true — wp_delete_post(), bypasses trash +``` + +#### `find( array $args = array() ): array` + +Runs `new WP_Query( $args )` — every [`WP_Query` argument](https://developer.wordpress.org/reference/classes/wp_query/) passes through — with the defaults `post_type => $this->post_types()`, `post_status => 'any'`, and `posts_per_page => -1`, then maps each result to a model. The query object is stored on the repository instance for `get_pagination()`. + +```php +$drafts = $posts->find( array( 'post_status' => 'draft' ) ); +// result: Post[] — every draft, unpaginated +``` + +#### `find_without_pagination( array $args = array() ): array` + +Same defaults as `find()` but backed by `get_posts()` instead of a stored `WP_Query` — it does not feed `get_pagination()`. Useful when you want to avoid touching the main loop state. + +```php +$all = $posts->find_without_pagination( array( 'author' => 1 ) ); +// result: Post[]; get_pagination() is NOT usable after this call +``` + +#### `find_paginated( array $args = array() ): array` + +Like `find()` but adds the default `paged => get_query_var( 'paged' ) ?: 1` and returns an array with keys `items` (the models), `pagination` (see `get_pagination()`), and `paginate_link` — singular — holding the rendered `paginate_links()` output. + +```php +$result = $posts->find_paginated( array( 'posts_per_page' => 10 ) ); +$page_of_posts = $result['items']; +$total_pages = $result['pagination']['total_pages']; +echo $result['paginate_link']; +// result: 10 Post models + pagination metadata + rendered page links +``` + +#### `find_all( array $args = array() ): array` + +`find()` with `posts_per_page => -1` and `post_status => 'any'` — every post of the repository's type, in any status. + +```php +$everything = $posts->find_all(); +// result: Post[] incl. drafts, pending, private, future +``` + +#### `find_published( array $args = array() ): array` + +`find()` with `post_status => 'publish'` and `posts_per_page => -1` — the variant to use for front-end listings. + +```php +$published = $posts->find_published(); +// result: Post[] — published posts only +``` + +#### `find_all_by_term( ModelInterface $model ): array` + +Takes a term model, resolves its repository through the Manager, and runs `find()` with a `tax_query` on `term_id`. Throws `IncorrectRepositoryException` when the term model's repository has no `taxonomy()` method. This is the query behind `#[TermPostsRelation]` props such as `Category::$posts`. + +```php +use Wpify\Model\CategoryRepository; + +$news = $manager->get_repository( CategoryRepository::class )->get( 'news' ); +$news_posts = $posts->find_all_by_term( $news ); +// result: Post[] assigned to the 'news' category (post_status 'any') +``` + +#### `find_child_posts_of( ModelInterface $model ): array` + +`find( array( 'post_parent' => $model->id ) )` — the query behind the `#[ChildPostsRelation]` `$children` property. + +```php +$children = $posts->find_child_posts_of( $post ); +// result: Post[] whose post_parent is $post->id +``` + +#### `find_by_ids( array $ids, array $args = array() ): array` + +`find()` with `post__in => $ids` merged over `$args` (the `post__in` always wins). Results follow `WP_Query`'s default date ordering, not the order of the given IDs — pass `'orderby' => 'post__in'` to preserve it. + +```php +$picked = $posts->find_by_ids( array( 12, 7, 42 ), array( 'orderby' => 'post__in' ) ); +// result: Post[] in the order 12, 7, 42 +``` + +#### `get_pagination(): array` + +Reads the `WP_Query` stored by the last `find()`/`find_paginated()` on this repository instance and returns `found_posts`, `current_page`, `total_pages`, and `per_page`. Calling it before any such query is a fatal error — see [Gotchas](#gotchas). + +```php +$posts->find( array( 'posts_per_page' => 10, 'paged' => 2 ) ); +$pagination = $posts->get_pagination(); +// result: array( 'found_posts' => 57, 'current_page' => 2, 'total_pages' => 6, 'per_page' => 10 ) +``` + +#### `get_paginate_links( array $args = array() ): array|string|null` + +Runs WordPress's `paginate_links()` with `total` and `current` prefilled from `get_pagination()` — same precondition: a `find()`/`find_paginated()` must have run first. + +```php +$posts->find( array( 'posts_per_page' => 10 ) ); +echo $posts->get_paginate_links(); +// result: the paginate_links() HTML for the last query +``` + +#### `assign_post_to_term( ModelInterface $model, array $terms, bool $append = false ): void` + +Groups the given term models by their `taxonomy` property and calls `wp_set_post_terms()` once per taxonomy. With `$append = false` (the default) the post's existing terms in each affected taxonomy are replaced. This is also what `#[PostTermsRelation]` calls during `save()` for `$categories` and `$tags`. + +```php +use Wpify\Model\PostTagRepository; + +$tag = $manager->get_repository( PostTagRepository::class )->get( 'featured' ); +$posts->assign_post_to_term( $post, array( $tag ) ); +// result: wp_set_post_terms( $post->id, array( $tag->id ), 'post_tag', false ) +``` + +## Behavior notes + +- `save()` runs these steps in order: + 1. `collect_persistable_props()` walks every non-readonly prop: props with a `persist_*` method on the model are called immediately as a side effect (for `Post` that is `persist_featured_image_id()` → `set_post_thumbnail()`); `#[SourceObject]` values are collected into the post data array; `#[Meta]` values into `meta_input`. Reading each collected value triggers lazy resolution, so a save round-trips every `#[SourceObject]`, `#[Meta]`, `persist_*`-backed, and (in step 3) `#[PostTermsRelation]` prop; other relation props (`$children`, `$parent`, `$top_parent`) and plain method-backed props (`$rendered_excerpt`, `Attachment::$url`) are never read during save — values set on them are silently ignored. + 2. `$data['ID'] > 0` → `wp_update_post( $data, true )`; otherwise `wp_insert_post( $data, true )`. A `WP_Error` result becomes a `CouldNotSaveModelException`. + 3. Every writable prop whose source attribute has a `persist()` method is persisted — in practice `#[PostTermsRelation]` for `$categories` and `$tags`, which calls `assign_post_to_term()` → `wp_set_post_terms()`. + 4. Unless the filter `wpify_model_refresh_model_after_save` returns `false`, the model is refreshed from `get_post()` — all cached prop values are dropped and DB state wins. + 5. The action `wpify_model_repository_save_insert` or `wpify_model_repository_save_update` fires with `( $model, $repository )`. +- Property values are resolved lazily and cached per model instance; relation props (`$children`, `$categories`, `$author`, ...) run live DB queries on first read. `unset( $post->prop )` or `$post->refresh()` invalidates the cache. See [persistence](../../concepts/persistence.md) for how this compares across model families. +- `$content` and `$title` are raw DB values; only `$rendered_excerpt` runs through WordPress filters. Apply `the_content`/`the_title` filters yourself when rendering. +- Hooks fired by this family: filter `wpify_model_refresh_model_after_save( bool $refresh, ModelInterface $model, Repository $repository )`; actions `wpify_model_repository_save_insert` / `wpify_model_repository_save_update` `( ModelInterface $model, Repository $repository )`. + +## Gotchas + +> [!WARNING] +> **A featured image set on a new post is silently lost on first save.** `collect_persistable_props()` calls `persist_featured_image_id()` → `set_post_thumbnail( $id, ... )` *before* `wp_insert_post()` runs, while `$model->id` is still `0`. Fix: save once to obtain an ID, then set `$post->featured_image_id` and save again. Updates to existing posts are unaffected. + +> [!WARNING] +> **Categories and tags are re-assigned on every save.** The save loop calls `PostTermsRelation::persist()` for `$categories` and `$tags` even when you never touched them — the lazy read loads the current terms and re-writes them with `wp_set_post_terms( ..., $append = false )`. Any term changes made by other code between load and save are overwritten. (When a relation prop resolves to an empty array, no `wp_set_post_terms()` call is made for it.) + +> [!WARNING] +> **`get_pagination()` and `get_paginate_links()` fatal before any query.** The stored `WP_Query` property is uninitialized until `find()` or `find_paginated()` runs on that repository instance, so calling either getter first raises a PHP `Error` ("typed property ... must not be accessed before initialization"). `find_without_pagination()` does not count. Fix: always query first on the same instance. + +> [!NOTE] +> Every `find*` variant defaults to `post_status => 'any'` — drafts, pending, private, and future posts come back by default. Use `find_published()` (or pass `post_status` yourself) for front-end output. See the [querying guide](../../guides/querying.md) for per-family defaults. + +> [!NOTE] +> `find_paginated()` returns the rendered links under the singular key `paginate_link`, not `paginate_links`. + +> [!WARNING] +> **`AttachmentRepository::save()` does not create real attachments.** It goes through `wp_insert_post()`/`wp_update_post()`, never `wp_insert_attachment()` or `wp_generate_attachment_metadata()` — no file sideloading, no thumbnail generation. Use it to read and update existing attachments (alt text, metadata, parent); create new media through WordPress's own upload APIs. + +> [!NOTE] +> Attachment `find*` calls likely return nothing with the default `post_status => 'any'`, because attachments use the internal `inherit` status, which `WP_Query`'s `'any'` excludes. Pass `array( 'post_status' => 'inherit' )` to `find()`/`find_all()` on `AttachmentRepository`. `get()` by ID is unaffected. + +- `$parent` is settable but setting it does not persist — set `$parent_id` instead. `$parent_id` has no declared PHP type, so the resolver falls back to the `string` type and coerces the value with `strval()` — it comes back as a numeric string (`'5'`, not `5`), so strict comparisons like `$post->parent_id === 0` silently fail; use `==` or cast to `int` first. +- `#[ReadOnlyProperty]` throws only once a non-empty value is already cached, and array-style writes (`$post['permalink'] = ...`) bypass the check entirely — see [property resolution](../../concepts/property-resolution.md). +- `find_by_ids()` does not preserve the given ID order — pass `'orderby' => 'post__in'`. +- `get()` never throws for a missing post; it returns `null`. Numeric strings resolve as IDs; other strings try slug first, then URL. +- `create()` throws `CouldNotSaveModelException` on a repository subclass whose `post_types()` returns zero or multiple types. diff --git a/docs/reference/models/product.md b/docs/reference/models/product.md new file mode 100644 index 0000000..286825a --- /dev/null +++ b/docs/reference/models/product.md @@ -0,0 +1,244 @@ +# Product models + +You are here because you work with WooCommerce products or product categories through wpify/model. `Product` wraps a `WC_Product` (served by `ProductRepository`); `ProductCat` wraps a `WP_Term` in the `product_cat` taxonomy (served by `ProductCatRepository`). + +> [!IMPORTANT] +> Requires WooCommerce. The Manager registers both repositories unconditionally, but the first real call without WooCommerce active dies with a PHP `Error` ("Call to undefined function `wc_get_product()`"), not a catchable library exception. Guard with `class_exists( 'WooCommerce' )` yourself. See the [WooCommerce guide](../../guides/woocommerce.md). + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Product` | `Wpify\Model\ProductRepository` | `WC_Product` | `wp_posts` (post type `product`) via the WC data store | +| `Wpify\Model\ProductCat` | `Wpify\Model\ProductCatRepository` | `WP_Term` (`product_cat`) | `wp_terms` / `wp_term_taxonomy` + `wp_termmeta` | + +`Product` does **not** extend [`Post`](post.md) — it extends `Wpify\Model\Model` directly, and all its data flows through the `WC_Product` object rather than a `WP_Post`. `ProductCat`, by contrast, extends [`Term`](term.md). + +## Properties + +### Product + +Every `#[AccessorObject]` property resolves lazily from the source `WC_Product` via the getter shown, and writes through to the matching `set_*()` setter **at assignment time** — the in-memory `WC_Product` is mutated before you ever call `save()`. See [attributes reference](../attributes.md) for how `#[AccessorObject]` works. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `WC_Product::get_id()` | Default `0`. | +| `parent_id` | `int` | `WC_Product::get_parent_id()` | Default `0`. | +| `type` | `string` | `WC_Product::get_type()` | `simple`, `variable`, … | +| `name` | `string` | `WC_Product::get_name()` | | +| `slug` | `string` | `WC_Product::get_slug()` | | +| `sku` | `string` | `WC_Product::get_sku()` | | +| `price` | `float` | `WC_Product::get_price()` | WC returns a string; coerced to float. Empty price resolves to `0.0`. | +| `regular_price` | `float` | `WC_Product::get_regular_price()` | Same coercion as `price`. | +| `sale_price` | `float` | `WC_Product::get_sale_price()` | Same coercion as `price`. | +| `stock_quantity` | `int` | `WC_Product::get_stock_quantity()` | Default `0`. | +| `is_in_stock` | `bool` | `WC_Product::is_in_stock()` | No `get_is_in_stock()` exists in WC; the accessor falls back to the method named exactly like the key. | +| `manage_stock` | `bool` | `WC_Product::get_manage_stock()` | | +| `stock_status` | `string` | `WC_Product::get_stock_status()` | `instock` / `outofstock` / `onbackorder`. | +| `catalog_visibility` | `string` | `WC_Product::get_catalog_visibility()` | | +| `short_description` | `string` | `WC_Product::get_short_description()` | | +| `description` | `string` | `WC_Product::get_description()` | | +| `permalink` | `string` | `WC_Product::get_permalink()` | `#[ReadOnlyProperty]`. | +| `category_ids` | `array` | `WC_Product::get_category_ids()` | Writable — **this is the property that persists category changes** (writes through to `WC_Product::set_category_ids()`). | +| `categories` | `array` (`ProductCat[]`) | `#[PostTermsRelation]` → `ProductCatRepository::find_terms_of_post()` | Read-only in practice — assignments are **not** persisted by `save()` (see gotchas). | +| `image_id` | `int` | `WC_Product::get_image_id()` | The featured image attachment ID. | +| `gallery_image_ids` | `array` | `WC_Product::get_gallery_image_ids()` | | +| `is_featured` | `bool` | `WC_Product::get_featured()` | `#[AccessorObject( key: 'featured' )]`. | +| `featured_image` | `?Attachment` | `#[ManyToOneRelation( 'featured_image_id' )]` | **Always `null`** — known limitation (see gotchas). Use `image_id` instead. | +| `wc_product` | `WC_Product\|null` | `get_wc_product()` → `source()` | `#[ReadOnlyProperty]`. The raw underlying `WC_Product`. | + +### Product methods + +Besides the inherited `Model` API (`source()`, `props()`, `refresh()`, `to_array()`, …), `Product` defines two helpers. + +#### `get_wc_product(): WC_Product|null` + +Returns the raw underlying `WC_Product`, for when you need WooCommerce's own API. + +```php +$wc = $product->get_wc_product(); +echo $wc->get_weight(); // result: '0.4' +``` + +#### `get_vat_rate( string $country_code ): ?float` + +Returns `null` for a non-taxable product; otherwise looks up `\WC_Tax::find_rates()` for the given country and the product's tax class, falling back to deriving the rate from the price incl./excl. tax. + +```php +$rate = $product->get_vat_rate( 'CZ' ); +// result: 21.0 +``` + +> [!WARNING] +> `get_vat_rate()` calls `is_taxable()` on the source object — a sourceless model (fresh `create()`) fatals. The fallback branch divides by the tax-inclusive price, so a taxable product priced at `0` raises `DivisionByZeroError`. + +### ProductCat + +`ProductCat` extends `Term` — it inherits all its properties (`id`, `name`, `slug`, `description`, `parent_id`, `parent`, `top_parent`, `children`, `count`, `permalink`, …); see [Term models](term.md) for the full table. It adds one property: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `products` | `array` (`Product[]`) | `#[TermPostsRelation( Product::class )]` → `ProductRepository::find_all_by_term()` | Lazy, cached, read-only. Runs a `wc_get_products()` query with a `tax_query` on `product_cat` — WooCommerce's default result limit applies. | + +> [!NOTE] +> The inherited `parent` property is declared `?Term`, so it resolves through the generic `TermRepository` and returns a plain `Term`, **not** a `ProductCat`. `top_parent` and `children` resolve through the model's own repository (`ProductCatRepository`) and *do* return typed `ProductCat` models. Re-fetch with `$cats->get( $cat->parent_id )` when you need a typed `ProductCat` parent. Also beware `to_array()` — it resolves every lazy property, including the potentially expensive `products` query. + +## Repository methods + +Both repositories inherit the shared contract (`create()`, `manager()`, `resolve_property()`, `maybe_convert_to_type()`) documented on the [Repository page](../repository.md). Only the family-specific surface is documented here. All snippets assume you obtained the repositories from the Manager: + +```php +use Wpify\Model\Manager; +use Wpify\Model\ProductRepository; +use Wpify\Model\ProductCatRepository; + +$manager = new Manager(); +$products = $manager->get_repository( ProductRepository::class ); +$cats = $manager->get_repository( ProductCatRepository::class ); +``` + +### ProductRepository + +#### `get( mixed $source ): ?ModelInterface` + +Resolves, in order: a `Product` instance (returned as-is), a `WC_Product` instance, a numeric ID via `wc_get_product()`, a **SKU** via `wc_get_products( array( 'sku' => …, 'posts_per_page' => 1 ) )`, and finally a **slug** via `get_page_by_path( …, OBJECT, 'product' )`. Returns `null` when nothing matches. + +```php +$product = $products->get( 123 ); // by ID +$product = $products->get( 'MY-SKU-001' ); // by SKU +$product = $products->get( 'blue-shirt' ); // by slug +echo $product->name; // result: 'Blue T-shirt' +``` + +> [!NOTE] +> SKU lookup runs before slug lookup for *any* still-unresolved source — a numeric string that is not a product ID is tried as a SKU, then as a slug. If your SKUs collide with slugs, the SKU wins. + +#### `find( array $args = array() ): array` + +Thin wrapper over `wc_get_products()` — the args are standard `WC_Product_Query` args, passed through unchanged — wrapping each result into a `Product`. Unlike plain `wc_get_products()`, a `tax_query` arg works here: the repository temporarily hooks `woocommerce_product_data_store_cpt_get_products_query` to merge it in. + +```php +$on_sale = $products->find( array( + 'status' => 'publish', + 'limit' => 20, + 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'sale' ) ), +) ); +// result: Product[] (up to 20 models) +``` + +> [!NOTE] +> `'return' => 'ids'` is passed through and short-circuits model wrapping — you get a raw `int[]`, not `Product[]`. + +#### `find_all( array $args = array() ): array` + +`find()` with a default of `array( 'limit' => -1 )` — every product, no limit. + +```php +$all = $products->find_all(); +// result: Product[] — one model per product in the catalog +``` + +#### `find_by_ids( array $ids, array $args = array() ): array` + +`find()` with defaults `array( 'limit' => -1, 'include' => $ids )`. + +```php +$picked = $products->find_by_ids( array( 12, 34, 56 ) ); +// result: Product[] for the existing IDs among 12, 34, 56 +``` + +#### `find_all_by_term( ModelInterface $model ): array` + +Takes any term model whose repository defines a `taxonomy()` method and runs `find()` with a `tax_query` on that taxonomy by `term_id`. Throws `IncorrectRepositoryException` when the term's repository has no `taxonomy()` method. + +```php +$cat = $cats->get( 'accessories' ); +$in_cat = $products->find_all_by_term( $cat ); +// result: Product[] assigned to the 'accessories' category +``` + +#### `save( ModelInterface $model ): ModelInterface` + +Runs `persist_{prop}()` hooks for non-readonly properties, then calls `$model->source()->save()` — it is `WC_Product::save()` that writes to the database (`wp_posts` plus WooCommerce lookup tables). The model is then refreshed from a freshly loaded `wc_get_product()`. + +```php +$product = $products->get( 123 ); +$product->stock_quantity = 5; // writes through to WC_Product::set_stock_quantity() +$product->sale_price = 19.99; +$product = $products->save( $product ); // WC_Product::save() + model refresh +// result: Product with updated values persisted +``` + +> [!WARNING] +> A model built by `create()` has **no source object**, and `save()` calls `$model->source()->save()` — a fatal "call to a member function on null". Attach a WC object first, and only set properties **after** attaching it — values assigned before a source exists are only cached on the model and never persisted: +> +> ```php +> $product = $products->create(); +> $product->source( new \WC_Product_Simple() ); // attach the source FIRST +> $product->name = 'Blue T-shirt'; // now writes through to the WC_Product +> $product = $products->save( $product ); +> echo $product->id; // result: 124 +> ``` + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Calls `WC_Product::delete( $force_delete )`. + +```php +$products->delete( $product ); +// result: true — product permanently deleted +``` + +> [!WARNING] +> The default is `$force_delete = true` — **permanent deletion, skipping trash** — the opposite of WordPress's usual trash-first behavior. Pass `false` to trash instead. + +### ProductCatRepository + +`ProductCatRepository` extends `TermRepository` and only overrides `model()` (→ `ProductCat::class`) and `taxonomy()` (→ `'product_cat'`). The full method documentation lives on the [Term models page](term.md); the real inherited names are: + +| Method | Behavior | +|---|---| +| `get( mixed $source ): ?ModelInterface` | By instance, `WP_Term`, numeric ID, or string — slug first, then name. | +| `find( array $args = [] ): array` | `get_terms()` with `taxonomy => 'product_cat'` default. | +| `find_all( array $args = array() ): array` | `find()` with `hide_empty => false`. | +| `find_not_empty( array $args = array() ): array` | `find()` with `hide_empty => true`. | +| `find_children_of( int $parent_id = 0, array $args = array() ): array` | `find()` with `child_of`; empty array when `$parent_id <= 0`. | +| `find_child_terms_of( ModelInterface $model ): array` | `find()` with `hierarchical => true, hide_empty => false, child_of => $model->id`. | +| `find_terms_of_post( int $post_id ): array` | `get_the_terms( $post_id, 'product_cat' )` wrapped into models. | +| `find_by_ids( array $ids, array $args = array() ): array` | `find()` with `include => $ids`. | +| `save( ModelInterface $model ): ModelInterface` | `wp_insert_term()` / `wp_update_term()` + `#[Meta]` props via `update_term_meta()`. | +| `delete( ModelInterface $model, bool $force_delete = true ): bool` | `wp_delete_term()`; `$force_delete` is unused (terms have no trash). | + +> [!NOTE] +> The class docblock advertises `all()`, `not_empty()`, `children_of()`, and `terms_of_post()` — **these methods do not exist**. The real names are `find_all()`, `find_not_empty()`, `find_children_of()`, and `find_terms_of_post()`. + +Unlike products, creating a category needs no source object — `TermRepository::save()` inserts via `wp_insert_term()`. + +```php +$cat = $cats->create( array( 'name' => 'Sale', 'slug' => 'sale' ) ); +$cat = $cats->save( $cat ); // wp_insert_term( ..., 'product_cat' ) +echo $cat->id; // result: 15 +``` + +## Behavior notes + +- **Assignment writes through immediately.** Setting any `#[AccessorObject]` property calls the matching `WC_Product::set_*()` on the in-memory source object at assignment time. Nothing hits the database until `save()`. +- **`ProductRepository::save()` step by step:** run `persist_{prop}()` hooks for non-readonly props → call `WC_Product::save()` (the actual DB write) → refresh the model from `wc_get_product( $result )` unless the `wpify_model_refresh_model_after_save` filter returns falsy → fire `wpify_model_repository_save_insert` or `_update` (insert vs. update is decided by `$model->source()->get_id()` *before* saving). +- **`ProductCatRepository::save()`** goes through WP core instead: `wp_insert_term()` / `wp_update_term()`, then `#[Meta]` properties via `update_term_meta()`. Failures throw `CouldNotSaveModelException` wrapping the underlying `WP_Error` (see [persistence concepts](../../concepts/persistence.md)). +- **Caching:** resolved property values are cached per model; `null` results are *not* cached and re-resolve on every access. `$model->refresh()` clears the cache (and `ProductCat::$products` with it). +- **Exceptions:** repository methods throw `RepositoryNotInitialized` when the repository was constructed manually and never registered with the Manager (see [Manager reference](../manager.md)). + +## Gotchas + +> [!WARNING] +> **`Product::$categories` does not persist on `save()`.** `#[PostTermsRelation]` persists only via `PostRepository::save()` — `ProductRepository::save()` never runs source-attribute persistence. Fix: assign `$product->category_ids` (an array of term IDs) instead — it writes through to `WC_Product::set_category_ids()` and persists. + +> [!NOTE] +> **Known limitation: `Product::$featured_image` is always `null`.** Its `#[ManyToOneRelation( 'featured_image_id' )]` reads a `featured_image_id` property that does not exist on `Product` (the real property is `image_id`), so the relation silently resolves to `null` every time. Fix: read `$product->image_id` and load the [Attachment](post.md) yourself. + +- **SKU beats slug in `get()`** — any unresolved string (even numeric) is tried as a SKU before a slug. Fix: pass an int for ID lookups and keep SKUs distinct from slugs. +- **`delete()` is permanent by default** (`$force_delete = true`). Fix: pass `false` to trash. +- **`find( array( 'return' => 'ids' ) )` returns `int[]`, not models.** Fix: drop the `return` arg when you want `Product[]`. +- **Empty price resolves to `0.0`**, because `price`/`regular_price`/`sale_price` are non-nullable floats and WC returns `''`. Fix: check `$product->wc_product->get_price() === ''` when "no price set" must differ from "free". +- **`ProductCat::$parent` is a plain `Term` model**, not `ProductCat` (it resolves via the declared `?Term` type through the generic `TermRepository`); `top_parent` resolves through `ProductCatRepository` and *is* a `ProductCat`. Fix: re-fetch with `$cats->get( $cat->parent_id )` when you need the `products` relation on the direct parent. +- **`OrderItemLine::$product` is a raw `WC_Product`**, not a wpify `Product` model — wrap it with `$products->get( $line->product )` when working with [orders](order.md). diff --git a/docs/reference/models/site.md b/docs/reference/models/site.md new file mode 100644 index 0000000..1b39a61 --- /dev/null +++ b/docs/reference/models/site.md @@ -0,0 +1,150 @@ +# Site models + +You'd land here when working with the sites of a WordPress multisite network — reading site records, site meta, or creating and updating sites programmatically. The `Site` model wraps a `WP_Site` object (a row in `wp_blogs`, plus site meta from `wp_blogmeta`) and is served by `SiteRepository`. + +> [!IMPORTANT] +> Requires multisite. Every `SiteRepository` method that touches WordPress (`get()`, `find()`, `find_all()`, `find_by_ids()`, `save()`, `delete()`) calls a function that WordPress only loads when `is_multisite()` is true, so on a single-site install each of them is a PHP fatal error (`Call to undefined function get_site()` and friends) — there is no graceful `null`/`false` path. Only `model()`, `create()`, and registration (the repository is registered by default by [the Manager](../manager.md)) are safe on single site; guard shared code with `is_multisite()` yourself. See the [multisite guide](../../guides/multisite.md) for a task-oriented walkthrough. + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Site` | `Wpify\Model\SiteRepository` | `WP_Site` | `wp_blogs` table + site meta in `wp_blogmeta` | + +## Properties + +`Site` extends `Wpify\Model\Model` and declares the following properties. RO marks `#[ReadOnlyProperty]` (never persisted; assignment throws once a non-empty value is cached). + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `#[SourceObject( 'blog_id' )]` | The site's own ID. "Blog" naming is legacy. Effective default `0`. | +| `domain` | `string = ''` | `#[SourceObject( 'domain' )]` | | +| `path` | `string = ''` | `#[SourceObject( 'path' )]` | | +| `site_id` | `int = 0` | `#[SourceObject( 'site_id' )]` | The parent **network** ID, not the site's ID — see the note below. | +| `registered` | `string = '0000-00-00 00:00:00'` | `#[SourceObject( 'registered' )]` | Creation date/time. | +| `last_updated` | `string = '0000-00-00 00:00:00'` | `#[SourceObject( 'last_updated' )]` | | +| `public` | `bool = true` | `#[SourceObject( 'public' )]` | | +| `archived` | `bool = false` | `#[SourceObject( 'archived' )]` | | +| `mature` | `bool = false` | `#[SourceObject( 'mature' )]` | No core handling; exists for custom implementations. | +| `spam` | `bool = false` | `#[SourceObject( 'spam' )]` | | +| `deleted` | `bool = false` | `#[SourceObject( 'deleted' )]` | | +| `lang_id` | `int = 0` | `#[SourceObject( 'lang_id' )]` | Language pack ID. | +| `site_name` | `string = ''` | `#[Meta( 'site_name' )]` | Site meta; not maintained by core — see the note below. | +| `admin_email` | `string = ''` | `#[Meta( 'admin_email' )]` | Site meta. | +| `admin_user_id` | `int = 0` | `#[Meta( 'admin_user_id' )]` | Site meta. | +| `admin_user` | `?User` | `#[ManyToOneRelation( 'admin_user_id' )]`, RO | Lazily loads `UserRepository::get( $site->admin_user_id )`; `null` when `admin_user_id` is empty. See [User models](user.md). | +| `site_url` | `string = ''` | `#[Meta( 'siteurl' )]` | Meta key `siteurl` differs from the property name. | +| `site_admins` | `array = []` | `#[Meta( 'site_admins' )]` | Site meta. | +| `is_main_site` | `bool = false` | `#[Meta( 'main_site' )]` | Site meta; not maintained by core. | +| `blog_count` | `int = 0` | `#[Meta( 'blog_count' )]` | Site meta; not maintained by core. | +| `user_count` | `int = 0` | `#[Meta( 'user_count' )]` | Site meta; not maintained by core. | + +> [!NOTE] +> `site_id` is the ID of the site's parent **network** (`WP_Site->site_id`, legacy naming). The site's own ID lives in `id`. On save, the repository renames it to the `network_id` argument that `wp_insert_site()`/`wp_update_site()` expect. + +> [!NOTE] +> The `#[Meta]` properties come from the `wp_blogmeta` table, which exists on WordPress >= 5.1 networks (checked via `is_site_meta_supported()`). Where site meta is unsupported, every `#[Meta]` property reads as its declared default and writes are silently dropped. Core does not maintain the `site_name`, `is_main_site`, `blog_count`, or `user_count` metas per site — they are conventions this model exposes, populated only if something writes them. + +> [!NOTE] +> Unlike every other model family, `#[Meta]` properties on `Site` write through **immediately on assignment**: setting `$site->admin_email = 'a@example.test'` calls `update_site_meta()` right away (when site meta is supported), before you ever call `save()`. `save()` then writes the same values again. See [persistence](../../concepts/persistence.md) for the family-by-family comparison. + +## Repository methods + +Only site-specific methods are documented here; `create()`, property resolution, and the shared contract live on the [Repository reference](../repository.md). All snippets below assume a multisite install and this setup: + +```php +use Wpify\Model\Manager; +use Wpify\Model\SiteRepository; + +$manager = new Manager(); +$sites = $manager->get_repository( SiteRepository::class ); +``` + +#### `get( mixed $source ): ?ModelInterface` + +Returns a `Site` model, resolving in order: an existing `Site` instance is returned as-is; a `WP_Site` instance is wrapped; anything else is passed to `get_site()` (which accepts a site ID). Returns `null` when the site is not found. + +```php +$site = $sites->get( get_main_site_id() ); +echo $site->domain . $site->path; // result: example.test/ +``` + +At the WP layer this calls `get_site( $source )`; property reads then resolve lazily from the returned `WP_Site` object. + +#### `save( ModelInterface $model ): ModelInterface` + +Persists the model: `wp_update_site( $model->id, $data )` when `id > 0`, otherwise `wp_insert_site( $data )`, then writes each `#[Meta]` property via `update_site_meta()`. Throws `CouldNotSaveModelException` on failure, with the underlying `WP_Error` attached (retrievable via `get_wp_error()`). + +```php +$site = $sites->create( array( 'domain' => 'shop.example.test', 'path' => '/' ) ); +$site = $sites->save( $site ); +echo $site->id; // result: 7 +``` + +At the WP layer this runs `wp_insert_site()` (or `wp_update_site()`), an `update_site_meta()` call per meta property, and a `get_site()` re-fetch to refresh the model. + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Deletes the site via `wp_delete_site( $model->id )`; returns `false` when WordPress returns a `WP_Error`. The `$force_delete` parameter is unused — site deletion is always permanent (table drops and uploads cleanup are left to core's deletion hooks). + +```php +$deleted = $sites->delete( $site ); +var_dump( $deleted ); // result: bool(true) +``` + +#### `find( array $args = array() ): array` + +Thin wrapper over `get_sites( $args )` — every `WP_Site_Query` argument passes through unchanged (see the `get_sites()` entry in the WordPress developer reference); each result is wrapped via `get()`. Returns `Site[]`. + +```php +$public = $sites->find( array( 'public' => 1, 'archived' => 0 ) ); +echo count( $public ); // result: 3 +``` + +#### `find_all( array $args = array() ): array` + +Alias for `find( $args )` with no extra defaults. + +```php +$all = $sites->find_all(); +echo count( $all ); // result: 5 +``` + +#### `find_by_ids( array $ids ): array` + +Calls `find( array( 'site__in' => $ids ) )`. Unlike the Term and Comment equivalents, it takes no second `$args` parameter. + +```php +$pair = $sites->find_by_ids( array( 1, 2 ) ); +echo $pair[0]->domain; // result: example.test +``` + +#### `create( array $data = array() ): ModelInterface` + +Inherited from the base [Repository](../repository.md): builds a new **unsaved** `Site` and assigns each `$data` key that matches a declared property. It never touches the database, so it is the one data method that is also safe on single site. + +```php +$site = $sites->create( array( 'domain' => 'blog.example.test', 'path' => '/' ) ); +echo $site->id; // result: 0 (not persisted until save()) +``` + +## Behavior notes + +- `save()` collects writable (non-readonly) properties, removes `blog_id` from the data array, and renames `site_id` to `network_id` — the shape `wp_insert_site()`/`wp_update_site()` expect (the site ID is passed as a separate argument to `wp_update_site()`). +- Insert vs update is decided by `$model->id > 0`. +- After the core write, `#[Meta]` properties are written in a loop via `update_site_meta( $site_id, $key, $value )` — but only when `is_site_meta_supported()` returns true. +- The model is then refreshed from a fresh `get_site( $site_id )`, controllable via the `wpify_model_refresh_model_after_save` filter (default `true`), and `wpify_model_repository_save_insert` or `wpify_model_repository_save_update` fires with `( $model, $repository )`. +- If the refresh filter returns `false`, an inserted `Site` model keeps `id = 0` — the new ID is only propagated through the refresh. +- Save failures throw `CouldNotSaveModelException` with the `WP_Error` from WordPress attached; call `get_wp_error()` on the exception to inspect it (only the Term and Site families attach it). +- Because saving collects every writable (non-readonly) property, `save()` forces resolution of each of them; readonly relations like `admin_user` are skipped and stay unresolved. +- On single site, the `Site` class itself is loadable and `create()` works; reading a `#[Meta]` property returns its declared default and assignments stay in memory only. + +## Gotchas + +- **Single-site fatals.** Every DB-touching repository method fatals on single site (see the callout at the top). Fix: guard with `is_multisite()` before using `SiteRepository`. +- **Immediate meta write-through.** Assigning a `#[Meta]` property on a fetched site writes `wp_blogmeta` instantly — you cannot stage site meta changes and discard them before `save()`. Fix: only assign meta values you intend to persist. +- **`site_id` is the network ID**, not the site's ID. Fix: use `id` for the site itself. +- **Site meta silently no-ops without `wp_blogmeta`.** On networks where `is_site_meta_supported()` is false, meta properties read as defaults and writes are dropped without error. Fix: check `is_site_meta_supported()` if your code depends on site meta. +- **`admin_user` needs an existing user.** The relation loads through `UserRepository::get( $site->admin_user_id )`, so the user must exist in the network (users are network-global; site membership is not checked); it returns `null` when `admin_user_id` is empty. It is read-only and never persisted. +- **`find_by_ids()` accepts no `$args`.** Pass `site__in` to `find()` directly if you need to combine an ID list with other query arguments. +- **`$force_delete` on `delete()` is ignored** — there is no trash for sites; deletion is permanent. diff --git a/docs/reference/models/term.md b/docs/reference/models/term.md new file mode 100644 index 0000000..eba5da5 --- /dev/null +++ b/docs/reference/models/term.md @@ -0,0 +1,232 @@ +# Term models + +You are here because you work with taxonomy terms — categories, tags, or terms of a custom taxonomy — as models. These models wrap a `WP_Term` source object and are served by `TermRepository` and its taxonomy-bound subclasses. + +> [!NOTE] +> `Term` implements `Wpify\Model\Interfaces\TermModelInterface`, an empty marker interface extending `ModelInterface`. Use it to type-hint "any term model" (built-in or custom) without committing to a concrete class. + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\Term` | `Wpify\Model\TermRepository` (taxonomy: `''` — all taxonomies) | `WP_Term` | `wp_terms` + `wp_term_taxonomy` | +| `Wpify\Model\Category` | `Wpify\Model\CategoryRepository` (taxonomy: `category`) | `WP_Term` | `wp_terms` + `wp_term_taxonomy` | +| `Wpify\Model\PostTag` | `Wpify\Model\PostTagRepository` (taxonomy: `post_tag`) | `WP_Term` | `wp_terms` + `wp_term_taxonomy` | + +Term meta declared via `#[Meta]` on model subclasses is stored in `wp_termmeta`. The base `Term` model declares no `#[Meta]` properties. + +For custom taxonomies, subclass `Term` and `TermRepository` and override `taxonomy()` — see the [custom taxonomies guide](../../guides/custom-taxonomies.md). WooCommerce product categories follow the same pattern with `ProductCat`/`ProductCatRepository` — see [Product models](product.md). + +## Properties + +### Term + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int` | `#[SourceObject( 'term_id' )]` | Default `0`; decides insert vs update on save | +| `name` | `string` | `#[SourceObject( 'name' )]` | Persisted | +| `slug` | `string` | `#[SourceObject( 'slug' )]` | Persisted | +| `group` | `int` | `#[SourceObject( 'term_group' )]` | Persisted as `term_group` | +| `taxonomy_id` | `int` | `#[SourceObject( 'term_taxonomy_id' )]` | Never persisted | +| `taxonomy` | `string` | `#[SourceObject( 'taxonomy' )]` | Picks the taxonomy on save/delete; falls back to the repository's `taxonomy()` when empty | +| `description` | `string` | `#[SourceObject( 'description' )]` | Persisted | +| `parent_id` | `int` | `#[SourceObject( 'parent' )]` | Persisted as `parent` | +| `parent` | `?Term` | `#[ManyToOneRelation( 'parent_id' )]` | Lazy; `null` when `parent_id` is `0`; not persisted | +| `top_parent` | `?Term` | `#[TopLevelTermParentRelation]` | Lazy; `null` when the term has no ancestors | +| `children` | `array` (`Term[]`) | `#[ChildTermsRelation]` | Lazy; all descendants, not just direct children | +| `count` | `int` | `#[SourceObject( 'count' )]` | WordPress's cached object count; never persisted | +| `filter` | `string` | `#[SourceObject( 'filter' )]` | Sanitization level, not a database field; never persisted | +| `permalink` | `string` | getter `get_permalink()` + `#[ReadOnlyProperty]` | `get_term_link( $id, $taxonomy )` | +| `alias_of` | `string` | *(none — write-only)* | Only consumed by `save()` as the `alias_of` argument to `wp_insert_term()`/`wp_update_term()` | + +All properties resolve lazily on first read and are cached per model instance — see [property resolution](../../concepts/property-resolution.md). To load a related model, set `parent_id`; assigning `parent` directly is never persisted. + +`top_parent` resolves through `get_ancestors( $id, $repository->taxonomy(), 'taxonomy' )` — it uses the **repository's** taxonomy, not the model's `taxonomy` property, so it only returns useful results through a taxonomy-bound repository subclass such as `CategoryRepository`. + +> [!WARNING] +> Reading `permalink` on an unsaved or nonexistent term is a fatal error, not an empty string: `get_term_link()` returns a `WP_Error`, and coercing it to the declared `string` type throws. Read `permalink` only after the term exists in the database. + +### Category and PostTag + +`Category extends Term` and `PostTag extends Term` — each inherits all `Term` properties and adds exactly one: + +| Property | Type | Source | Notes | +|---|---|---|---| +| `posts` | `array` (`Post[]`) | `#[TermPostsRelation( Post::class )]` | Lazy read-only view; not persisted | + +The `posts` relation runs a `WP_Query` (`tax_query` on `term_id`) through `PostRepository`, so it returns only `post_type = post` items — with `post_status => 'any'` and no pagination. It can be a big query; count posts another way on large sites. + +```php +use Wpify\Model\CategoryRepository; + +$news = $manager->get_repository( CategoryRepository::class )->get( 'news' ); +echo count( $news->posts ); // result: 42 (all statuses, unpaginated) +``` + +> [!NOTE] +> Tags are non-hierarchical in WordPress, so `PostTag` inherits `parent`, `top_parent`, and `children` but they are meaningless for real tags — `parent_id` is always `0`. + +## Repository methods + +This section lists only what `TermRepository` adds or changes versus the shared contract; `create()`, `manager()`, and property resolution helpers are documented once on the [Repository reference](../repository.md). `create( array $data = array() )` builds an **unsaved** `Term` in memory — nothing hits the database until `save()`. `model()` returns `Term::class` and is overridden together with `taxonomy()` in subclasses. Cross-family querying patterns live in the [querying guide](../../guides/querying.md). + +#### `taxonomy(): string` + +Returns the taxonomy the repository is bound to — `''` in the base class (all taxonomies), `'category'`/`'post_tag'` in the built-in subclasses. Override it to bind a repository to a custom taxonomy. `get()` passes it unconditionally to the underlying `get_term()`/`get_term_by()` lookups, `find()` uses it as the default `taxonomy` query argument, and `save()`/`delete()` fall back to it only when the model's own `taxonomy` property is empty. + +```php +taxonomy() )`, then as a name. Returns `null` when nothing matches. + +```php +use Wpify\Model\CategoryRepository; + +$categories = $manager->get_repository( CategoryRepository::class ); +$news = $categories->get( 'news' ); // get_term_by( 'slug', 'news', 'category' ) +echo $news->name; // result: News +``` + +> [!NOTE] +> Slug and name lookups require a taxonomy-bound repository. On the base `TermRepository`, `taxonomy()` is `''`, and `get_term_by()` rejects an empty taxonomy — so string lookups through the base repository always return `null`. Look up by ID or `WP_Term` there instead. + +> [!NOTE] +> `get( 0 )` (or any empty numeric value) does **not** return `null`. `get_term( 0 )` returns a `WP_Error`, which is truthy, so it becomes the model's source and you get a `Term` whose properties all resolve to defaults (`id === 0`). Guard IDs before calling, or check `$term->id > 0` afterwards. + +Numeric strings such as `'123'` are tried as IDs first, but when no term with that ID exists, `get_term()` returns `null` and the lookup falls through to slug and then name — so `get( '2024' )` can match a term with slug `2024` when no term ID 2024 exists. Only empty values like `get( 0 )` short-circuit, because `get_term( 0 )` returns a truthy `WP_Error`. A string lookup tries slug before name, so a term whose name equals another term's slug is shadowed by the slug match. + +#### `find( array $args = [] ): array` + +Runs `get_terms( $args )` with `taxonomy` defaulting to `$this->taxonomy()` (an empty taxonomy is dropped, querying all taxonomies), and wraps each result via `get()`. All other `get_terms()` arguments pass through unchanged. + +```php +use Wpify\Model\CategoryRepository; + +$categories = $manager->get_repository( CategoryRepository::class ); +$found = $categories->find( array( 'search' => 'news' ) ); +// result: Category[] — only categories that have posts (hide_empty default) +``` + +> [!NOTE] +> `find()` inherits `get_terms()`'s default `hide_empty => true` — terms assigned to no posts are silently omitted. Use `find_all()` or pass `hide_empty => false` to include them. This is the mirror image of the post side, where bare `find()` is the permissive variant. + +#### `find_all( array $args = array() ): array` + +`find()` with a default of `hide_empty => false` (your `$args` can override it) — returns all terms including empty ones. + +```php +$all = $categories->find_all(); +// result: every category, including ones with no posts +``` + +#### `find_not_empty( array $args = array() ): array` + +`find()` with an explicit default of `hide_empty => true` — only terms that have at least one object assigned. + +```php +$used = $categories->find_not_empty(); +// result: only categories with at least one post +``` + +#### `find_children_of( int $parent_id = 0, array $args = array() ): array` + +`find()` with `child_of => $parent_id`, which returns **all descendants** recursively, not just direct children. When `$parent_id` is `0` or negative it returns an empty array without querying. + +```php +$subtree = $categories->find_children_of( 5 ); +// result: Category[] — children, grandchildren, and deeper +``` + +#### `find_terms_of_post( int $post_id ): array` + +Wraps `get_the_terms( $post_id, $this->taxonomy() )` — the terms of the repository's taxonomy assigned to a post. Returns an empty array when the post has none. This method backs the `#[PostTermsRelation]` attribute (e.g. `Post::$categories`). + +```php +$of_post = $categories->find_terms_of_post( 42 ); +// result: Category[] assigned to post 42 +``` + +#### `find_child_terms_of( ModelInterface $model ): array` + +`find()` with the model's `taxonomy` used as-is, `hierarchical => true`, `hide_empty => false`, and `child_of => $model->id`. When the model's `taxonomy` is empty, `find()` drops the taxonomy argument and queries all taxonomies (the `?? $this->taxonomy()` fallback in the source is effectively dead code, because the property resolves to `''`, never `null`). This is what resolves `Term::$children` — like `find_children_of()`, it includes grandchildren. + +```php +$children = $categories->find_child_terms_of( $news ); +// result: same as reading $news->children +``` + +#### `find_by_ids( array $ids, array $args = array() ): array` + +`find()` with `include => $ids` merged over `$args` (the `include` key wins). + +```php +$picked = $categories->find_by_ids( array( 3, 7 ), array( 'hide_empty' => false ) ); +// result: Category[] for IDs 3 and 7, even if empty +``` + +> [!NOTE] +> `find_by_ids()` also inherits `hide_empty => true` — empty terms are silently missing from the result unless you pass `hide_empty => false` in `$args`, as above. + +#### `save( ModelInterface $model ): Term` + +Persists the model: `wp_update_term()` when `$model->id > 0`, otherwise `wp_insert_term()`, using the taxonomy from `$model->taxonomy ?: $this->taxonomy()`. Core term fields come from a fixed mapping (`name`, `slug`, `term_group` ← `group`, `description`, `parent` ← `parent_id`, `alias_of`); each `#[Meta]` property of a subclassed model is then written via `update_term_meta()`. + +```php +$category = $categories->create( array( 'name' => 'Releases', 'slug' => 'releases' ) ); +$category = $categories->save( $category ); +echo $category->id; // result: 17 (assigned by wp_insert_term(), read back via refresh) +``` + +On failure the underlying `WP_Error` is attached to the exception — retrieve it with `get_wp_error()`. + +```php +use Wpify\Model\Exceptions\CouldNotSaveModelException; + +try { + $categories->save( $categories->create( array( 'name' => '' ) ) ); +} catch ( CouldNotSaveModelException $e ) { + echo $e->get_wp_error()->get_error_code(); // result: empty_term_name +} +``` + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Calls `wp_delete_term( $model->id, $model->taxonomy ?: $this->taxonomy() )` and returns `false` on `WP_Error`. The `$force_delete` parameter is unused — terms have no trash, so deletion is always permanent. + +```php +$categories->delete( $category ); // wp_delete_term( 17, 'category' ) +// result: true +``` + +## Behavior notes + +- `save()` step by step: (1) picks the taxonomy from `$model->taxonomy ?: $this->taxonomy()`; (2) `id > 0` → `wp_update_term()`, else `wp_insert_term()` with the fixed field mapping above; (3) a `WP_Error` result throws `CouldNotSaveModelException` wrapping the `WP_Error`; (4) writes every `#[Meta]` property via `update_term_meta()`; (5) unless the `wpify_model_refresh_model_after_save` filter returns `false`, refreshes the model from `get_term()` so database state wins; (6) fires `wpify_model_repository_save_insert` or `wpify_model_repository_save_update` with `( $model, $repository )`. +- Core term fields are persisted **only** through the fixed mapping — the collected `#[SourceObject]` data bucket is discarded, and only the `#[Meta]` bucket is written after the core call. `persist_*` hooks defined on a model subclass still run during collection (and can persist data as a side effect); a prop with a persist hook is excluded from the meta bucket. `taxonomy_id`, `count`, and `filter` are never written back. +- Collecting values for save reads only writable `#[SourceObject]`- and `#[Meta]`-attributed properties (plus invoking any `persist_*` hooks); relation properties such as `children` are skipped entirely, so `save()` never resolves them and runs no extra `get_terms()` query. See [persistence](../../concepts/persistence.md) for how this compares across families. +- `#[Meta]` writes are deferred until `save()` — assigning a meta-backed property on a term model only caches the value in memory (unlike Site models, where meta writes immediately). +- Every property is resolved once and cached on the model; `unset( $term->prop )` re-resolves a single property, `$term->refresh()` clears them all. + +## Gotchas + +- **`permalink` fatals on an unsaved term** (`get_term_link()` returns `WP_Error`, string coercion throws) — read it only after `save()`. +- **`get( 0 )` returns a model, not `null`** — the `WP_Error` from `get_term( 0 )` is wrapped as a source; check `$term->id > 0` after `get()`. +- **`find()` and `find_by_ids()` hide empty terms by default** — pass `hide_empty => false` or use `find_all()`. +- **String `get()` matches slug before name** — a name colliding with another term's slug resolves to the slug match; look up by ID when ambiguous. +- **`top_parent` uses the repository's `taxonomy()`, not the model's `taxonomy`** — use a taxonomy-bound repository subclass or it resolves to `null`. +- **`children` includes all descendants** (`child_of` is recursive) — filter by `parent_id` yourself if you need direct children only. +- **After insert, `id` stays `0` if the `wpify_model_refresh_model_after_save` filter returns `false`** — the inserted ID reaches the model only through the post-save refresh. +- **`alias_of` is write-only** and `taxonomy_id`/`count`/`filter` are read-only in practice — none of them round-trips through save as a term field. +- **`delete()` ignores `$force_delete`** — term deletion is always permanent. diff --git a/docs/reference/models/user.md b/docs/reference/models/user.md new file mode 100644 index 0000000..3037e45 --- /dev/null +++ b/docs/reference/models/user.md @@ -0,0 +1,174 @@ +# User models + +You're here because you need to read, query, create, update, or delete WordPress users through wpify/model. The `User` model wraps a `WP_User` object — core user fields plus the standard profile user meta — and is served by `UserRepository`. + +## Models and repositories + +| Model | Repository | WP object | Storage | +|---|---|---|---| +| `Wpify\Model\User` | `Wpify\Model\UserRepository` | `WP_User` | `wp_users` + `wp_usermeta` | + +## Properties + +All properties are lazy: the value is resolved from the source attribute on first read, coerced to the declared type, and cached on the model (see [property resolution](../../concepts/property-resolution.md)). Read-only means the property carries `#[ReadOnlyProperty]`: it is never persisted by `save()`, and assigning it throws `ReadOnlyPropertyException` once a non-empty value is already resolved. + +| Property | Type | Source | Notes | +|---|---|---|---| +| `id` | `int = 0` | `#[SourceObject( 'ID' )]` | | +| `password` | `string = ''` | *(none)* | Write-only; never read from the source, consumed only by `save()` | +| `first_name` | `string = ''` | `#[Meta( 'first_name' )]` | | +| `last_name` | `string = ''` | `#[Meta( 'last_name' )]` | | +| `nickname` | `string = ''` | `#[Meta( 'nickname' )]` | | +| `description` | `string = ''` | `#[Meta( 'description' )]` | | +| `rich_editing` | `bool = true` | `#[Meta( 'rich_editing' )]` | Read-only | +| `syntax_highlighting` | `bool = true` | `#[Meta( 'syntax_highlighting' )]` | Read-only | +| `comment_shortcuts` | `bool = false` | `#[Meta( 'comment_shortcuts' )]` | Read-only | +| `admin_color` | `string = ''` | `#[Meta( 'admin_color' )]` | Read-only | +| `use_ssl` | `bool = false` | `#[Meta( 'use_ssl' )]` | Read-only | +| `show_admin_bar_front` | `bool = true` | `#[Meta( 'show_admin_bar_front' )]` | Read-only | +| `locale` | `string = ''` | `#[Meta( 'locale' )]` | | +| `capabilities` | `array = []` | `#[Meta( 'wp_capabilities' )]` | Read-only | +| `user_level` | `int = 0` | `#[Meta( 'wp_user_level' )]` | Read-only | +| `dismissed_wp_pointers` | `string = ''` | `#[Meta( 'dismissed_wp_pointers' )]` | Read-only | +| `show_welcome_panel` | `bool = true` | `#[Meta( 'show_welcome_panel' )]` | | +| `dashboard_quick_press_last_post_id` | `int = 0` | `#[Meta( 'wp_dashboard_quick_press_last_post_id' )]` | Read-only | +| `login` | `string = ''` | `#[SourceObject( 'data.user_login' )]` | WordPress ignores changes on update — see Gotchas | +| `nicename` | `string = ''` | `#[SourceObject( 'data.user_nicename' )]` | The user's slug | +| `email` | `string = ''` | `#[SourceObject( 'data.user_email' )]` | | +| `url` | `string = ''` | `#[SourceObject( 'data.user_url' )]` | | +| `registered` | `string = ''` | `#[SourceObject( 'data.user_registered' )]` | | +| `display_name` | `string = ''` | `#[SourceObject( 'data.display_name' )]` | | +| `activation_key` | `string = ''` | `#[SourceObject( 'data.user_activation_key' )]` | | +| `status` | `int = 0` | `#[SourceObject( 'data.user_status' )]` | | +| `spam` | `?string = ''` | `#[SourceObject( 'data.spam' )]` | Read-only; multisite only — resolves to `''` on single site | +| `deleted` | `?string = ''` | `#[SourceObject( 'data.deleted' )]` | Read-only; multisite only — resolves to `''` on single site | +| `caps` | `array = []` | `#[SourceObject]` | Read-only; capabilities granted outside the role | +| `cap_key` | `string = ''` | `#[SourceObject]` | Read-only | +| `roles` | `array = []` | `#[SourceObject]` | Read-only | +| `allcaps` | `array = []` | `#[SourceObject]` | Read-only | +| `filter` | `?string = null` | `#[SourceObject]` | Read-only | + +The `data.*` source keys are dot paths into `WP_User->data`, where WordPress nests the core user row; `save()` strips the prefix before passing them to the user functions. `#[Meta]` properties read via `get_user_meta()` and are written only at save time — see [meta fields](../../guides/meta-fields.md). + +The model defines no custom getter or setter methods beyond the shared [`Model`](../model.md) API. + +## Repository methods + +Only the methods `UserRepository` adds or specializes are documented here. `create()`, `manager()`, and the rest of the shared contract are documented once on the [Repository reference](../repository.md) — note that `create()` builds an unsaved in-memory model and never touches the database. + +Get the repository from [the Manager](../manager.md) once and reuse it; the snippets below assume `$users` exists. + +```php +use Wpify\Model\Manager; +use Wpify\Model\UserRepository; + +$manager = new Manager(); +$users = $manager->get_repository( UserRepository::class ); +``` + +#### `get( mixed $source ): ?ModelInterface` + +Fetches one user — the docblock narrows the return to `?User`. Resolution order: an existing `User` model is returned as-is; a `WP_User` object is wrapped; anything else is tried through `get_user_by()` as `'id'`, then `'login'`, then `'email'`, then `'slug'`. Returns `null` when nothing matches. + +```php +$user = $users->get( 'jane@example.com' ); +echo $user->display_name; // result: Jane Doe +``` + +At the WP layer this calls `get_user_by()` for each lookup type in turn until one returns a `WP_User`. + +#### `get_current(): ?User` + +Wraps `wp_get_current_user()` and returns the logged-in user as a model. + +```php +$me = $users->get_current(); +if ( $me && $me->id > 0 ) { + echo $me->login; // result: jane +} +``` + +> [!NOTE] +> `get_current()` never returns `null` in a normal request. For a logged-out visitor, `wp_get_current_user()` returns `WP_User( 0 )`, which is truthy — so you get a `User` model with `id === 0`, not `null`. Always check `$me->id > 0`, not just for `null`. + +#### `find( array $args = array() ): array` + +Returns `User[]` matching the query args. This is a thin wrapper over `get_users()` — all [`get_users()` / `WP_User_Query` arguments](https://developer.wordpress.org/reference/functions/get_users/) pass through unchanged, with no defaults added. See the [querying guide](../../guides/querying.md) for cross-family query patterns. + +```php +$editors = $users->find( array( 'role' => 'editor' ) ); +echo count( $editors ); // result: 3 +``` + +#### `find_all( array $args = array() ): array` + +Alias for `find()` with no extra defaults; without args, `get_users()` returns all users of the current site. + +```php +$everyone = $users->find_all(); +echo count( $everyone ); // result: 27 +``` + +#### `find_by_ids( array $ids ): array` + +Shorthand for `find( array( 'include' => $ids ) )`. + +```php +$authors = $users->find_by_ids( array( 1, 5, 8 ) ); +echo $authors[0]->display_name; // result: Jane Doe +``` + +> [!NOTE] +> Unlike `TermRepository::find_by_ids()` and `CommentRepository::find_by_ids()`, this method takes no second `$args` parameter — pass extra args through `find()` yourself if you need them. + +#### `save( ModelInterface $model ): ModelInterface` + +Persists the model: `wp_insert_user()` when the collected `ID` is empty, `wp_update_user()` otherwise. Writable `#[Meta]` properties are passed as `meta_input` in the same call. Throws `CouldNotSaveModelException` on failure. + +```php +$user = $users->create( array( + 'login' => 'jdoe', + 'email' => 'jdoe@example.com', + 'first_name' => 'John', +) ); +$user->password = 'S3cret!'; +$user = $users->save( $user ); // wp_insert_user() + meta_input +echo $user->id; // result: 7 +``` + +At the WP layer this writes one row to `wp_users` and the `meta_input` keys to `wp_usermeta`. If `password` is empty on insert, the repository generates one via `wp_generate_password( 24 )`, because `wp_insert_user()` requires a password. + +#### `delete( ModelInterface $model, bool $force_delete = true ): bool` + +Deletes the user via `wp_delete_user( $model->id )`. The `$force_delete` parameter exists for interface compatibility but is unused — user deletion is always permanent. + +```php +require_once ABSPATH . 'wp-admin/includes/user.php'; + +$deleted = $users->delete( $user ); +// result: true — row removed from wp_users, their usermeta deleted +``` + +> [!WARNING] +> `wp_delete_user()` lives in `wp-admin/includes/user.php`, which WordPress loads only for admin requests. Calling `delete()` on the front end (or in cron/CLI) is a PHP fatal error unless you `require_once ABSPATH . 'wp-admin/includes/user.php';` first. On multisite, `wp_delete_user()` only removes the user from the current site. + +## Behavior notes + +- `save()` step by step: collects persistable props (skipping every read-only prop) via `collect_persistable_props()`; strips the `data.` prefix from `#[SourceObject]` keys so `wp_insert_user()` / `wp_update_user()` receive them bare (`user_login`, `user_email`, …); moves `#[Meta]` props into `meta_input`, converting booleans to the strings `'true'`/`'false'` (WordPress's own storage convention for boolean user meta); adds `user_pass` from `$model->password` when non-empty, or generates a 24-character password on insert; dispatches to `wp_update_user()` when the collected `ID > 0`, else `wp_insert_user()`. Full cross-family semantics are on the [persistence concept page](../../concepts/persistence.md). +- Because collection reads every writable prop, calling `save()` forces resolution of all lazy writable properties. +- After a successful save, the model is refreshed from `get_user_by( 'id', $result )` — controllable via the `wpify_model_refresh_model_after_save` filter (default `true`; receives `$model`, `$repository`). If the filter returns `false`, an inserted model keeps `id = 0`. +- After the refresh step, `save()` fires `do_action( 'wpify_model_repository_save_insert' )` or `wpify_model_repository_save_update` with `$model` and `$repository`. +- On failure, `save()` throws `CouldNotSaveModelException` with the error message only — `get_wp_error()` returns `null` (unlike Term and Site saves, which attach the underlying `WP_Error`). See [troubleshooting](../../guides/troubleshooting.md). +- Meta properties are only written at save time via `meta_input`; assigning them changes the model in memory but writes nothing to `wp_usermeta` until `save()` (unlike the [Site model](site.md), whose meta writes through immediately). + +## Gotchas + +- **`get_current()` returns an `id === 0` model for logged-out visitors**, never `null` in a normal request — check `$user->id > 0`. +- **`password` is write-only.** It has no source attribute, is never populated from the database, and is excluded from prop collection; `save()` reads it explicitly. It holds only whatever you assigned in memory. +- **Roles are not modeled.** `roles`, `capabilities`, `caps`, `allcaps`, and `user_level` are all read-only and never persisted; there is no `role` prop, so new users get WordPress's default role. Change roles through `WP_User::set_role()` or `wp_update_user()` directly. +- **A numeric string is treated as an ID first.** `get()` tries `'id'` before `'login'`/`'email'`/`'slug'`, so `get( '123' )` resolves to user ID 123 whenever that user exists; a login named "123" is only found if no user has that ID. +- **Editing `login` on an existing user silently does nothing.** WordPress itself ignores `user_login` in `wp_update_user()` — this is WP behavior, not library code. Create a new user if you need a different login. +- **Boolean meta round-trips through strings.** `save()` writes boolean meta as `'true'`/`'false'` strings and the shared bool coercion parses them back — query `wp_usermeta` accordingly if you bypass the model. +- **`delete()` fatals outside wp-admin** without `require_once ABSPATH . 'wp-admin/includes/user.php';` — see the WARNING above. +- **Assigning a read-only prop doesn't always throw.** `ReadOnlyPropertyException` is thrown only once a non-empty value is already resolved and cached; assigning before the first read silently succeeds in memory — but the value is still never persisted. +- **`spam` and `deleted` are multisite fields.** On single site they simply resolve to their default `''`; nothing fatals, but don't expect real values outside a [multisite](../../guides/multisite.md) network. diff --git a/docs/reference/repository.md b/docs/reference/repository.md new file mode 100644 index 0000000..1ba12ab --- /dev/null +++ b/docs/reference/repository.md @@ -0,0 +1,249 @@ +# Repository + +You'd land here to look up the shared contract that every repository — built-in or custom — is built on. `Wpify\Model\Repository` is the abstract base class: it provides the Manager wiring, the model factory (`create()`), the property-resolution pipeline behind every lazy property read, and the save-time prop collector for repository authors. Concrete storage (`get`, `save`, `delete`, `find`…) lives in the subclasses, so this page documents the shared surface once and each family page documents only its deltas. + +The one rule to keep in mind: **models hold the data, repositories talk to WordPress, the Manager wires them together.** + +## What lives where + +The base class implements the plumbing; the storage methods required by `Wpify\Model\Interfaces\RepositoryInterface` are left entirely to subclasses. + +| Method | Implemented in base class | Purpose | +|---|---|---| +| `model()` | No — abstract, you implement it | FQCN of the model this repository manages | +| `manager()` | Yes | Gets/sets the Manager | +| `create()` | Yes | Builds an unsaved, in-memory model from an array | +| `resolve_property()` | Yes | The lazy `__get` pipeline | +| `maybe_convert_to_type()` | Yes | Type coercion for reads and writes | +| `collect_persistable_props()` | Yes (protected) | Save-time prop collector for repository authors | +| `get()`, `save()`, `delete()`, `find()`, `find_by_ids()`, `find_all()` | No — subclass must implement | Storage — see [The storage surface](#the-storage-surface) | + +> [!NOTE] +> The base class does not re-declare the six storage methods as `abstract`. A repository that extends `Repository` directly and forgets one fails at class-load time with a PHP "must implement interface method" fatal — not with a library exception. + +## Base class methods + +#### `abstract public function model(): string` + +Returns the fully qualified class name of the model this repository manages. The Manager uses it as the registry key that maps a model class to its repository, and `create()` uses it as the class to instantiate. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); + +echo $posts->model(); // result: Wpify\Model\Post +``` + +#### `public function manager( ?Manager $manager = null ): Manager` + +Combined getter/setter for the Manager. `Manager::register_repository()` calls it to inject itself; after that, the repository (and every model it produces) resolves related repositories through it. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); + +var_dump( $posts->manager() === $manager ); // result: bool(true) +``` + +> [!NOTE] +> Reading `manager()` before the repository was registered with a Manager throws `RepositoryNotInitialized`. A repository constructed by hand (`new BookRepository()`) and never registered fails the first time it needs its Manager — pass it to the Manager constructor or `register_repository()` first. See [the Manager](manager.md). + +#### `public function create( array $data = array() ): ModelInterface` + +Instantiates `model()` with the Manager, then assigns each `$data` pair through the model's magic `__set` — so type coercion, `set_{prop}()` hooks, and accessor/meta write-through all apply. No WordPress function is called; the model exists only in memory. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$manager = new Manager(); +$posts = $manager->get_repository( PostRepository::class ); + +$draft = $posts->create( [ 'title' => 'Dune', 'post_status' => 'draft' ] ); +echo $draft->id; // result: 0 — nothing in the database yet +``` + +> [!WARNING] +> `create()` never persists anything. Until you call the repository's `save()`, the model exists only in memory and is lost at the end of the request. See [persistence](../concepts/persistence.md) for what `save()` does per family. + +> [!NOTE] +> Keys in `$data` that don't match a declared model property are silently dropped — a typo like `'titel'` produces no error, just a model without that value. + +#### `public function resolve_property( array $property, ModelInterface $model ): mixed` + +The resolution pipeline behind `Model::__get`: (1) if the model defines `get_{name}()`, call it; (2) otherwise, if the property has a source attribute, call the attribute's `get()`; (3) run the result through `maybe_convert_to_type()`. You'd call it directly only when building tooling on top of `props()` — normal reads go through the model. The full flow is explained in [property resolution](../concepts/property-resolution.md). + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$posts = ( new Manager() )->get_repository( PostRepository::class ); +$post = $posts->get( 42 ); + +echo $posts->resolve_property( $post->props()['title'], $post ); // result: Hello world! +``` + +At the WordPress layer: for a `#[SourceObject]` property this is a plain property read on the cached `WP_Post` (no query); for a `#[Meta]` property this is where `get_post_meta()` (or the family's meta function) fires; for relation attributes it runs the relation's query. + +> [!NOTE] +> A `get_{prop}()` accessor method on the model wins over the source attribute entirely — the attribute's `get()` is never called for that property. + +#### `public function maybe_convert_to_type( $property, $value ): mixed` + +Coerces a raw value to the property's declared PHP type. It runs at the end of every property resolution *and* on every default write (`Model::__set`), so both reads and writes are type-safe. + +| Declared type | Value | Conversion rule | +|---|---|---| +| Any nullable type | `null` or `''` | Short-circuits before everything else: returns the property's **declared default** (which may itself be `null`) | +| `int` / `integer` | any | `intval( $value )` | +| `float` | any | `floatval( $value )` | +| `string` | any | `strval( $value )` | +| `bool` / `boolean` | `'true'` / `'false'` string | `true` / `false` | +| `bool` / `boolean` | anything else | `boolval( $value )` | +| `array` | string | `json_decode( $value, true )` — JSON strings stored in meta decode transparently; malformed JSON yields `null`, not an exception | +| `array` | anything else | `(array)` cast | +| `object` | string | `json_decode( $value )` | +| `object` | anything else | `(object)` cast | +| An existing class name | any | Looks up that model's repository via the Manager and returns `$repository->get( $value )` | +| Anything else | any | Value returned unchanged | + +The class-name row is how relation auto-loading works: a property typed with a registered model class turns a raw ID into a loaded model. `Post::$parent` is typed `?Post`, so an integer runs through `PostRepository::get()` — which calls `get_post()` at the WordPress layer. + +```php +use Wpify\Model\Manager; +use Wpify\Model\PostRepository; + +$posts = ( new Manager() )->get_repository( PostRepository::class ); +$post = $posts->get( 42 ); +$parent = $posts->maybe_convert_to_type( $post->props()['parent'], 7 ); + +echo get_class( $parent ); // result: Wpify\Model\Post +``` + +> [!NOTE] +> If no repository is registered for the class, the `RepositoryNotFoundException` from the lookup is silently swallowed and the raw value is returned unchanged — a missing registration shows up as "my typed prop holds an int instead of a model", not as an error. + +> [!NOTE] +> Because of the nullable short-circuit, a nullable property never resolves to `''` — empty values collapse to the declared default. Pin the default you actually want in the property declaration. + +#### `protected function collect_persistable_props( ModelInterface $model ): array` + +The save-time helper for repository authors — protected, so it is only callable inside a repository subclass. It returns `array( 'data' => [...], 'meta' => [...] )` and behaves as follows: + +- Iterates `$model->props()`, skipping every `#[ReadOnlyProperty]` prop — readonly props are never persisted. +- If the model defines `persist_{prop}()`, that method is called immediately with the current value — side effect only; the value lands in **neither** bucket. +- Otherwise `#[SourceObject]` values go into `data`, keyed by the attribute's source key (falling back to the property name when the attribute has no key). +- Otherwise `#[Meta]` values go into `meta`, keyed by the attribute's meta key (falling back to the property name when the attribute has no key). +- Reading each collected value forces lazy resolution of every persist-hooked, `#[SourceObject]`, and `#[Meta]` prop, so collection itself can fire meta reads (`get_post_meta()` and friends). Relation and accessor props are skipped without ever being read. + +The built-ins map the buckets onto their own storage: `PostRepository` passes `meta` as `meta_input` inside one `wp_insert_post`/`wp_update_post` call, while `TermRepository` writes meta via `update_term_meta()` after `wp_insert_term`/`wp_update_term`. The full per-family table is in [persistence](../concepts/persistence.md). + +```php +collect_persistable_props( $model ); + + // $props['data'] — #[SourceObject] values, keyed by source key (or prop name). + // $props['meta'] — #[Meta] values, keyed by meta key (or prop name). + // Write both buckets to your storage here. + + return $model; + } + + // get(), delete(), find(), find_by_ids(), find_all() are also required + // by RepositoryInterface — implement them against the same storage. +} +``` + +> [!WARNING] +> Properties backed by relation attributes, `#[AccessorObject]`, or no attribute at all — and without a `persist_{prop}()` hook — are not collected: in a `save()` built only on `collect_persistable_props()` they are silently never written. (`PostRepository` and its subclasses additionally call each source attribute's own `persist()` method after insert/update — which is how `#[PostTermRelation]`/`#[PostTermsRelation]` props get written — and `#[AccessorObject]` props write through immediately on assignment.) If a prop must survive a `save()` built on this helper alone, give it `#[SourceObject]`, `#[Meta]`, or a `persist_{prop}()` method. Also call `collect_persistable_props()` exactly once per save: every call re-fires the model's `persist_*` hooks. + +## The storage surface + +`RepositoryInterface` requires six storage methods that every concrete repository implements itself. The base class defines none of them; what follows is the contract plus the convention the built-in repositories share. + +| Method | Contract | Convention across built-ins | +|---|---|---| +| `get( mixed $source ): ?ModelInterface` | Load one model | Accepts an ID, a raw WP/WC object, or an existing model; returns `null` when not found. Extra string semantics vary per family (slug or URL for posts, email or login for users, SKU for products, order key for orders) | +| `save( ModelInterface $model ): ModelInterface` | Persist and return the model | Throws `CouldNotSaveModelException` on failure; refreshes the model from the database afterwards (filterable via `wpify_model_refresh_model_after_save`) | +| `delete( ModelInterface $model, bool $force_delete = true ): bool` | Remove the model's storage row | `$force_delete` maps to the WP trash/force flag where the family supports one; several families ignore it | +| `find( array $args = [] ): array` | Query, return an array of models | Thin wrapper over the family's WP query (`WP_Query`, `get_terms`, `WP_User_Query`, …) with changed defaults per family | +| `find_by_ids( array $ids ): array` | Models for a list of IDs | — | +| `find_all( array $args = [] ): array` | Everything the repository manages | — | + +> [!NOTE] +> Signatures, argument defaults, and extra finders vary per family — for example, post `find()` defaults to `post_status => 'any'` while term `find()` hides empty terms by default. Always check the family page below (or the [querying guide](../guides/querying.md)) before relying on a default. + +Per-family documentation: + +| Page | Repositories covered | +|---|---| +| [Post family](models/post.md) | `PostRepository`, `PageRepository`, `AttachmentRepository` | +| [Term family](models/term.md) | `TermRepository`, `CategoryRepository`, `PostTagRepository` | +| [User](models/user.md) | `UserRepository` | +| [Comment](models/comment.md) | `CommentRepository` | +| [Site](models/site.md) | `SiteRepository` (multisite only) | +| [Menu](models/menu.md) | `MenuRepository`, `MenuItemRepository` | +| [Product](models/product.md) | `ProductRepository`, `ProductCatRepository` (WooCommerce only) | +| [Order](models/order.md) | `OrderRepository`, `OrderItemRepository` and item subclasses (WooCommerce only) | +| [Custom table repository](custom-table-repository.md) | `CustomTableRepository` | + +## Writing a custom repository + +In practice you almost never extend `Repository` directly — extend the built-in closest to your storage and override only its extension points: `PostRepository` for a custom post type (`model()` + `post_types()`), `TermRepository` for a custom taxonomy (`model()` + `taxonomy()`), `CustomTableRepository` for a custom database table (`model()` + `table_name()`). A minimal custom post type repository looks like this — the matching `Book` model is built step by step in the [custom post types guide](../guides/custom-post-types.md). + +```php +migrate(); +$events->migrate(); + +$case = $cases->transaction( function () use ( $cases, $items, $events ) { + $case = $cases->create( array( 'status' => 'received' ) ); + $cases->save( $case ); + // Save the related items and history using their repositories. + return $case; +} ); +``` + +The callback runs once. A successful callback commits; a thrown `Throwable` rolls back and is rethrown. A callback returning `false` is still successful: throw an exception to abort. Raw `$wpdb` failures must also be turned into exceptions by their caller; normal custom-table `save()` failures already throw `SqlException`. + +## Helper + +`Wpify\Model\Transaction` accepts one `wpdb` connection. Repositories can use it directly when they already control schema preparation: + +```php +use Wpify\Model\Transaction; + +$transaction = new Transaction( $wpdb ); +$result = $transaction->run( fn () => $repository->save( $record ) ); +``` + +| Method | Meaning | +| --- | --- | +| `__construct( wpdb $database )` | Use this connection for transaction statements. | +| `run( callable $operation ): mixed` | Run once, return the result or throw. | +| `is_active(): bool` | Probe whether the server has an open transaction using a temporary savepoint. Includes transactions started elsewhere. | +| `static is_running( wpdb $database ): bool` | Whether a library-managed callback is open on this `wpdb`; used by the migration guard. | + +When a transaction is already open, `run()` uses a unique savepoint. Success releases the savepoint; failure rolls back only to it. The outer caller retains the choice to commit or roll back. Different helper instances on the same connection can nest. No callback retry, deadlock retry or isolation-level change is performed. + +## Schema and side effects + +Prepare schema before starting the transaction. A pending lazy migration inside a library-managed callback throws `SqlException` before calling `dbDelta()`. The repository convenience method also refuses a pending automatic migration when joining a transaction owned elsewhere. Automatic migration disabled by the repository constructor stays disabled. + +Callbacks must not issue schema changes, manual commit/rollback or transaction-control SQL. MySQL may implicitly commit schema changes. The helper detects a lost transaction or changed connection before reporting success, but cannot undo already committed writes or reconstruct work lost by a reconnect. + +Transactions cover database rows only. WordPress hooks, caches, model instances, files, emails and external requests do not roll back. Prefer this helper for custom-table operations without external side effects. Keep external requests outside the callback and persist delivery intents with the business records. Reload models affected by a rollback and invalidate any caches your own hooks changed. Do not promise transactional WordPress/WooCommerce CRUD simply because it ran inside this callback. + +## Failures + +Failed transaction statements throw `SqlException`. A rollback failure throws `SqlException` with the original callback/commit failure available through `getPrevious()`. Treat connection-loss or commit ambiguity as an operation requiring reconciliation, rather than automatically rerunning the callback. + +See [custom tables](../guides/custom-tables.md) for model storage and [persistence](../concepts/persistence.md) for ordinary save behavior. + +On multisite, prepare schemas after switching to the participating shop. Shared repository schema caches follow the physical table, so an unmigrated table in another shop still needs preparation outside the transaction. diff --git a/docs/testing/checklist.md b/docs/testing/checklist.md index 6fd034c..584fd99 100644 --- a/docs/testing/checklist.md +++ b/docs/testing/checklist.md @@ -440,3 +440,14 @@ are never thrown; `Manager.php` imports nonexistent `Factories\DefaultStorageFac Bugs #1 and #28–#41 are fixed; every previously skipped test is now a passing regression test. Suite: **168 single-site + 8 multisite tests, 0 skips**. The only unchecked items left are the 3 unreachable WooCommerce `WP_Error` branches noted above. + +## Transactions + +- [x] `Transaction::run()` — root commit/rollback, callback result, nested savepoints, external ownership, failed transaction statements and lost-transaction detection +- [x] `Transaction::is_active()` — root and externally started transaction state +- [x] `Transaction::is_running()` — managed scope tracking and cleanup on failure +- [x] `CustomTableRepository::transaction()` — model rollback and migration preconditions +- [x] Shared custom-table repositories reset schema caches across shop switches +- [x] Schema upgrade preserves existing unique indexes and rows, updates the cached/stored version, and allows a subsequent transaction in the same request + +Transaction work verified on PHP 8.4 with wp-env: 180 single-site tests / 515 assertions, and 9 multisite tests / 27 assertions. diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..83bb8c5 --- /dev/null +++ b/llms.txt @@ -0,0 +1,52 @@ +# wpify/model + +> PHP 8 library giving WordPress data an object-oriented API: typed model classes with lazily resolved properties, repositories for all reads/writes, and a Manager wiring them together. Covers posts, terms, users, comments, sites, menus, WooCommerce products/orders, and custom database tables. + +Terminology is defined in CONTEXT.md; use it exactly. The rule: models hold the data, repositories talk to WordPress, the Manager wires them together. `create()` never persists — `save()` on the repository does. + +## Getting started + +- [Installation](docs/getting-started/installation.md): requirements, composer require, bootstrapping the Manager in a plugin, registering custom repositories +- [Quickstart](docs/getting-started/quickstart.md): full CRUD on the built-in Post model in numbered, pasteable steps, plus a first custom model + +## Concepts + +- [Architecture](docs/concepts/architecture.md): the Model/Repository/Manager split, how a property read flows, the 18 built-in repositories +- [Property resolution](docs/concepts/property-resolution.md): the lazy __get pipeline — cache, accessor methods, source attributes, type coercion, cache invalidation, readonly semantics +- [Persistence](docs/concepts/persistence.md): what create/save/delete actually do per model family, which WP functions they call, failure exceptions + +## Guides (task recipes) + +- [Custom post type models](docs/guides/custom-post-types.md): define a model + repository for a CPT with meta, computed props, relations, custom finders — the canonical extension example +- [Custom taxonomy models](docs/guides/custom-taxonomies.md): term model + repository for a custom taxonomy, term meta, parent/child, attaching terms to posts +- [Meta fields](docs/guides/meta-fields.md): #[Meta] keys, typed props, when meta is written per family, custom persistence +- [Model properties](docs/guides/model-properties.md): get_/set_/persist_ accessor methods, AliasOf, AccessorObject, ReadOnlyProperty, to_array +- [Relations](docs/guides/relations.md): every relation attribute with examples; which persist on save and which are read-only +- [Querying](docs/guides/querying.md): get() semantics per family, find() argument pass-through and changed defaults, finders, pagination +- [Custom tables](docs/guides/custom-tables.md): #[Column] schema, automatic migrations, CRUD, the array where-syntax, uninstall +- [WooCommerce models](docs/guides/woocommerce.md): products, orders, order items; requires WooCommerce; save/create semantics differ from WP models +- [Menus](docs/guides/menus.md): menus by theme location, nested MenuItem trees, rendering navigation +- [Multisite](docs/guides/multisite.md): Site models; multisite-only, immediate meta write-through +- [Troubleshooting](docs/guides/troubleshooting.md): error message → cause → fix, including the common traps + +## Reference + +- [Manager](docs/reference/manager.md): constructor, register_repository, get_repository vs get_model_repository, default repositories table +- [Model](docs/reference/model.md): base class API — source(), props(), refresh(), to_array(), magic accessors, ArrayAccess +- [Repository](docs/reference/repository.md): shared repository contract — create(), type coercion table, conventions concrete repositories follow +- [Attributes](docs/reference/attributes.md): all 17 PHP attributes with parameter tables, usage, and persistence behavior +- [Transactions](docs/reference/transactions.md): atomic custom-table writes, savepoint nesting, migration preparation and rollback limits +- [CustomTableRepository](docs/reference/custom-table-repository.md): constructor flags, migration/versioning, CRUD signatures, where-array grammar, exceptions +- [Post models](docs/reference/models/post.md): Post, Page, Attachment properties and PostRepository methods +- [Term models](docs/reference/models/term.md): Term, Category, PostTag properties and TermRepository methods +- [User model](docs/reference/models/user.md): User properties and UserRepository methods +- [Comment model](docs/reference/models/comment.md): Comment properties and CommentRepository methods +- [Site model](docs/reference/models/site.md): Site properties and SiteRepository methods (multisite) +- [Menu models](docs/reference/models/menu.md): Menu and MenuItem properties and repositories +- [Product models](docs/reference/models/product.md): Product and ProductCat properties and repositories (WooCommerce) +- [Order models](docs/reference/models/order.md): Order and order item models and repositories (WooCommerce) + +## Optional + +- [Domain glossary](CONTEXT.md): ubiquitous language for models, repositories, sources, resolution +- [Docs map for maintainers](docs/agents/docs-map.md): which pages to update when a source file changes diff --git a/src/CustomTableRepository.php b/src/CustomTableRepository.php index 247e638..5aba972 100644 --- a/src/CustomTableRepository.php +++ b/src/CustomTableRepository.php @@ -31,6 +31,19 @@ abstract class CustomTableRepository extends Repository { private string $current_version = ''; private bool $migrated = false; + private string $migration_table = ''; + + /** Reset schema caches when a shared repository switches physical tables. */ + private function prepare_table_context(): void { + $table = $this->prefixed_table_name(); + if ( $table !== $this->migration_table ) { + $this->migration_table = $table; + $this->sql = ''; + $this->version = ''; + $this->current_version = ''; + $this->migrated = false; + } + } /** * Repository constructor. @@ -64,6 +77,7 @@ private function reflection(): ReflectionClass { * @throws ReflectionException */ private function create_table_sql(): string { + $this->prepare_table_context(); if ( empty( $this->sql ) ) { $columns = array(); $unique_keys = array(); @@ -85,7 +99,7 @@ private function create_table_sql(): string { if ( count( $unique_keys ) > 0 ) { foreach ( $unique_keys as $unique_key ) { - $columns[] = sprintf( "UNIQUE KEY (%s)", $unique_key ); + $columns[] = sprintf( "UNIQUE KEY %s (%s)", $unique_key, $unique_key ); } } if ( count( $foreign_keys ) > 0 ) { @@ -162,6 +176,7 @@ public function primary_key( ?ModelInterface $model = null ): mixed { * @throws ReflectionException */ private function version(): string { + $this->prepare_table_context(); if ( empty( $this->version ) ) { $this->version = md5( $this->create_table_sql() ); @@ -178,7 +193,8 @@ private function version(): string { * @return string */ private function current_version( string $new_version = '' ): string { - if ( $this->current_version ) { + $this->prepare_table_context(); + if ( $this->current_version && '' === $new_version ) { return $this->current_version; } @@ -228,6 +244,7 @@ public function prefixed_table_name(): string { * @throws ReflectionException */ public function migrate(): void { + $this->prepare_table_context(); global $wpdb; if ( $this->migrated ) { @@ -238,6 +255,10 @@ public function migrate(): void { return; } + if ( Transaction::is_running( $this->db() ) ) { + throw new SqlException( 'Migrate custom tables before starting a transaction.' ); + } + if ( ! function_exists( 'dbDelta' ) ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } @@ -275,6 +296,28 @@ protected function db(): wpdb { return $wpdb; } + /** + * Run database writes atomically, preparing this repository before entry. + * + * Migrate any other participating custom tables before calling this method. + * + * @template T + * @param callable(): T $operation Database-only operation. + * @return T + * @throws SqlException When migration or transaction control fails. + */ + public function transaction( callable $operation ): mixed { + $transaction = new Transaction( $this->db() ); + if ( $transaction->is_active() && $this->auto_migrate && ! $this->migrated && $this->version() !== $this->current_version() ) { + throw new SqlException( 'Migrate custom tables before starting a transaction.' ); + } + $this->auto_migrate(); + if ( $this->auto_migrate && $this->version() !== $this->current_version() ) { + throw new SqlException( 'Could not migrate a transaction repository.' ); + } + return $transaction->run( $operation ); + } + /** * Returns the columns for the table. * @return array{ property:string, name:string, type:string, attribute:Column }[] diff --git a/src/Exceptions/ModelException.php b/src/Exceptions/ModelException.php index 32829a7..7bff3cd 100644 --- a/src/Exceptions/ModelException.php +++ b/src/Exceptions/ModelException.php @@ -4,6 +4,7 @@ namespace Wpify\Model\Exceptions; use Exception; +use Throwable; use WP_Error; class ModelException extends Exception { @@ -13,8 +14,8 @@ class ModelException extends Exception { */ private ?WP_Error $wp_error; - public function __construct( $message = '', $code = 0, $wp_error = null ) { - parent::__construct( $message, $code ); + public function __construct( $message = '', $code = 0, $wp_error = null, ?Throwable $previous = null ) { + parent::__construct( $message, $code, $previous ); $this->wp_error = $wp_error; } diff --git a/src/Transaction.php b/src/Transaction.php new file mode 100644 index 0000000..f9b6a80 --- /dev/null +++ b/src/Transaction.php @@ -0,0 +1,145 @@ +|null Active library-managed scopes per connection. */ + private static ?WeakMap $scopes = null; + + /** + * @param wpdb $database Connection used by every participating repository. + */ + public function __construct( private wpdb $database ) { + } + + /** + * Whether a library-managed scope is currently open on this wpdb object. + * + * Used to prevent lazy migrations from implicitly committing a transaction. + */ + public static function is_running( wpdb $database ): bool { + return ( self::$scopes[ $database ] ?? 0 ) > 0; + } + + /** + * Detect an existing transaction without committing or starting one. + * + * SAVEPOINT outside a transaction succeeds but has no effect; releasing it + * then returns MySQL error 1305. Inside a transaction both statements succeed. + * This avoids MariaDB-only variables and performance_schema permissions. + * + * @throws SqlException When the probe fails for any other reason. + */ + public function is_active(): bool { + $name = 'wpify_probe_' . bin2hex( random_bytes( 12 ) ); + $this->execute( 'SAVEPOINT ' . $name ); + $connection = $this->connection(); + $suppressed = $this->database->suppress_errors( true ); + try { + $result = $this->database->query( 'RELEASE SAVEPOINT ' . $name ); + if ( $this->connection() !== $connection ) { + throw new SqlException( 'The database connection changed during a transaction statement.' ); + } + if ( false !== $result ) { + return true; + } + if ( 1305 !== $connection->errno ) { + throw new SqlException( 'Transaction statement failed: ' . $this->database->last_error ); + } + // Clear the expected missing-savepoint error before repository operations. + $this->execute( 'SELECT 1', $connection ); + return false; + } finally { + $this->database->suppress_errors( $suppressed ); + } + } + + /** + * Run an operation atomically, returning its value and rethrowing its failure. + * + * An existing transaction is joined with a uniquely named savepoint. Success + * releases that savepoint; failure rolls back only this scope. Never commits + * a transaction owned by the caller. There are no automatic callback retries. + * + * @template T + * @param callable(): T $operation Database-only operation. + * @return T + * @throws Throwable The callback's error, or SqlException on transaction failure. + */ + public function run( callable $operation ): mixed { + $nested = $this->is_active(); + $connection = $this->connection(); + $savepoint = 'wpify_model_' . bin2hex( random_bytes( 12 ) ); + $this->execute( $nested ? 'SAVEPOINT ' . $savepoint : 'START TRANSACTION', $connection ); + self::$scopes ??= new WeakMap(); + self::$scopes[ $this->database ] = ( self::$scopes[ $this->database ] ?? 0 ) + 1; + + try { + $this->assert_active( $connection ); + $result = $operation(); + $this->assert_active( $connection ); + $this->execute( $nested ? 'RELEASE SAVEPOINT ' . $savepoint : 'COMMIT', $connection ); + return $result; + } catch ( Throwable $error ) { + try { + // Do not issue rollback on a replacement connection or after a lost + // transaction. That could affect unrelated work after a reconnect. + if ( $this->connection() === $connection && $this->is_active() && $this->connection() === $connection ) { + $this->execute( $nested ? 'ROLLBACK TO SAVEPOINT ' . $savepoint : 'ROLLBACK', $connection ); + if ( $nested ) { + $this->execute( 'RELEASE SAVEPOINT ' . $savepoint, $connection ); + } + } + } catch ( Throwable $rollback_error ) { + throw new SqlException( 'Transaction rollback failed: ' . $rollback_error->getMessage(), 0, null, $error ); + } + throw $error; + } finally { + self::$scopes[ $this->database ] = self::$scopes[ $this->database ] - 1; + if ( 0 === self::$scopes[ $this->database ] ) { + unset( self::$scopes[ $this->database ] ); + } + } + } + + /** @throws SqlException When the transaction disappeared or the connection changed. */ + private function assert_active( mysqli $connection ): void { + if ( ! $this->is_active() || $this->connection() !== $connection ) { + throw new SqlException( 'Transaction was lost or the database connection changed.' ); + } + } + + /** @throws SqlException When wpdb does not expose a supported connection. */ + private function connection(): mysqli { + $connection = $this->database->dbh; + if ( ! $connection instanceof mysqli ) { + throw new SqlException( 'Transactions require a mysqli-backed wpdb connection.' ); + } + return $connection; + } + + /** @throws SqlException When a transaction statement fails or reconnects. */ + private function execute( string $sql, ?mysqli $connection = null ): void { + if ( false === $this->database->query( $sql ) ) { + throw new SqlException( 'Transaction statement failed: ' . $this->database->last_error ); + } + if ( $connection && $this->connection() !== $connection ) { + throw new SqlException( 'The database connection changed during a transaction statement.' ); + } + } +} diff --git a/tests/integration/CustomTableMultisiteTest.php b/tests/integration/CustomTableMultisiteTest.php new file mode 100644 index 0000000..cbcef0e --- /dev/null +++ b/tests/integration/CustomTableMultisiteTest.php @@ -0,0 +1,39 @@ +manager->register_repository( $repo ); + $repo->migrate(); + $main_table = $repo->prefixed_table_name(); + $site_id = (int) self::factory()->blog->create(); + switch_to_blog( $site_id ); + try { + delete_option( 'custom_table_wpify_test_records_version' ); + $repo->migrate(); + $record = $repo->create(); + $record->title = 'Other shop'; + $record->code = 'shop-two'; + $repo->save( $record ); + $this->assertNotSame( $main_table, $repo->prefixed_table_name() ); + $this->assertSame( 'Other shop', $repo->get( $record->id )->title ); + $this->assertNotEmpty( get_option( 'custom_table_wpify_test_records_version' ) ); + $wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS ' . $repo->prefixed_table_name() ); + } finally { + restore_current_blog(); + $repo->migrate(); + $this->assertSame( $main_table, $repo->prefixed_table_name() ); + $this->assertSame( array(), $repo->find() ); + $wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS ' . $main_table ); + } + } +} diff --git a/tests/integration/CustomTableTest.php b/tests/integration/CustomTableTest.php index c616f4b..2ec7df5 100644 --- a/tests/integration/CustomTableTest.php +++ b/tests/integration/CustomTableTest.php @@ -80,6 +80,60 @@ public function test_migrate_creates_the_table(): void { $this->assertContains( 'payload', $columns ); } + public function test_migration_preserves_existing_unique_indexes_and_rows(): void { + global $wpdb; + $this->records->migrate(); + $record = $this->make_record( 'Before upgrade', 1, 'unique-before-upgrade' ); + // Force dbDelta over the existing schema, as happens after adding a column. + update_option( 'custom_table_wpify_test_records_version', 'previous-schema-version' ); + $fresh = new RecordRepository(); + $this->manager->register_repository( $fresh ); + $fresh->migrate(); + $this->assertSame( '', $wpdb->last_error ); + $this->assertSame( 'Before upgrade', $fresh->get( $record->id )->title ); + $this->assertNotSame( 'previous-schema-version', get_option( 'custom_table_wpify_test_records_version' ) ); + $this->assertTrue( $fresh->transaction( static fn(): bool => true ) ); + $indexes = $wpdb->get_results( "SHOW INDEX FROM {$wpdb->prefix}wpify_test_records WHERE Key_name = 'code'" ); + $this->assertCount( 1, $indexes ); + $this->assertSame( '0', (string) $indexes[0]->Non_unique ); + } + + public function test_transaction_rolls_back_model_writes_and_preserves_outer_transaction(): void { + // WordPress's test isolation already owns the outer transaction. + $this->records->migrate(); + try { + $this->records->transaction( function (): void { + $this->make_record( 'Rolled back' ); + throw new \RuntimeException( 'Abort operation' ); + } ); + $this->fail( 'Expected callback failure.' ); + } catch ( \RuntimeException $error ) { + $this->assertSame( 'Abort operation', $error->getMessage() ); + } + $this->assertSame( array(), $this->records->find() ); + $this->assertTrue( ( new \Wpify\Model\Transaction( $GLOBALS['wpdb'] ) )->is_active() ); + $this->assertSame( 42, $this->records->transaction( static fn(): int => 42 ) ); + } + + public function test_lazy_migration_is_refused_inside_a_managed_transaction(): void { + $this->records->migrate(); + $late = new class() extends RecordRepository { + public function table_name(): string { + return 'wpify_test_late_transaction_table'; + } + }; + delete_option( 'custom_table_wpify_test_late_transaction_table_version' ); + try { + $this->records->transaction( function () use ( $late ): void { + $late->migrate(); + } ); + $this->fail( 'Expected migration guard.' ); + } catch ( SqlException $error ) { + $this->assertSame( 'Migrate custom tables before starting a transaction.', $error->getMessage() ); + } + $this->assertTrue( ( new \Wpify\Model\Transaction( $GLOBALS['wpdb'] ) )->is_active() ); + } + public function test_columns_describes_all_column_props(): void { $columns = $this->records->columns(); diff --git a/tests/integration/TransactionTest.php b/tests/integration/TransactionTest.php new file mode 100644 index 0000000..dd6a641 --- /dev/null +++ b/tests/integration/TransactionTest.php @@ -0,0 +1,193 @@ +database = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST ); + $this->database->suppress_errors( true ); + $this->database->query( 'CREATE TEMPORARY TABLE wpify_transaction_test (value varchar(40) NOT NULL) ENGINE=InnoDB' ); + $this->assertSame( '', $this->database->last_error ); + $this->transactions = new Transaction( $this->database ); + } + + public function tear_down(): void { + $this->database->query( 'ROLLBACK' ); + $this->database->query( 'DROP TEMPORARY TABLE IF EXISTS wpify_transaction_test' ); + $this->database->close(); + parent::tear_down(); + } + + private function insert( string $value ): void { + $this->assertSame( 1, $this->database->insert( 'wpify_transaction_test', array( 'value' => $value ) ) ); + } + + private function values(): array { + return $this->database->get_col( 'SELECT value FROM wpify_transaction_test ORDER BY value' ); + } + + public function test_root_transaction_commits_and_returns_callback_value(): void { + $result = $this->transactions->run( function (): int { + $this->assertTrue( Transaction::is_running( $this->database ) ); + $this->insert( 'committed' ); + return 42; + } ); + $this->assertSame( 42, $result ); + $this->assertSame( array( 'committed' ), $this->values() ); + $this->assertFalse( $this->transactions->is_active() ); + $this->assertFalse( Transaction::is_running( $this->database ) ); + } + + public function test_throwable_rolls_back_and_rethrows_the_original_object(): void { + $error = new Error( 'Callback failed' ); + try { + $this->transactions->run( function () use ( $error ): void { + $this->insert( 'rolled back' ); + throw $error; + } ); + $this->fail( 'Expected the callback error.' ); + } catch ( Error $caught ) { + $this->assertSame( $error, $caught ); + } + $this->assertSame( array(), $this->values() ); + $this->assertFalse( $this->transactions->is_active() ); + $this->assertFalse( Transaction::is_running( $this->database ) ); + } + + public function test_nested_instances_roll_back_only_the_failed_scope(): void { + $this->transactions->run( function (): void { + $this->insert( 'outer' ); + try { + ( new Transaction( $this->database ) )->run( function (): void { + $this->insert( 'inner failed' ); + throw new RuntimeException( 'Abort inner' ); + } ); + } catch ( RuntimeException $error ) { + $this->assertSame( 'Abort inner', $error->getMessage() ); + } + $this->assertTrue( Transaction::is_running( $this->database ) ); + $this->transactions->run( function (): void { + $this->insert( 'inner success' ); + } ); + } ); + $this->assertSame( array( 'inner success', 'outer' ), $this->values() ); + $this->assertFalse( Transaction::is_running( $this->database ) ); + } + + public function test_outer_failure_undoes_successful_inner_scope(): void { + try { + $this->transactions->run( function (): void { + $this->transactions->run( function (): void { + $this->insert( 'inner' ); + } ); + throw new RuntimeException( 'Abort outer' ); + } ); + } catch ( RuntimeException $error ) { + $this->assertSame( 'Abort outer', $error->getMessage() ); + } + $this->assertSame( array(), $this->values() ); + } + + public function test_external_transaction_keeps_ownership_on_success_and_failure(): void { + $this->database->query( 'START TRANSACTION' ); + $this->insert( 'external' ); + $this->transactions->run( function (): void { + $this->insert( 'joined' ); + } ); + try { + $this->transactions->run( function (): void { + $this->insert( 'failed' ); + throw new RuntimeException( 'Abort joined scope' ); + } ); + } catch ( RuntimeException $error ) { + $this->assertSame( 'Abort joined scope', $error->getMessage() ); + } + $this->assertTrue( $this->transactions->is_active() ); + $this->assertSame( array( 'external', 'joined' ), $this->values() ); + $this->database->query( 'ROLLBACK' ); + $this->assertSame( array(), $this->values() ); + } + + public function test_failed_start_does_not_invoke_callback(): void { + $called = false; + $filter = static fn( string $sql ): string => 'START TRANSACTION' === $sql ? 'INVALID TRANSACTION STATEMENT' : $sql; + add_filter( 'query', $filter ); + try { + $this->transactions->run( function () use ( &$called ): void { + $called = true; + } ); + $this->fail( 'Expected a failed start.' ); + } catch ( SqlException $error ) { + $this->assertStringContainsString( 'Transaction statement failed:', $error->getMessage() ); + } finally { + remove_filter( 'query', $filter ); + } + $this->assertFalse( $called ); + $this->assertFalse( Transaction::is_running( $this->database ) ); + } + + public function test_failed_commit_rolls_back_instead_of_reporting_success(): void { + $filter = static fn( string $sql ): string => 'COMMIT' === $sql ? 'INVALID TRANSACTION STATEMENT' : $sql; + add_filter( 'query', $filter ); + try { + $this->transactions->run( function (): void { + $this->insert( 'not committed' ); + } ); + $this->fail( 'Expected a failed commit.' ); + } catch ( SqlException $error ) { + $this->assertStringContainsString( 'Transaction statement failed:', $error->getMessage() ); + } finally { + remove_filter( 'query', $filter ); + } + $this->assertSame( array(), $this->values() ); + $this->assertFalse( $this->transactions->is_active() ); + } + + public function test_failed_rollback_retains_the_original_failure_as_previous(): void { + $original = new RuntimeException( 'Business failure' ); + $filter = static fn( string $sql ): string => 'ROLLBACK' === $sql ? 'INVALID TRANSACTION STATEMENT' : $sql; + add_filter( 'query', $filter ); + try { + $this->transactions->run( function () use ( $original ): void { + $this->insert( 'pending' ); + throw $original; + } ); + $this->fail( 'Expected rollback failure.' ); + } catch ( SqlException $error ) { + $this->assertStringContainsString( 'Transaction rollback failed:', $error->getMessage() ); + $this->assertSame( $original, $error->getPrevious() ); + } finally { + remove_filter( 'query', $filter ); + } + $this->assertFalse( Transaction::is_running( $this->database ) ); + } + + public function test_lost_transaction_cannot_report_success(): void { + try { + $this->transactions->run( function (): void { + $this->insert( 'already committed' ); + $this->database->query( 'COMMIT' ); + } ); + $this->fail( 'Expected detection of the lost transaction.' ); + } catch ( SqlException $error ) { + $this->assertStringContainsString( 'Transaction was lost', $error->getMessage() ); + } + // Detection cannot undo writes already committed by unsupported callback SQL. + $this->assertSame( array( 'already committed' ), $this->values() ); + } +}