├── .gitignore
├── fixtures
├── assets
│ └── dist
│ │ ├── css
│ │ └── test-style.asset.php
│ │ └── js
│ │ └── test-script.asset.php
└── classes
│ ├── Loadable
│ ├── BaseClass.php
│ ├── ChildClass.php
│ └── InvalidChildClass.php
│ ├── TraitTests.php
│ ├── Standalone
│ └── Standalone.php
│ ├── Taxonomies
│ └── Demo.php
│ └── PostTypes
│ ├── Page.php
│ ├── Post.php
│ └── Demo.php
├── tests
├── bootstrap.php
├── PostTypes
│ └── AbstractPostTypeTest.php
├── Taxonomies
│ └── AbstractTaxonomyTest.php
├── FrameworkTestSetup.php
├── Assets
│ └── GetAssetInfoTest.php
└── ModuleInitializationTest.php
├── phpstan.neon
├── phpcs.xml
├── phpunit.xml.dist
├── src
├── ModuleInterface.php
├── Module.php
├── PostTypes
│ ├── AbstractCorePostType.php
│ └── AbstractPostType.php
├── Assets
│ └── GetAssetInfo.php
├── Taxonomies
│ └── AbstractTaxonomy.php
└── ModuleInitialization.php
├── CREDITS.md
├── CHANGELOG.md
├── .github
└── workflows
│ └── php.yml
├── composer.json
├── docs
├── README.md
├── Asset-Loading.md
├── Autoloading.md
├── Taxonomies.md
├── Modules-and-Initialization.md
└── Post-Types.md
├── CONTRIBUTING.md
├── README.md
├── CODE_OF_CONDUCT.md
└── LICENSE.md
/.gitignore:
--------------------------------------------------------------------------------
1 | vendor/
2 | coverage/
3 | .phpunit.result.cache
4 |
--------------------------------------------------------------------------------
/fixtures/assets/dist/css/test-style.asset.php:
--------------------------------------------------------------------------------
1 | array( 'test-style-deps' ), 'version' => 'test-style-version');
2 |
--------------------------------------------------------------------------------
/fixtures/assets/dist/js/test-script.asset.php:
--------------------------------------------------------------------------------
1 | array( 'test-script-deps' ), 'version' => 'test-script-version');
2 |
--------------------------------------------------------------------------------
/tests/bootstrap.php:
--------------------------------------------------------------------------------
1 | etc.
18 | - '#no value type specified in iterable type array#'
19 |
--------------------------------------------------------------------------------
/phpcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 10up PHPCS extended.
4 |
5 |
6 | fixtures
7 | src
8 | tests
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 | ./src/
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | ./tests/
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/ModuleInterface.php:
--------------------------------------------------------------------------------
1 | register();
33 |
34 | $this->assertArrayHasKey( $class->get_name(), self::$registered_post_types );
35 | $this->assertEquals( $class->get_plural_label(), self::$registered_post_types['tenup-demo']['labels']['name'] );
36 | $this->assertEquals( $class->get_singular_label(), self::$registered_post_types['tenup-demo']['labels']['singular_name'] );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tests/Taxonomies/AbstractTaxonomyTest.php:
--------------------------------------------------------------------------------
1 | register();
33 |
34 | $this->assertArrayHasKey( $class->get_name(), self::$registered_taxonomies );
35 | $this->assertEquals( $class->get_plural_label(), self::$registered_taxonomies['tenup-tax-demo']['labels']['name'] );
36 | $this->assertEquals( $class->get_singular_label(), self::$registered_taxonomies['tenup-tax-demo']['labels']['singular_name'] );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/fixtures/classes/Taxonomies/Demo.php:
--------------------------------------------------------------------------------
1 |
36 | */
37 | public function get_supported_taxonomies() {
38 | return [];
39 | }
40 |
41 | /**
42 | * Run any code after the post type has been registered.
43 | *
44 | * @return void
45 | */
46 | public function after_register() {
47 | // Do nothing.
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/CREDITS.md:
--------------------------------------------------------------------------------
1 | # Credits
2 |
3 | The following acknowledges the Maintainers for this repository, those who have Contributed to this repository (via bug reports, code, design, ideas, project management, translation, testing, etc.), and any Libraries utilized.
4 |
5 | ## Maintainers
6 |
7 | The following individuals are responsible for curating the list of issues, responding to pull requests, and ensuring regular releases happen.
8 |
9 | [Daryll Doyle (@darylldoyle)](https://github.com/darylldoyle), [Taylor Lovett (@tlovett1)](https://github.com/tlovett1).
10 |
11 | ## Contributors
12 |
13 | Thank you to all the people who have already contributed to this repository via bug reports, code, design, ideas, project management, translation, testing, etc.
14 |
15 | [Daryll Doyle (@darylldoyle)](https://github.com/darylldoyle), [Taylor Lovett (@tlovett1)](https://github.com/tlovett1), [Clayton Collie (@claytoncollie)](https://github.com/claytoncollie), [Sérgio Santos (@s3rgiosan)](https://github.com/s3rgiosan), [Jeffrey Paul (@jeffpaul)](https://github.com/jeffpaul).
16 |
17 | ## Libraries
18 |
19 | The following software libraries are utilized in this repository.
20 |
21 | n/a
22 |
--------------------------------------------------------------------------------
/fixtures/classes/PostTypes/Post.php:
--------------------------------------------------------------------------------
1 |
38 | */
39 | public function get_supported_taxonomies() {
40 | return [];
41 | }
42 |
43 | /**
44 | * Run any code after the post type has been registered.
45 | *
46 | * @return void
47 | */
48 | public function after_register() {
49 | // Do nothing.
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file, per [the Keep a Changelog standard](http://keepachangelog.com/) and will adhere to [Semantic Versioning](http://semver.org/).
4 |
5 | ## [Unreleased] - TBD
6 |
7 | ## [1.2.0] - 2025-03-20
8 | ### Changed
9 | - Lowered the minimum required PHP version from 8.3 to 8.2 (props [@s3rgiosan](https://github.com/s3rgiosan) via [#8](https://github.com/10up/wp-framework/pull/8)).
10 |
11 | ## [1.1.0] - 2025-03-13
12 | ### Added
13 | - Asset loading functionality (props [@darylldoyle](https://github.com/darylldoyle), [@darylldoyle](https://github.com/darylldoyle) via [#5](https://github.com/10up/wp-framework/pull/5)).
14 |
15 | ### Changed
16 | - Use project-based lint commands instead of global reference (props [@claytoncollie](https://github.com/claytoncollie) in [#2](https://github.com/10up/wp-framework/pull/2)).
17 | - Specify `WordPress.WP.I18n.MissingTranslatorsComment` rule in AbstractTaxonomy class (props [@s3rgiosan](https://github.com/s3rgiosan), [@darylldoyle](https://github.com/darylldoyle) via [#4](https://github.com/10up/wp-framework/pull/4)).
18 |
19 | ## [1.0.0] - 2025-01-09
20 | - Base repo and readme creation
21 |
22 | [Unreleased]: https://github.com/10up/wp-framework/compare/trunk...develop
23 | [1.2.0]: https://github.com/10up/wp-framework/compare/1.1.0...1.2.0
24 | [1.1.0]: https://github.com/10up/wp-framework/compare/1.0.0...1.1.0
25 | [1.0.0]: https://github.com/10up/wp-framework/commit/341fc55c8abf302380ad0d1e269b13366bdd710a
26 |
--------------------------------------------------------------------------------
/.github/workflows/php.yml:
--------------------------------------------------------------------------------
1 | name: PHP Checks
2 |
3 | on:
4 | push:
5 | branches: ["trunk", "develop"]
6 | pull_request:
7 | branches: ["trunk", "develop"]
8 |
9 | permissions:
10 | contents: read
11 |
12 | env:
13 | PHP_VERSION: "8.3"
14 |
15 | jobs:
16 | lint:
17 | name: Linting
18 | runs-on: ubuntu-latest
19 |
20 | steps:
21 | - uses: actions/checkout@v3
22 |
23 | - name: Setup PHP with composer v2
24 | uses: shivammathur/setup-php@v2
25 | with:
26 | php-version: ${{ env.PHP_EXTENSIONS }}
27 | tools: composer:v2
28 |
29 | - name: Validate composer.json and composer.lock
30 | run: composer validate --strict
31 |
32 | - name: Install dependencies
33 | run: composer install --prefer-dist --no-progress
34 |
35 | - name: Run PHPCS
36 | run: composer run lint
37 |
38 | static-analysis:
39 | name: Static Analysis
40 | runs-on: ubuntu-latest
41 |
42 | steps:
43 | - uses: actions/checkout@v3
44 |
45 | - name: Setup PHP with composer v2
46 | uses: shivammathur/setup-php@v2
47 | with:
48 | php-version: ${{ env.PHP_EXTENSIONS }}
49 | tools: composer:v2
50 |
51 | - name: Install dependencies
52 | run: composer install --no-progress --no-suggest
53 |
54 | - name: Run PHPStan
55 | run: composer run static
56 |
57 | test:
58 | name: Unit Tests
59 | runs-on: ubuntu-latest
60 |
61 | steps:
62 | - uses: actions/checkout@v3
63 |
64 | - name: Setup PHP with composer v2
65 | uses: shivammathur/setup-php@v2
66 | with:
67 | php-version: ${{ env.PHP_EXTENSIONS }}
68 | tools: composer:v2
69 |
70 | - name: Install dependencies
71 | run: composer install --no-progress --no-suggest
72 |
73 | - name: Run PHPUnit
74 | run: composer run test
75 |
--------------------------------------------------------------------------------
/fixtures/classes/PostTypes/Demo.php:
--------------------------------------------------------------------------------
1 |
73 | */
74 | public function get_supported_taxonomies() {
75 | return [
76 | 'tenup-tax-demo',
77 | ];
78 | }
79 |
80 | /**
81 | * Run any code after the post type has been registered.
82 | *
83 | * @return void
84 | */
85 | public function after_register() {
86 | // Register any hooks/filters you need.
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/PostTypes/AbstractCorePostType.php:
--------------------------------------------------------------------------------
1 | get_name() to get the post's type name.
69 | * @return Bool Whether this theme has supports for this post type.
70 | */
71 | public function register() {
72 | $this->register_taxonomies();
73 | $this->after_register();
74 |
75 | return true;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "10up/wp-framework",
3 | "description": "A PHP package designed to simplify the development of WordPress themes and plugins by centralizing shared functionality.",
4 | "type": "library",
5 | "homepage": "https://github.com/10up/wp-framework",
6 | "license": "GPL-2.0-or-later",
7 | "authors": [
8 | {
9 | "name": "Daryll Doyle",
10 | "email": "daryll.doyle@10up.com",
11 | "homepage": "https://enshrined.co.uk/",
12 | "role": "Developer"
13 | },
14 | {
15 | "name": "10up",
16 | "email": "opensource@10up.com",
17 | "homepage": "https://10up.com",
18 | "role": "Developer"
19 | }
20 | ],
21 | "autoload": {
22 | "psr-4": {
23 | "TenupFramework\\": "src/"
24 | }
25 | },
26 | "autoload-dev": {
27 | "psr-4": {
28 | "TenupFrameworkTests\\": "tests/",
29 | "TenupFrameworkTestClasses\\": "fixtures/classes/"
30 | }
31 | },
32 | "require": {
33 | "php": ">=8.2",
34 | "spatie/php-structure-discoverer": "^2.2"
35 | },
36 | "require-dev": {
37 | "phpunit/phpunit": "^9.5",
38 | "yoast/phpunit-polyfills": "^2.0",
39 | "brain/monkey": "^2.6",
40 | "szepeviktor/phpstan-wordpress": "^2.0",
41 | "php-stubs/wp-cli-stubs": "^2.11",
42 | "phpstan/phpstan-deprecation-rules": "^2.0",
43 | "10up/phpcs-composer": "^3.0",
44 | "phpcompatibility/php-compatibility": "dev-develop as 9.99.99",
45 | "phpunit/php-code-coverage": "^9.2",
46 | "slevomat/coding-standard": "^8.15"
47 | },
48 | "scripts": {
49 | "test": "XDEBUG_MODE=coverage ./vendor/bin/phpunit",
50 | "lint": "./vendor/bin/phpcs --standard=./phpcs.xml",
51 | "lint-fix": "./vendor/bin/phpcbf --standard=./phpcs.xml",
52 | "static": [
53 | "Composer\\Config::disableProcessTimeout",
54 | "phpstan --memory-limit=1G"
55 | ]
56 | },
57 | "config": {
58 | "allow-plugins": {
59 | "dealerdirect/phpcodesniffer-composer-installer": true
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/tests/FrameworkTestSetup.php:
--------------------------------------------------------------------------------
1 |
34 | */
35 | public static $registered_taxonomies = [];
36 |
37 | /**
38 | * Registered post types.
39 | *
40 | * @var array
41 | */
42 | public static $registered_post_types = [];
43 |
44 | /**
45 | * Set up the test.
46 | *
47 | * @return void
48 | */
49 | protected function setUp(): void { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
50 | parent::setUp();
51 | Monkey\setUp();
52 |
53 | stubs(
54 | [
55 | 'wp_get_environment_type' => 'local',
56 | 'sanitize_title' => function ( $title ) {
57 | return str_replace( ' ', '-', strtolower( $title ) );
58 | },
59 | 'register_post_type' => function ( $slug, $args ) {
60 | self::$registered_post_types[ $slug ] = $args;
61 | },
62 | 'register_taxonomy_for_object_type' => '__return_true',
63 | 'register_taxonomy' => function ( $slug, $object_type, $args ) {
64 | self::$registered_taxonomies[ $slug ] = $args;
65 | },
66 | ]
67 | );
68 |
69 | stubEscapeFunctions();
70 | stubTranslationFunctions();
71 | }
72 |
73 | /**
74 | * Tear down the test.
75 | *
76 | * @return void
77 | */
78 | protected function tearDown(): void { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
79 | self::$registered_taxonomies = [];
80 | self::$registered_post_types = [];
81 |
82 | Monkey\tearDown();
83 | parent::tearDown();
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # WP Framework Documentation
2 |
3 | WP Framework is a lightweight set of building blocks for structuring WordPress plugins and themes around small, composable Modules. It provides:
4 | - Module discovery and initialization (with a predictable lifecycle)
5 | - Base classes for custom and core post types
6 | - Base class for taxonomies
7 | - Asset helpers that read modern build sidecars (`.asset.php`)
8 |
9 | ## Who is this for?
10 | - External engineers — Start here: follow the Quick Start and then read Autoloading and Modules → Modules and Initialization → Post Types/Taxonomies → Asset Loading.
11 | - Internal engineers — Concepts: jump straight to Modules and Initialization and the specific Post Types/Taxonomies APIs. Skim the Quick Start for constants and bootstrap.
12 | - Non‑technical stakeholders — Overview: This framework standardizes how we register types, taxonomies, and assets so teams ship features faster with less boilerplate and more consistency.
13 |
14 | ## Quick Start (at a glance)
15 | 1) Add PSR-4 autoloading in composer.json for your project namespace (inc/ or src/).
16 | 2) Define constants (`YOUR_PLUGIN_PATH`, `YOUR_PLUGIN_URL`, `YOUR_PLUGIN_INC`, `YOUR_PLUGIN_VERSION`) in your plugin/theme bootstrap.
17 | 3) Initialize modules: `TenupFramework\ModuleInitialization::instance()->init_classes( YOUR_PLUGIN_INC )`.
18 | 4) Implement small classes that implement `ModuleInterface` (use the `Module` trait) and optionally extend `AbstractPostType` / `AbstractTaxonomy`.
19 | 5) Load assets via the `GetAssetInfo` trait using dist/.asset.php sidecars.
20 |
21 | ## Table of Contents
22 | - [Autoloading and Modules](Autoloading.md) — how classes are discovered and initialized
23 | - [Modules and Initialization](Modules-and-Initialization.md)
24 | - [Post Types](Post-Types.md) — building custom and core post type integrations
25 | - [Taxonomies](Taxonomies.md) — registering and configuring taxonomies
26 | - [Asset Loading](Asset-Loading.md) — working with dist/.asset.php for dependencies and versioning
27 |
28 | ## Conventions
29 | - Namespaces: use your project namespace (e.g., `YourVendor\\YourPlugin`) for app code; reference framework classes via the TenupFramework namespace.
30 | - Translation: return translated strings from label methods using the correct text domain.
31 | - Keep Modules small and focused; guard execution in `can_register()` to keep admin/frontend/REST behaviors tidy.
32 |
--------------------------------------------------------------------------------
/src/Assets/GetAssetInfo.php:
--------------------------------------------------------------------------------
1 | dist_path = trailingslashit( $dist_path );
45 | $this->fallback_version = $fallback_version;
46 | }
47 |
48 | /**
49 | * Get asset info from extracted asset files
50 | *
51 | * @param string $slug Asset slug as defined in build/webpack configuration
52 | * @param ?string $attribute Optional attribute to get. Can be version or dependencies
53 | *
54 | * @throws RuntimeException If asset variables are not set
55 | *
56 | * @return string|($attribute is null ? array{version: string, dependencies: array} : $attribute is'dependencies' ? array : string)
57 | */
58 | public function get_asset_info( string $slug, ?string $attribute = null ) {
59 |
60 | if ( is_null( $this->dist_path ) || is_null( $this->fallback_version ) ) {
61 | throw new RuntimeException( 'Asset variables not set. Please run setup_asset_vars() before calling get_asset_info().' );
62 | }
63 |
64 | if ( file_exists( $this->dist_path . 'js/' . $slug . '.asset.php' ) ) {
65 | $asset = require $this->dist_path . 'js/' . $slug . '.asset.php';
66 | } elseif ( file_exists( $this->dist_path . 'css/' . $slug . '.asset.php' ) ) {
67 | $asset = require $this->dist_path . 'css/' . $slug . '.asset.php';
68 | } elseif ( file_exists( $this->dist_path . 'blocks/' . $slug . '.asset.php' ) ) {
69 | $asset = require $this->dist_path . 'blocks/' . $slug . '.asset.php';
70 | } else {
71 | $asset = [
72 | 'version' => $this->fallback_version,
73 | 'dependencies' => [],
74 | ];
75 | }
76 |
77 | // phpcs:ignore Generic.Commenting.DocComment.MissingShort
78 | /** @var array{version: string, dependencies: array} $asset */
79 |
80 | if ( empty( $attribute ) ) {
81 | return $asset;
82 | }
83 |
84 | if ( isset( $asset[ $attribute ] ) ) {
85 | return $asset[ $attribute ];
86 | }
87 |
88 | return '';
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing and Maintaining
2 |
3 | First, thank you for taking the time to contribute!
4 |
5 | The following is a set of guidelines for contributors as well as information and instructions around our maintenance process. The two are closely tied together in terms of how we all work together and set expectations, so while you may not need to know everything in here to submit an issue or pull request, it's best to keep them in the same document.
6 |
7 | ## Ways to contribute
8 |
9 | Contributing isn't just writing code - it's anything that improves the project. All contributions are managed right here on GitHub. Here are some ways you can help:
10 |
11 | ### Reporting bugs
12 |
13 | If you're running into an issue, please take a look through [existing issues](https://github.com/10up/wp-framework/issues) and [open a new one](https://github.com/10up/wp-framework/issues/new) if needed. If you're able, include steps to reproduce, environment information, and screenshots/screencasts as relevant.
14 |
15 | ### Suggesting enhancements
16 |
17 | New features and enhancements are also managed via [issues](https://github.com/10up/wp-framework/issues).
18 |
19 | ### Pull requests
20 |
21 | Pull requests represent a proposed solution to a specified problem. They should always reference an issue that describes the problem and contains discussion about the problem itself. Discussion on pull requests should be limited to the pull request itself, i.e. code review.
22 |
23 | For more on how 10up writes and manages code, check out our [10up Engineering Best Practices](https://10up.github.io/Engineering-Best-Practices/).
24 |
25 | ## Getting started
26 |
27 | Contributions are welcome (thank you!), to get started:
28 |
29 | 1. Clone the repository.
30 | 2. Install dependencies:
31 |
32 | ```bash
33 | composer install
34 | ```
35 |
36 | ## Workflow
37 |
38 | The `develop` branch is the development branch which means it contains the next version to be released. `trunk` contains the latest released version. Always work on the `develop` branch and open up PRs against `develop`.
39 |
40 | ## Release instructions
41 |
42 | 1. Branch: Starting from `develop`, cut a release branch named `release/X.Y.Z` for your changes.
43 | 1. Changelog: Add/update the changelog in `CHANGELOG.md`.
44 | 1. Props: update `CREDITS.md` with any new contributors, confirm maintainers are accurate.
45 | 1. Readme updates: Make any other readme changes as necessary. `README.md` is geared toward GitHub and `readme.txt` contains WordPress.org-specific content. The two are slightly different.
46 | 1. Merge: Make a non-fast-forward merge from your release branch to `develop` (or merge the pull request), then do the same for `develop` into `trunk`, ensuring you pull the most recent changes into `develop` first (`git checkout develop && git pull origin develop && git checkout trunk && git merge --no-ff develop`). `trunk` contains the stable development version.
47 | 1. Push: Push your `trunk` branch to GitHub (e.g. `git push origin trunk`).
48 | 1. [Compare](https://github.com/10up/wp-framework/compare/trunk...develop) trunk to develop to ensure no additional changes were missed.
49 | 1. Release: Create a [new release](https://github.com/10up/wp-framework/releases/new), naming the tag and the release with the new version number, and targeting the `trunk` branch. Paste the changelog from `CHANGELOG.md` into the body of the release and include a link to the [closed issues on the milestone](/milestone/3?closed=1).
50 | 1. Close the milestone: Edit the [X.Y.Z milestone](https://github.com/10up/wp-framework/milestone/#) with release date (in the `Due date (optional)` field) and link to GitHub release (in the `Description` field), then close the milestone.
51 | 1. Punt incomplete items: If any open issues or PRs which were milestoned for `X.Y.Z` do not make it into the release, update their milestone to `X+1.0.0`, `X.Y+1.0`, `X.Y.Z+1`, or `Future Release`.
52 |
--------------------------------------------------------------------------------
/tests/Assets/GetAssetInfoTest.php:
--------------------------------------------------------------------------------
1 | setup_asset_vars(
36 | dist_path: 'dist',
37 | fallback_version: '1.0.0'
38 | );
39 |
40 | $this->assertEquals( 'dist/', $asset_info->dist_path );
41 | $this->assertEquals( '1.0.0', $asset_info->fallback_version );
42 | }
43 |
44 | /**
45 | * Test get_asset_info returns an array with version and dependencies.
46 | *
47 | * @return void
48 | */
49 | public function test_get_asset_info_returns_array_with_version_and_dependencies() {
50 | $asset_info = new class() {
51 | use GetAssetInfo;
52 | };
53 |
54 | $asset_info->setup_asset_vars(
55 | dist_path: dirname( __DIR__, 2 ) . '/fixtures/assets/dist',
56 | fallback_version: '1.0.0'
57 | );
58 |
59 | $asset = $asset_info->get_asset_info(
60 | slug: 'test-script'
61 | );
62 | $this->assertIsArray( $asset );
63 | $this->assertArrayHasKey( 'version', $asset );
64 | $this->assertArrayHasKey( 'dependencies', $asset );
65 | $vars = require dirname( __DIR__, 2 ) . '/fixtures/assets/dist/js/test-script.asset.php';
66 | $this->assertEquals( $vars, $asset );
67 |
68 | $asset = $asset_info->get_asset_info(
69 | slug: 'test-style'
70 | );
71 | $this->assertArrayHasKey( 'version', $asset );
72 | $this->assertArrayHasKey( 'dependencies', $asset );
73 | $vars = require dirname( __DIR__, 2 ) . '/fixtures/assets/dist/css/test-style.asset.php';
74 | $this->assertEquals( $vars, $asset );
75 |
76 | $asset = $asset_info->get_asset_info(
77 | slug: 'non-existent'
78 | );
79 |
80 | $this->assertArrayHasKey( 'version', $asset );
81 | $this->assertArrayHasKey( 'dependencies', $asset );
82 | }
83 |
84 | /**
85 | * Test get_asset_info returns a string when passed a specific dependency.
86 | *
87 | * @return void
88 | */
89 | public function test_get_asset_info_returns_string_when_passed_specific_dependency() {
90 | $asset_info = new class() {
91 | use GetAssetInfo;
92 | };
93 |
94 | $asset_info->setup_asset_vars(
95 | dist_path: dirname( __DIR__, 2 ) . '/fixtures/assets/dist',
96 | fallback_version: '1.0.0'
97 | );
98 |
99 | $vars = require dirname( __DIR__, 2 ) . '/fixtures/assets/dist/js/test-script.asset.php';
100 |
101 | $version = $asset_info->get_asset_info(
102 | slug: 'test-script',
103 | attribute: 'version'
104 | );
105 |
106 | $this->assertEquals( $vars['version'], $version );
107 |
108 | $version = $asset_info->get_asset_info(
109 | slug: 'test-script',
110 | attribute: 'dependencies'
111 | );
112 |
113 | $this->assertEquals( $vars['dependencies'], $version );
114 | }
115 |
116 | /**
117 | * Test get_asset_info throws and exception when get_asset_info is called without setting up the asset vars.
118 | *
119 | * @return void
120 | */
121 | public function test_get_asset_info_throws_exception_when_called_without_setting_up_asset_vars() {
122 | $asset_info = new class() {
123 | use GetAssetInfo;
124 | };
125 |
126 | $this->expectException( \RuntimeException::class );
127 | $this->expectExceptionMessage( 'Asset variables not set. Please run setup_asset_vars() before calling get_asset_info().' );
128 |
129 | $asset_info->get_asset_info(
130 | slug: 'test-script'
131 | );
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/docs/Asset-Loading.md:
--------------------------------------------------------------------------------
1 | # Asset Loading
2 |
3 | ## Overview
4 | Use the `TenupFramework\Assets\GetAssetInfo` trait to read dependency and version metadata generated by your build (the `.asset.php` sidecar files). The trait looks for files in:
5 | - `dist/js/{slug}.asset.php`
6 | - `dist/css/{slug}.asset.php`
7 | - `dist/blocks/{slug}.asset.php`
8 |
9 | If no sidecar is found, it falls back to the version you provide and returns an empty dependency list, allowing safe enqueues during development or when assets are missing.
10 |
11 | ## Setup
12 | Prerequisites: define common constants and a dist/ directory for built assets.
13 |
14 | ```php
15 | // Plugin main file or bootstrap
16 | define( 'YOUR_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
17 | define( 'YOUR_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
18 | define( 'YOUR_PLUGIN_INC', YOUR_PLUGIN_PATH . 'inc/' );
19 | define( 'YOUR_PLUGIN_VERSION', '1.0.0' );
20 | ```
21 |
22 | Typical dist/ layout (your build may vary):
23 | ```
24 | dist/
25 | ├─ js/
26 | │ ├─ admin.js
27 | │ └─ admin.asset.php
28 | ├─ css/
29 | │ └─ admin.css
30 | └─ blocks/
31 | ├─ my-block.js
32 | └─ my-block.asset.php
33 | ```
34 |
35 | Include the trait in any class that enqueues assets and set the dist path and fallback version once (e.g., in the constructor or on first use):
36 |
37 | ```php
38 | use TenupFramework\Assets\GetAssetInfo;
39 |
40 | class AssetsModule {
41 | use GetAssetInfo;
42 |
43 | public function __construct() {
44 | $this->setup_asset_vars(
45 | dist_path: YOUR_PLUGIN_PATH . 'dist/',
46 | fallback_version: YOUR_PLUGIN_VERSION
47 | );
48 | }
49 | }
50 | ```
51 |
52 | Notes:
53 | - If you call `get_asset_info()` before `setup_asset_vars()`, a RuntimeException will be thrown.
54 | - During local development, sidecar files (e.g., `admin.asset.php`) may be missing. The trait safely falls back to your provided fallback_version and an empty dependency list, so your enqueues still work.
55 | - If your build produces multiple variants (e.g., `admin.js` vs `admin.min.js`), you can conditionally enqueue based on `SCRIPT_DEBUG` or `wp_get_environment_type() === 'development'`.
56 |
57 | ## Enqueuing scripts
58 | ```php
59 | wp_enqueue_script(
60 | 'tenup_plugin_admin',
61 | YOUR_PLUGIN_URL . 'dist/js/admin.js',
62 | $this->get_asset_info( 'admin', 'dependencies' ),
63 | $this->get_asset_info( 'admin', 'version' ),
64 | true
65 | );
66 | ```
67 | - dependencies: array of script handles from `admin.asset.php`
68 | - version: string used for cache busting
69 |
70 | ## Enqueuing styles
71 | ```php
72 | wp_enqueue_style(
73 | 'tenup_plugin_admin',
74 | YOUR_PLUGIN_URL . 'dist/css/admin.css',
75 | [], // CSS dependencies are uncommon; pass [] unless needed
76 | $this->get_asset_info( 'admin', 'version' )
77 | );
78 | ```
79 |
80 | ## Working with blocks
81 | If you build blocks, pass the block slug used by your build tool:
82 | ```php
83 | $deps = $this->get_asset_info( 'my-block', 'dependencies' );
84 | $ver = $this->get_asset_info( 'my-block', 'version' );
85 | $handle = 'tenup_my_block';
86 |
87 | wp_register_script( $handle, YOUR_PLUGIN_URL . 'dist/blocks/my-block.js', $deps, $ver, true );
88 | ```
89 | The trait automatically checks `dist/blocks/my-block.asset.php` if present.
90 |
91 | ## Error handling and fallbacks
92 | ```php
93 | try {
94 | $deps = $this->get_asset_info( 'frontend', 'dependencies' );
95 | $ver = $this->get_asset_info( 'frontend', 'version' );
96 | } catch ( \RuntimeException $e ) {
97 | // setup_asset_vars() was not called — fall back to safe defaults
98 | $deps = [];
99 | $ver = YOUR_PLUGIN_VERSION;
100 | }
101 | ```
102 |
103 | ## Best practices
104 | - Always call `setup_asset_vars()` early (constructor or on first enqueue).
105 | - Keep your dist path stable across environments (use constants for PATH and URL).
106 | - Use the version from `.asset.php` for reliable cache busting in production.
107 | - For admin-only assets, enqueue on `admin_enqueue_scripts`; for frontend, use `wp_enqueue_scripts`.
108 |
109 | ## See also
110 | - [Docs Home](README.md)
111 | - [Autoloading and Modules](Autoloading.md)
112 | - [Modules and Initialization](Modules-and-Initialization.md)
113 | - [Post Types](Post-Types.md)
114 | - [Taxonomies](Taxonomies.md)
115 |
--------------------------------------------------------------------------------
/docs/Autoloading.md:
--------------------------------------------------------------------------------
1 | # Autoloading and Modules
2 |
3 | ## Overview
4 | WP Framework follows PSR-4 autoloading and discovers your classes at runtime to initialize Modules. Instead of extending a base class, you implement ModuleInterface and use the Module trait to participate in the lifecycle.
5 |
6 | ## Composer PSR-4 setup
7 | Add your project namespace and source directory in composer.json:
8 |
9 | ```json
10 | {
11 | "autoload": {
12 | "psr-4": {
13 | "YourVendor\\YourPlugin\\": "inc/"
14 | }
15 | }
16 | }
17 | ```
18 |
19 | Run `composer dump-autoload` after changes.
20 |
21 | ## Recommended plugin structure & bootstrap
22 | A simple plugin layout that works well with the framework:
23 |
24 | ```
25 | my-plugin/
26 | ├─ my-plugin.php // main plugin file
27 | ├─ composer.json
28 | ├─ inc/ // PHP source (PSR-4 autoloaded)
29 | │ ├─ Features/
30 | │ ├─ Posts/
31 | │ └─ Taxonomies/
32 | ├─ dist/ // built assets from your toolchain
33 | │ ├─ js/
34 | │ │ ├─ admin.js
35 | │ │ └─ admin.asset.php
36 | │ ├─ css/
37 | │ │ └─ admin.css
38 | │ └─ blocks/
39 | │ ├─ my-block.js
40 | │ └─ my-block.asset.php
41 | └─ readme.txt
42 | ```
43 |
44 | Define a few useful constants in your main plugin file (or a bootstrap class), then initialize modules:
45 |
46 | ```php
47 | // Plugin main file or bootstrap
48 | define( 'YOUR_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
49 | define( 'YOUR_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
50 | define( 'YOUR_PLUGIN_INC', YOUR_PLUGIN_PATH . 'inc/' );
51 | define( 'YOUR_PLUGIN_VERSION', '1.0.0' );
52 |
53 | use TenupFramework\ModuleInitialization;
54 | ModuleInitialization::instance()->init_classes( YOUR_PLUGIN_INC );
55 | ```
56 |
57 | ## Initialization
58 | Call the framework’s initializer with the directory where your classes live (e.g., inc or src):
59 |
60 | ```php
61 | use TenupFramework\ModuleInitialization;
62 |
63 | ModuleInitialization::instance()->init_classes( YOUR_PLUGIN_INC );
64 | ```
65 |
66 | - Classes must be instantiable and implement `TenupFramework\ModuleInterface`.
67 | - The initializer sorts modules by `load_order()` (defaults to `10` via the `Module` trait) and then calls `register()` only if `can_register()` returns `true`.
68 | - A hook fires before registration: `tenup_framework_module_init__{slug}`, where slug is a sanitized class FQN.
69 |
70 | ### Verify discovery and environment behavior
71 | In development, you can verify discovered/initialized modules:
72 |
73 | ```php
74 | add_action( 'plugins_loaded', function () {
75 | $mods = TenupFramework\ModuleInitialization::instance()->get_all_classes();
76 | // For local/dev only:
77 | // error_log( print_r( array_keys( $mods ), true ) );
78 | } );
79 | ```
80 |
81 | Environment caching:
82 | - Discovery results are cached only in production and staging environments (per `wp_get_environment_type()`).
83 | - Cache is stored under the directory you pass to `init_classes()`, in a "class-loader-cache" folder (e.g., `YOUR_PLUGIN_INC . 'class-loader-cache'`).
84 | - To refresh: delete that folder; it will be rebuilt automatically.
85 | - Caching is skipped entirely when the constant `VIP_GO_APP_ENVIRONMENT` is defined or when `TENUP_FRAMEWORK_DISABLE_CLASS_CACHE` is set to `true`. Use `define( 'TENUP_FRAMEWORK_DISABLE_CLASS_CACHE', true )` in environments that don't support writable file systems.
86 |
87 | ## Defining a Module
88 | ```php
89 | namespace YourVendor\YourPlugin\Features;
90 |
91 | use TenupFramework\ModuleInterface;
92 | use TenupFramework\Module;
93 |
94 | class YourModule implements ModuleInterface {
95 | use Module; // provides default load_order() = 10
96 |
97 | public function can_register(): bool {
98 | // Only run on frontend, for example
99 | return ! is_admin();
100 | }
101 |
102 | public function register(): void {
103 | add_action( 'init', function () {
104 | // Add hooks/filters here
105 | } );
106 | }
107 | }
108 | ```
109 |
110 | ## Best practices
111 | - Keep Modules small and focused; compose behavior via multiple classes.
112 | - Use `can_register()` to gate context-specific behavior (admin vs. frontend, REST, multisite, feature flags).
113 | - Prefer dependency injection via constructor where practical; avoid doing heavy work before `register()`.
114 |
115 |
116 | ## See also
117 | - [Docs Home](README.md)
118 | - [Modules and Initialization](Modules-and-Initialization.md)
119 | - [Post Types](Post-Types.md)
120 | - [Taxonomies](Taxonomies.md)
121 | - [Asset Loading](Asset-Loading.md)
122 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WP Framework
2 |
3 | [](#support-level) [](https://github.com/10up/wp-framework/blob/develop/LICENSE.md) [](https://github.com/10up/wp-framework/actions/workflows/php.yml)
4 |
5 | > WP Framework is a PHP package designed to simplify the development of WordPress themes and plugins by centralizing shared functionality. It provides a set of foundational tools, abstract classes, and reusable components to handle common challenges, enabling developers to focus on project-specific logic while ensuring consistency across projects.
6 |
7 | ## Key Features
8 |
9 | - **Shared Functionality:** Provides commonly used abstract classes and utilities to reduce boilerplate code in WordPress projects.
10 | - **Extendability:** Built for easy extension. Engineers can subclass or override functionality as needed to tailor it to their projects.
11 | - **Centralized Updates:** Simplifies rolling out updates and new features across projects using this framework.
12 | - **Modern Standards:** Compatible with PHP 8.2+ and adheres to modern development practices.
13 |
14 | ## Installation
15 |
16 | You can include WP Framework in your project via Composer:
17 |
18 | ```bash
19 | composer require 10up/wp-framework
20 | ```
21 |
22 | ## Usage
23 |
24 | ### Autoloading
25 |
26 | The framework follows the PSR-4 autoloading standard, making it easy to include and extend classes in your project.
27 |
28 | It also builds upon the module autoloader that was previously used in the WP-Scaffold. The only difference is that now,
29 | instead of extending the `Module` class, you should implement the `ModuleInterface` interface. To help with this, we
30 | have also provided a `Module` trait that gives you a basic implementation of the interface.
31 |
32 | ```php
33 | namespace YourNamespace;
34 |
35 | use TenupFramework\ModuleInterface;
36 | use TenupFramework\Module;
37 |
38 | class YourModule implements ModuleInterface {
39 | use Module;
40 |
41 | public function can_register(): bool {
42 | return true;
43 | }
44 |
45 | public function register(): void {
46 | // Register hooks and filters here.
47 | }
48 | }
49 | ```
50 |
51 | ### Helpful Abstract Classes
52 |
53 | #### Custom Post Types
54 |
55 | ```php
56 | namespace TenUpPlugin\Posts;
57 |
58 | use TenupFramework\PostTypes\AbstractPostType;
59 |
60 | class Demo extends AbstractPostType {
61 |
62 | public function get_name() {
63 | return 'tenup-demo';
64 | }
65 |
66 | public function get_singular_label() {
67 | return esc_html__( 'Demo', 'tenup-plugin' );
68 | }
69 |
70 | public function get_plural_label() {
71 | return esc_html__( 'Demos', 'tenup-plugin' );
72 | }
73 |
74 | public function get_menu_icon() {
75 | return 'dashicons-chart-pie';
76 | }
77 | }
78 | ```
79 |
80 | #### Core Post Types
81 |
82 | ```php
83 | namespace TenUpPlugin\Posts;
84 |
85 | use TenupFramework\PostTypes\AbstractCorePostType;
86 |
87 | class Post extends AbstractCorePostType {
88 |
89 | public function get_name() {
90 | return 'post';
91 | }
92 |
93 | public function get_supported_taxonomies() {
94 | return [];
95 | }
96 |
97 | public function after_register() {
98 | // Do nothing.
99 | }
100 | }
101 | ```
102 |
103 | #### Taxonomies
104 |
105 | ```php
106 | namespace TenUpPlugin\Taxonomies;
107 |
108 | use TenupFramework\Taxonomies\AbstractTaxonomy;
109 |
110 | class Demo extends AbstractTaxonomy {
111 |
112 | public function get_name() {
113 | return 'tenup-demo-category';
114 | }
115 |
116 | public function get_singular_label() {
117 | return esc_html__( 'Category', 'tenup-plugin' );
118 | }
119 |
120 | public function get_plural_label() {
121 | return esc_html__( 'Categories', 'tenup-plugin' );
122 | }
123 | }
124 | ```
125 |
126 | ## Changelog
127 |
128 | A complete listing of all notable changes to Distributor are documented in [CHANGELOG.md](https://github.com/10up/wp-framework/blob/develop/CHANGELOG.md).
129 |
130 | ## Contributing
131 |
132 | Please read [CODE_OF_CONDUCT.md](https://github.com/10up/wp-framework/blob/develop/CODE_OF_CONDUCT.md) for details on our code of conduct and [CONTRIBUTING.md](https://github.com/10up/wp-framework/blob/develop/CONTRIBUTING.md) for details on the process for submitting pull requests to us.
133 |
134 | ## Support Level
135 |
136 | **Beta:** This project is quite new and we're not sure what our ongoing support level for this will be. Bug reports, feature requests, questions, and pull requests are welcome. If you like this project please let us know, but be cautious using this in a Production environment!
137 |
138 | ## Like what you see?
139 |
140 |
141 |
--------------------------------------------------------------------------------
/docs/Taxonomies.md:
--------------------------------------------------------------------------------
1 | # Taxonomies
2 |
3 | ## Overview
4 | WP Framework provides an AbstractTaxonomy base class to register and configure taxonomies with minimal boilerplate. Taxonomy classes are also Modules and follow the standard lifecycle (load_order → can_register → register). By default, taxonomies load at order 9 so they can be available for post types that load at the default 10.
5 |
6 | Important: Taxonomies are associated to post types via the Post Type classes (`get_supported_taxonomies()`), not via the taxonomy class itself.
7 |
8 | ## Quick start
9 | ```php
10 | namespace TenUpPlugin\Taxonomies;
11 |
12 | use TenupFramework\Taxonomies\AbstractTaxonomy;
13 |
14 | class DemoCategory extends AbstractTaxonomy {
15 | public function get_name() { return 'tenup-demo-category'; }
16 | public function get_singular_label() { return esc_html__( 'Category', 'tenup-plugin' ); }
17 | public function get_plural_label() { return esc_html__( 'Categories', 'tenup-plugin' ); }
18 |
19 | // Optional: make hierarchical like "category"; defaults to false (tags-like)
20 | public function is_hierarchical() { return true; }
21 |
22 | // Optional: adjust options beyond defaults
23 | public function get_options() {
24 | $opts = parent::get_options();
25 | $opts['rewrite'] = [ 'slug' => 'demo-category', 'with_front' => false ];
26 | return $opts;
27 | }
28 |
29 | // Optional: gate where this module runs
30 | public function can_register() { return true; }
31 | }
32 | ```
33 |
34 | Associate the taxonomy with your post type by declaring it in the post type class:
35 | ```php
36 | // In your AbstractPostType subclass
37 | public function get_supported_taxonomies() { return [ 'tenup-demo-category' ]; }
38 | ```
39 |
40 | ## API reference (AbstractTaxonomy)
41 | Required methods:
42 | - `get_name()`: string — Taxonomy slug, e.g., tenup-demo-category.
43 | - `get_singular_label()`: string — Translated singular label.
44 | - `get_plural_label()`: string — Translated plural label.
45 |
46 | Common optional methods:
47 | - `is_hierarchical()`: bool — Defaults to false (tags-like). Return true for category-like.
48 | - `get_options()`: array — Returns args passed to `register_taxonomy()`; see below for defaults and keys.
49 | - `after_register()`: void — Called after registration; use for additional setup.
50 | - `can_register()`: bool — Implement to control when to register (admin vs. frontend, feature flags, etc.).
51 | - `load_order()`: int — Defaults to 9 in `AbstractTaxonomy`; override to change load priority relative to other modules.
52 |
53 | Registration (implemented by `AbstractTaxonomy`):
54 | - `register()`: calls `register_taxonomy( get_name(), get_post_types(), get_options() )` and then `after_register()`. The base class returns an empty array from `get_post_types()` intentionally; association is handled by post types via `get_supported_taxonomies()`.
55 |
56 | ## Options (get_options) defaults
57 | AbstractTaxonomy provides sensible defaults:
58 | - `labels`: from `get_labels()`
59 | - `hierarchical`: `is_hierarchical()`
60 | - `show_ui`: true
61 | - `show_admin_column`: true
62 | - `query_var`: true
63 | - `show_in_rest`: true
64 | - `public`: true
65 |
66 | You may override `get_options()` to set any core taxonomy args, including:
67 | - `rewrite` (array|bool): slug, with_front, hierarchical, ep_mask
68 | - `capabilities` (array)
69 | - `default_term` (string|array{name: string, slug?: string, description?: string})
70 | - `meta_box_cb` (bool|callable)
71 | - `show_in_menu`, show_in_nav_menus, show_tagcloud, show_in_quick_edit
72 | - `rest_base`, rest_namespace, rest_controller_class
73 | - `update_count_callback` (callable)
74 |
75 | ## Labels
76 | `AbstractTaxonomy::get_labels()` builds a robust labels array using your singular/plural labels. Ensure your label methods return translated strings using your project’s text domain.
77 |
78 | ## Examples
79 | - Non-hierarchical tag-like taxonomy:
80 | ```php
81 | public function is_hierarchical() { return false; }
82 | public function get_options() {
83 | return [
84 | 'labels' => $this->get_labels(),
85 | 'show_in_rest' => true,
86 | 'rewrite' => [ 'slug' => 'demo-tags' ],
87 | ];
88 | }
89 | ```
90 |
91 | - Custom capabilities:
92 | ```php
93 | public function get_options() {
94 | $opts = parent::get_options();
95 | $opts['capabilities'] = [
96 | 'manage_terms' => 'manage_demo_terms',
97 | 'edit_terms' => 'manage_demo_terms',
98 | 'delete_terms' => 'manage_demo_terms',
99 | 'assign_terms' => 'edit_posts',
100 | ];
101 | return $opts;
102 | }
103 | ```
104 |
105 | ## Association pattern and rationale
106 | - Associations are declared in Post Type classes via `get_supported_taxonomies()`; taxonomy classes should not declare post types with `get_post_types()`.
107 | - Rationale: centralizes relationships in the place where object-type behavior lives; avoids duplication and fragile coupling; keeps taxonomy registration independent of associations.
108 | - Migration: If you previously returned post types from a taxonomy class via `get_post_types()`, remove that method and add the taxonomy slug to each relevant post type's `get_supported_taxonomies()`.
109 |
110 | ## See also
111 | - [Docs Home](README.md)
112 | - [Autoloading and Modules](Autoloading.md)
113 | - [Modules and Initialization](Modules-and-Initialization.md)
114 | - [Post Types](Post-Types.md)
115 | - [Asset Loading](Asset-Loading.md)
116 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | opensource@10up.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
--------------------------------------------------------------------------------
/docs/Modules-and-Initialization.md:
--------------------------------------------------------------------------------
1 | # Modules and Initialization
2 |
3 | ## Overview
4 | The WP Framework organizes functionality into small Modules. A Module is any class that implements TenupFramework\ModuleInterface and typically uses the TenupFramework\Module trait. Modules are discovered at runtime and initialized in a defined order.
5 |
6 | Key interfaces and utilities:
7 | - `TenupFramework\ModuleInterface`: declares `load_order()`, `can_register()`, `register()`.
8 | - `TenupFramework\Module` trait: provides a default `load_order()` of `10` and leaves `can_register()` and `register()` abstract for your class to implement.
9 | - `TenupFramework\ModuleInitialization`: discovers, orders, and initializes your Modules.
10 |
11 | ## Bootstrapping
12 | Call the initializer at plugin or theme bootstrap, pointing it at the directory containing your namespaced classes (e.g., `inc/` or `src/`):
13 |
14 | ```php
15 | use TenupFramework\ModuleInitialization;
16 |
17 | ModuleInitialization::instance()->init_classes( YOUR_PLUGIN_INC );
18 | ```
19 |
20 | `YOUR_PLUGIN_INC` (or your equivalent constant/path) should resolve to an existing directory. If it does not exist, a RuntimeException will be thrown.
21 |
22 | ## How discovery and initialization work
23 | ModuleInitialization performs the following steps:
24 | 1. Validate the directory exists; otherwise throw a RuntimeException.
25 | 2. Discover class names within the directory using spatie/structure-discoverer.
26 | - In production and staging environments (wp_get_environment_type), results are cached for performance using a file-based cache.
27 | - Caching is skipped entirely when the constant `VIP_GO_APP_ENVIRONMENT` is defined.
28 | 3. Reflect on each discovered class and skip any that:
29 | - are not instantiable,
30 | - do not implement `TenupFramework\ModuleInterface`.
31 | 4. Instantiate the class.
32 | 5. Fire an action before registration for each module: `tenup_framework_module_init__{slug}`
33 | - `slug` is the sanitized class FQN (backslashes replaced with dashes, then passed through `sanitize_title`).
34 | 6. Sort modules by `load_order()` (lower numbers first) and iterate in order.
35 | 7. For each module, call `register()` only if `can_register()` returns true.
36 | 8. Store initialized modules for later retrieval.
37 |
38 | Environment cache behavior
39 | - Where cache lives: under the directory you pass to `init_classes()`, in a `class-loader-cache` folder (e.g., `YOUR_PLUGIN_INC . 'class-loader-cache'`).
40 | - When it’s used: only in `production` and `staging` environment types (`wp_get_environment_type()`).
41 | - How to clear: delete the `class-loader-cache` folder; it will be rebuilt on next discovery.
42 | - How to disable in development: use `development` or `local` environment types, or define `VIP_GO_APP_ENVIRONMENT` to skip the cache.
43 | - How to disable for hosts that don't support file-based caching: `define( 'TENUP_FRAMEWORK_DISABLE_CLASS_CACHE', true );` to skip caching altogether.
44 |
45 | Hooks
46 | - Action: `tenup_framework_module_init__{slug}` — fires before each module’s `register()` runs.
47 | - Parameters: the module instance.
48 | - Example:
49 | ```php
50 | add_action( 'tenup_framework_module_init__yourvendor-yourplugin-features-frontendtweaks', function ( $module ) {
51 | // Inspect or adjust before register()
52 | } );
53 | ```
54 |
55 | Load order dependencies example
56 | - If Module B depends on Module A:
57 | ```php
58 | class ModuleA implements ModuleInterface { use Module; public function load_order(): int { return 5; } }
59 | class ModuleB implements ModuleInterface { use Module; public function load_order(): int { return 10; } }
60 | ```
61 | Lower numbers run first. Taxonomies typically use 9 so post types (default 10) can associate afterward.
62 |
63 | Utilities:
64 | - `ModuleInitialization::get_module( $classFqn )` retrieves an initialized module instance by its fully qualified class name.
65 | - `ModuleInitialization::instance()->get_all_classes()` returns all initialized module instances keyed by slug.
66 |
67 | ## Module lifecycle in your code
68 | Your Module should be lightweight at construction time. Use the following methods effectively:
69 | - `load_order(): int` — controls initialization order (default = 10 via Module trait). Override to run earlier/later. For example, taxonomy modules may run at 9 so they are available before post types.
70 | - `can_register(): bool` — return true only when the module should register hooks in the current context (e.g., only in admin, only on frontend, only if a feature flag is enabled).
71 | - `register(): void` — attach your WordPress hooks/filters and perform setup here.
72 |
73 | ### Example
74 | ```php
75 | namespace YourVendor\YourPlugin\Features;
76 |
77 | use TenupFramework\ModuleInterface;
78 | use TenupFramework\Module;
79 |
80 | class FrontendTweaks implements ModuleInterface {
81 | use Module; // default load_order() = 10
82 |
83 | public function can_register(): bool {
84 | return ! is_admin(); // only on frontend
85 | }
86 |
87 | public function register(): void {
88 | add_action( 'wp_enqueue_scripts', [ $this, 'enqueue' ] );
89 | }
90 |
91 | public function enqueue(): void {
92 | // ... enqueue assets here ...
93 | }
94 | }
95 | ```
96 |
97 | ## Troubleshooting
98 | - Directory is required — If `init_classes()` is called with an empty or non-existent directory, a RuntimeException is thrown.
99 | - Class not initialized — Ensure the class is instantiable and implements `TenupFramework\ModuleInterface`.
100 | - Order of initialization — If you have inter-module dependencies, adjust `load_order()` to ensure prerequisites are registered first.
101 | - Observability — Use the `tenup_framework_module_init__{slug}` action to inspect or modify module instances before they register.
102 |
--------------------------------------------------------------------------------
/docs/Post-Types.md:
--------------------------------------------------------------------------------
1 | # Post Types
2 |
3 | ## Overview
4 | WP Framework provides base classes for implementing both custom and core post types with minimal boilerplate and a consistent API. Post type classes are also Modules, so they participate in the standard lifecycle (load_order → can_register → register).
5 |
6 | - Custom post types: extend `TenupFramework\PostTypes\AbstractPostType`
7 | - Core post types: extend `TenupFramework\PostTypes\AbstractCorePostType`
8 |
9 | ## Quick start (custom post type)
10 | ```php
11 | namespace TenUpPlugin\Posts;
12 |
13 | use TenupFramework\PostTypes\AbstractPostType;
14 |
15 | class Demo extends AbstractPostType {
16 | public function get_name() { return 'tenup-demo'; }
17 | public function get_singular_label() { return esc_html__( 'Demo', 'tenup-plugin' ); }
18 | public function get_plural_label() { return esc_html__( 'Demos', 'tenup-plugin' ); }
19 | public function get_menu_icon() { return 'dashicons-chart-pie'; }
20 |
21 | // Optional: run only in specific contexts
22 | public function can_register() { return true; }
23 |
24 | // Optional: fine-tune options beyond defaults
25 | public function get_options() {
26 | $options = parent::get_options();
27 | $options['supports'] = [ 'title', 'editor', 'thumbnail', 'excerpt' ];
28 | $options['rewrite'] = [ 'slug' => 'demos', 'with_front' => false ];
29 | $options['has_archive'] = true;
30 | return $options;
31 | }
32 |
33 | // Declare related taxonomies (registered separately via taxonomy classes)
34 | public function get_supported_taxonomies() { return [ 'tenup-demo-category' ]; }
35 | }
36 | ```
37 |
38 | ## Working with core post types
39 | If you need to attach taxonomies or behaviors to built-in types (post, page, attachment), extend `AbstractCorePostType`:
40 | ```php
41 | namespace TenUpPlugin\Posts;
42 |
43 | use TenupFramework\PostTypes\AbstractCorePostType;
44 |
45 | class Post extends AbstractCorePostType {
46 | public function get_name() { return 'post'; }
47 |
48 | public function get_supported_taxonomies() {
49 | return [ 'tenup-demo-category' ];
50 | }
51 |
52 | public function after_register() {
53 | // Add metaboxes, filters, etc.
54 | }
55 | }
56 | ```
57 | Notes:
58 | - Core post types are already registered by WordPress. `AbstractCorePostType::register()` does not call `register_post_type()`; it only registers taxonomies (via `get_supported_taxonomies()`) and then calls `after_register()`.
59 | - `can_register()` returns `true` by default in `AbstractCorePostType`.
60 |
61 | ## Taxonomy association pattern and migration
62 | - Associations are declared in Post Type classes via `get_supported_taxonomies();` taxonomy classes should not declare post types with `get_post_types()`.
63 | - Rationale: centralizes relationships in the object type; avoids duplication and fragile coupling; taxonomy registration stays independent of associations.
64 | - Migration: If you previously returned post types from a taxonomy class via `get_post_types()`, remove that method and add the taxonomy slug to each relevant post type’s `get_supported_taxonomies()`.
65 |
66 | ## API reference (AbstractPostType)
67 | Required methods you must implement:
68 | - `get_name()`: string — The post type slug, e.g., tenup-demo.
69 | - `get_singular_label()`: string — Translated singular label.
70 | - `get_plural_label()`: string — Translated plural label.
71 | - `get_menu_icon()`: string — A dashicons class, base64 SVG, or 'none'.
72 |
73 | Common optional methods to override:
74 | - `get_menu_position()`: ?int — Position in admin menu; null by default.
75 | - `is_hierarchical()`: bool — Defaults to false.
76 | - `get_editor_supports()`: array — Defaults to [title, editor, author, thumbnail, excerpt, revisions].
77 | - `get_options()`: array — Returns options passed to `register_post_type()`. See below for keys and defaults.
78 | - `get_supported_taxonomies()`: string[] — Array of taxonomy slugs to associate via `register_taxonomy_for_object_type()`.
79 | - `after_register()`: void — Called after the type is registered and taxonomies associated.
80 | - `can_register()`: bool — Implement to control when this module should run; e.g., limit to admin.
81 |
82 | Registration methods (already implemented):
83 | - `register()`: calls `register_post_type()`, `register_taxonomies()`, then `after_register()`; returns `true`.
84 | - `register_post_type()`: wraps WordPress `register_post_type( $this->get_name(), $this->get_options() )`.
85 | - `register_taxonomies()`: iterates get_supported_taxonomies() and calls `register_taxonomy_for_object_type()`.
86 |
87 | ## Options (get_options) overview
88 | AbstractPostType provides sensible defaults and merges in:
89 | - `labels`: from `get_labels()`
90 | - `public`: true
91 | - `has_archive`: true
92 | - `show_ui`: true
93 | - `show_in_menu`: true
94 | - `show_in_nav_menus`: false
95 | - `show_in_rest`: true
96 | - `supports`: `get_editor_supports()`
97 | - `menu_icon`: `get_menu_icon()`
98 | - `hierarchical`: `is_hierarchical()`
99 | - `menu_position`: included if `get_menu_position()` returns a number
100 |
101 | You can override get_options() in your class to set any supported core args, including:
102 | - `rewrite` (array|bool): slug, with_front, feeds, pages, ep_mask
103 | - `capability_type` (string|array), capabilities (array), map_meta_cap (bool)
104 | - `taxonomies` (array) — Note: prefer `get_supported_taxonomies()` to associate after registration
105 | - `has_archive` (bool|string)
106 | - `show_in_rest` (bool), rest_base, rest_namespace, rest_controller_class
107 | - `register_meta_box_cb` (callable)
108 | - `template` (array), template_lock (string|false)
109 |
110 | ## Labels
111 | `AbstractPostType::get_labels()` builds a comprehensive labels array using the singular/plural labels you provide. Ensure your `get_*_label()` methods return translated strings using your project text domain.
112 |
113 | ## Tips
114 | - Flush rewrite rules on activation only (not within `register()`).
115 | - Keep post type classes focused on registration; put custom business logic in separate modules/services.
116 | - Link taxonomies via `get_supported_taxonomies()` for clarity; implement taxonomy classes separately (see Taxonomies.md).
117 |
118 | ## See also
119 | - [Taxonomies](Taxonomies.md)
120 | - [Modules and Initialization](Modules-and-Initialization.md)
121 |
--------------------------------------------------------------------------------
/src/Taxonomies/AbstractTaxonomy.php:
--------------------------------------------------------------------------------
1 | get_name() to get the taxonomy's slug.
88 | * @return bool
89 | */
90 | public function register() {
91 | \register_taxonomy(
92 | $this->get_name(),
93 | $this->get_post_types(),
94 | $this->get_options()
95 | );
96 |
97 | $this->after_register();
98 |
99 | return true;
100 | }
101 |
102 | /**
103 | * Get the options for the taxonomy.
104 | *
105 | * @return array{
106 | * labels?: array,
107 | * description?: string,
108 | * public?: bool,
109 | * publicly_queryable?: bool,
110 | * hierarchical?: bool,
111 | * show_ui?: bool,
112 | * show_in_menu?: bool,
113 | * show_in_nav_menus?: bool,
114 | * show_tagcloud?: bool,
115 | * show_in_quick_edit?: bool,
116 | * show_admin_column?: bool,
117 | * meta_box_cb?: bool|callable,
118 | * show_in_rest?: bool,
119 | * rest_base?: string,
120 | * rest_namespace?: string,
121 | * rest_controller_class?: string,
122 | * capabilities?: array,
123 | * rewrite?: bool|array{
124 | * slug?: string,
125 | * with_front?: bool,
126 | * hierarchical?: bool,
127 | * ep_mask?: int,
128 | * },
129 | * query_var?: string|bool,
130 | * update_count_callback?: callable,
131 | * default_term?: string|array{
132 | * name: string,
133 | * slug?: string,
134 | * description?: string,
135 | * },
136 | * sort?: bool,
137 | * _builtin?: bool,
138 | * }
139 | */
140 | public function get_options() {
141 | return [
142 | 'labels' => $this->get_labels(),
143 | 'hierarchical' => $this->is_hierarchical(),
144 | 'show_ui' => true,
145 | 'show_admin_column' => true,
146 | 'query_var' => true,
147 | 'show_in_rest' => true,
148 | 'public' => true,
149 | ];
150 | }
151 |
152 | /**
153 | * Get the labels for the taxonomy.
154 | *
155 | * @return array
156 | */
157 | public function get_labels() {
158 | $plural_label = $this->get_plural_label();
159 | $singular_label = $this->get_singular_label();
160 |
161 | // phpcs:disable WordPress.WP.I18n.MissingTranslatorsComment -- ignoring template strings without translators placeholder since this is dynamic
162 | $labels = [
163 | 'name' => $plural_label, // Already translated via get_plural_label().
164 | 'singular_name' => $singular_label, // Already translated via get_singular_label().
165 | 'search_items' => sprintf( __( 'Search %s', 'tenup-plugin' ), $plural_label ),
166 | 'popular_items' => sprintf( __( 'Popular %s', 'tenup-plugin' ), $plural_label ),
167 | 'all_items' => sprintf( __( 'All %s', 'tenup-plugin' ), $plural_label ),
168 | 'edit_item' => sprintf( __( 'Edit %s', 'tenup-plugin' ), $singular_label ),
169 | 'update_item' => sprintf( __( 'Update %s', 'tenup-plugin' ), $singular_label ),
170 | 'add_new_item' => sprintf( __( 'Add %s', 'tenup-plugin' ), $singular_label ),
171 | 'new_item_name' => sprintf( __( 'New %s Name', 'tenup-plugin' ), $singular_label ),
172 | 'separate_items_with_commas' => sprintf( __( 'Separate %s with commas', 'tenup-plugin' ), strtolower( $plural_label ) ),
173 | 'add_or_remove_items' => sprintf( __( 'Add or remove %s', 'tenup-plugin' ), strtolower( $plural_label ) ),
174 | 'choose_from_most_used' => sprintf( __( 'Choose from the most used %s', 'tenup-plugin' ), strtolower( $plural_label ) ),
175 | 'not_found' => sprintf( __( 'No %s found.', 'tenup-plugin' ), strtolower( $plural_label ) ),
176 | 'not_found_in_trash' => sprintf( __( 'No %s found in Trash.', 'tenup-plugin' ), strtolower( $plural_label ) ),
177 | 'view_item' => sprintf( __( 'View %s', 'tenup-plugin' ), $singular_label ),
178 | ];
179 | // phpcs:enable WordPress.WP.I18n.MissingTranslatorsComment
180 |
181 | return $labels;
182 | }
183 |
184 | /**
185 | * Setting the post types to null to ensure no post type is registered with
186 | * this taxonomy. Post Type classes declare their supported taxonomies.
187 | *
188 | * @return array
189 | */
190 | public function get_post_types() {
191 | return [];
192 | }
193 |
194 | /**
195 | * Run any code after the taxonomy has been registered.
196 | *
197 | * @return void
198 | */
199 | public function after_register() {
200 | // Do nothing.
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/src/ModuleInitialization.php:
--------------------------------------------------------------------------------
1 |
54 | */
55 | protected $classes = [];
56 |
57 | /**
58 | * Get all the TenupFramework plugin classes.
59 | *
60 | * @param string $dir The directory to search for classes.
61 | *
62 | * @return array
63 | */
64 | public function get_classes( $dir ) {
65 | $this->directory_check( $dir );
66 |
67 | // Get all classes from this directory and its subdirectories.
68 | $class_finder = Discover::in( $dir );
69 | // Only fetch classes.
70 | $class_finder->classes();
71 | // Disable inheritance chain resolution
72 | $class_finder->withoutChains();
73 |
74 | // If we are in production or staging, cache the class loader to improve performance.
75 | if ( $this->should_use_cache() ) {
76 | $class_finder->withCache(
77 | __NAMESPACE__,
78 | new FileDiscoverCacheDriver( $dir . '/class-loader-cache' )
79 | );
80 | }
81 |
82 | $classes = array_filter( $class_finder->get(), fn( $cl ) => is_string( $cl ) );
83 |
84 | // Return the classes
85 | return $classes;
86 | }
87 |
88 | /**
89 | * Should we set up and use the class cache?
90 | *
91 | * @return bool
92 | */
93 | protected function should_use_cache(): bool {
94 | if ( defined( 'VIP_GO_APP_ENVIRONMENT' ) ) {
95 | return false;
96 | }
97 |
98 | if ( ! in_array( wp_get_environment_type(), [ 'production', 'staging' ], true ) ) {
99 | return false;
100 | }
101 |
102 | if ( defined( 'TENUP_FRAMEWORK_DISABLE_CLASS_CACHE' ) && true === TENUP_FRAMEWORK_DISABLE_CLASS_CACHE ) {
103 | return false;
104 | }
105 |
106 | return true;
107 | }
108 |
109 | /**
110 | * Check if the directory exists.
111 | *
112 | * @param string $dir The directory to check.
113 | *
114 | * @throws \RuntimeException If the directory does not exist.
115 | *
116 | * @return bool
117 | */
118 | protected function directory_check( $dir ): bool {
119 | if ( empty( $dir ) ) {
120 | throw new \RuntimeException( 'Directory is required to initialize classes.' );
121 | }
122 |
123 | if ( ! is_dir( $dir ) ) {
124 | // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
125 | throw new \RuntimeException( 'Directory "' . $dir . '" does not exist.' );
126 | }
127 |
128 | return true;
129 | }
130 |
131 | /**
132 | * Initialize all the TenupFramework plugin classes.
133 | *
134 | * @param string $dir The directory to search for classes.
135 | *
136 | * @return void
137 | */
138 | public function init_classes( $dir = '' ) {
139 | $this->directory_check( $dir );
140 |
141 | $load_class_order = [];
142 | foreach ( $this->get_classes( $dir ) as $class ) {
143 | // Create a slug for the class name.
144 | $slug = $this->slugify_class_name( $class );
145 |
146 | // If the class has already been initialized, skip it.
147 | if ( isset( $this->classes[ $slug ] ) ) {
148 | continue;
149 | }
150 |
151 | $reflection_class = $this->get_fully_loadable_class( $class );
152 |
153 | if ( ! $reflection_class ) {
154 | continue;
155 | }
156 |
157 | // Using reflection, check if the class can be initialized.
158 | // If not, skip.
159 | if ( ! $reflection_class->isInstantiable() ) {
160 | continue;
161 | }
162 |
163 | // Check if the class implements ModuleInterface before instantiating it
164 | if ( ! $reflection_class->implementsInterface( 'TenupFramework\ModuleInterface' ) ) {
165 | continue;
166 | }
167 |
168 | // Initialize the class.
169 | // phpcs:ignore Generic.Commenting.DocComment.MissingShort
170 | /** @var ModuleInterface $instantiated_class */
171 | $instantiated_class = new $class();
172 |
173 | do_action( 'tenup_framework_module_init__' . $slug, $instantiated_class );
174 |
175 | // Assign the classes into the order they should be initialized.
176 | $load_class_order[ intval( $instantiated_class->load_order() ) ][] = [
177 | 'slug' => $slug,
178 | 'class' => $instantiated_class,
179 | ];
180 | }
181 |
182 | // Sort the initialized classes by load order.
183 | ksort( $load_class_order );
184 |
185 | // Loop through the classes and initialize them.
186 | foreach ( $load_class_order as $class_objects ) {
187 | foreach ( $class_objects as $class_object ) {
188 | $class = $class_object['class'];
189 | $slug = $class_object['slug'];
190 |
191 | // If the class can be registered, register it.
192 | if ( $class->can_register() ) {
193 | // Call its register method.
194 | $class->register();
195 | // Store the class in the list of initialized classes.
196 | $this->classes[ $slug ] = $class;
197 | }
198 | }
199 | }
200 | }
201 |
202 | /**
203 | * Retrieves a fully loadable class using reflection.
204 | *
205 | * @param string $class_name The name of the class to load.
206 | *
207 | * @return false|ReflectionClass Returns a ReflectionClass instance if the class is loadable, or false if it is not.
208 | *
209 | * @phpstan-ignore missingType.generics
210 | */
211 | public function get_fully_loadable_class( string $class_name ): false|ReflectionClass {
212 | try {
213 | // Create a new reflection of the class.
214 | // @phpstan-ignore argument.type
215 | return new ReflectionClass( $class_name );
216 | } catch ( \Throwable $e ) {
217 | // This includes ReflectionException, Error due to missing parent, etc.
218 | return false;
219 | }
220 | }
221 |
222 | /**
223 | * Slugify a class name.
224 | *
225 | * @param string $class_name The class name.
226 | *
227 | * @return string
228 | */
229 | protected function slugify_class_name( $class_name ) {
230 | return sanitize_title( str_replace( '\\', '-', $class_name ) );
231 | }
232 |
233 | /**
234 | * Get a class by its full class name, including namespace.
235 | *
236 | * @param string $class_name The class name & namespace.
237 | *
238 | * @return false|ModuleInterface
239 | */
240 | public function get_class( $class_name ) {
241 | $class_name = $this->slugify_class_name( $class_name );
242 |
243 | if ( isset( $this->classes[ $class_name ] ) ) {
244 | return $this->classes[ $class_name ];
245 | }
246 |
247 | return false;
248 | }
249 |
250 | /**
251 | * Get all the initialized classes.
252 | *
253 | * @return array
254 | */
255 | public function get_all_classes() {
256 | return $this->classes;
257 | }
258 |
259 | /**
260 | * Get an initialized class by its full class name, including namespace.
261 | *
262 | * @param string $class_name The class name including the namespace.
263 | *
264 | * @return false|ModuleInterface
265 | */
266 | public static function get_module( $class_name ) {
267 | return self::instance()->get_class( $class_name );
268 | }
269 | }
270 |
--------------------------------------------------------------------------------
/tests/ModuleInitializationTest.php:
--------------------------------------------------------------------------------
1 | get_classes( dirname( __DIR__, 1 ) . '/src/' );
30 |
31 | // Check that we have the concrete classes we expect to see.
32 | $this->assertContains( 'TenupFramework\PostTypes\AbstractPostType', $classes );
33 | $this->assertContains( 'TenupFramework\PostTypes\AbstractCorePostType', $classes );
34 | $this->assertContains( 'TenupFramework\Taxonomies\AbstractTaxonomy', $classes );
35 | $this->assertContains( 'TenupFramework\ModuleInitialization', $classes );
36 | }
37 |
38 | /**
39 | * Ensure we can find the right classes.
40 | *
41 | * @return void
42 | */
43 | public function test_it_can_find_classes_to_register() {
44 | $class = \TenupFramework\ModuleInitialization::instance();
45 | $class->init_classes( dirname( __DIR__, 1 ) . '/src/' );
46 | $classes = $class->get_all_classes();
47 |
48 | // Check that we have only classes that extend Module and more than 0.
49 | $this->assertGreaterThanOrEqual( 0, count( $classes ) );
50 | }
51 |
52 | /**
53 | * Ensure an exception is thrown when a directory does not exist.
54 | *
55 | * @return void
56 | */
57 | public function test_that_an_exception_is_thrown_when_a_directory_does_not_exist() {
58 | $class = \TenupFramework\ModuleInitialization::instance();
59 | $this->expectException( \RuntimeException::class );
60 | $class->init_classes( dirname( __DIR__, 1 ) . '/src/does-not-exist-1234567/' );
61 | }
62 |
63 | /**
64 | * Ensure an exception is thrown when a directory is not passed.
65 | *
66 | * @return void
67 | */
68 | public function test_that_an_exception_is_thrown_when_a_directory_is_not_passed() {
69 | $class = \TenupFramework\ModuleInitialization::instance();
70 | $this->expectException( \RuntimeException::class );
71 | $class->init_classes();
72 | }
73 |
74 | /**
75 | * Ensure the instance method returns the same instance.
76 | *
77 | * @return void
78 | */
79 | public function test_instance_returns_same_instance() {
80 | $instance1 = \TenupFramework\ModuleInitialization::instance();
81 | $instance2 = \TenupFramework\ModuleInitialization::instance();
82 | $this->assertSame( $instance1, $instance2 );
83 | }
84 |
85 | /**
86 | * Ensure the instance method returns the same instance.
87 | *
88 | * @return void
89 | */
90 | public function test_get_classes_returns_classes_from_directory() {
91 | $module_init = \TenupFramework\ModuleInitialization::instance();
92 | $classes = $module_init->get_classes( dirname( __DIR__, 1 ) . '/fixtures/classes' );
93 | $this->assertIsArray( $classes );
94 | $this->assertNotEmpty( $classes );
95 | }
96 |
97 | /**
98 | * Ensure the instance method returns the same instance.
99 | *
100 | * @return void
101 | */
102 | public function test_init_classes_initializes_classes_in_correct_order() {
103 | $module_init = \TenupFramework\ModuleInitialization::instance();
104 | $module_init->init_classes( dirname( __DIR__, 1 ) . '/fixtures/classes' );
105 | $classes = $module_init->get_all_classes();
106 | $this->assertNotEmpty( $classes );
107 | $this->assertNotContains( 'TenupFramework\Taxonomies\AbstractTaxonomy', $classes );
108 | $this->assertInstanceOf( \TenupFramework\ModuleInterface::class, reset( $classes ) );
109 | }
110 |
111 | /**
112 | * Ensure that we can return an instantiated class vie get_module.
113 | *
114 | * @return void
115 | */
116 | public function test_get_module_returns_instantiated_class() {
117 | $module_init = \TenupFramework\ModuleInitialization::instance();
118 | $module_init->init_classes( dirname( __DIR__, 1 ) . '/fixtures/classes' );
119 | $module = \TenupFramework\ModuleInitialization::get_module( 'TenupFrameworkTestClasses\PostTypes\Demo' );
120 | $this->assertInstanceOf( \TenupFrameworkTestClasses\PostTypes\Demo::class, $module );
121 |
122 | $module = \TenupFramework\ModuleInitialization::get_module( 'TenupFrameworkTestClasses\DoesntExist' );
123 | $this->assertFalse( $module );
124 | }
125 |
126 | /**
127 | * Test that only classes implementing ModuleInterface are initialized.
128 | *
129 | * @return void
130 | */
131 | public function test_only_classes_implementing_module_interface_are_initialized() {
132 | $module_init = \TenupFramework\ModuleInitialization::instance();
133 | $module_init->init_classes( dirname( __DIR__, 1 ) . '/fixtures/classes' );
134 |
135 | $this->assertTrue( did_action( 'tenup_framework_module_init__tenupframeworktestclasses-posttypes-demo' ) > 0, 'Demo was not initialized.' );
136 | $this->assertFalse( did_action( 'tenup_framework_module_init__tenupframeworktestclasses-standalone-standalone' ) > 0, 'Standalone class was initialized.' );
137 | }
138 |
139 | /**
140 | * Validate if the classes are fully loadable.
141 | *
142 | * @return void
143 | */
144 | public function testIsClassFullyLoadable() {
145 | $module_init = \TenupFramework\ModuleInitialization::instance();
146 |
147 | $this->assertInstanceOf( 'ReflectionClass', $module_init->get_fully_loadable_class( '\TenupFrameworkTestClasses\Loadable\BaseClass' ) );
148 | $this->assertInstanceOf( 'ReflectionClass', $module_init->get_fully_loadable_class( '\TenupFrameworkTestClasses\Loadable\ChildClass' ) );
149 | $this->assertFalse( $module_init->get_fully_loadable_class( '\TenupFrameworkTestClasses\Loadable\InvalidChildClass' ) );
150 | }
151 |
152 |
153 | /**
154 | * Ensure it returns false if VIP_GO_APP_ENVIRONMENT is defined.
155 | *
156 | * @return void
157 | */
158 | public function test_should_use_cache_returns_false_when_vip_env_is_defined() {
159 | define( 'VIP_GO_APP_ENVIRONMENT', true );
160 | $module_init = \TenupFramework\ModuleInitialization::instance();
161 | $reflection = new \ReflectionClass( $module_init );
162 | $method = $reflection->getMethod( 'should_use_cache' );
163 | $method->setAccessible( true );
164 |
165 | $this->assertFalse( $method->invoke( $module_init ) );
166 | }
167 |
168 | /**
169 | * Ensure it returns false in non-production or staging environments.
170 | *
171 | * @return void
172 | */
173 | public function test_should_use_cache_returns_false_in_non_production_or_staging_env() {
174 | stubs(
175 | [
176 | 'wp_get_environment_type' => 'development',
177 | ]
178 | );
179 |
180 | $module_init = \TenupFramework\ModuleInitialization::instance();
181 | $reflection = new \ReflectionClass( $module_init );
182 | $method = $reflection->getMethod( 'should_use_cache' );
183 | $method->setAccessible( true );
184 |
185 | $this->assertFalse( $method->invoke( $module_init ) );
186 | }
187 |
188 | /**
189 | * Ensure it returns false when TENUP_FRAMEWORK_DISABLE_CLASS_CACHE is defined.
190 | *
191 | * @return void
192 | */
193 | public function test_should_use_cache_returns_false_when_disable_class_cache_is_defined() {
194 | define( 'TENUP_FRAMEWORK_DISABLE_CLASS_CACHE', true );
195 | $module_init = \TenupFramework\ModuleInitialization::instance();
196 | $reflection = new \ReflectionClass( $module_init );
197 | $method = $reflection->getMethod( 'should_use_cache' );
198 | $method->setAccessible( true );
199 |
200 | $this->assertFalse( $method->invoke( $module_init ) );
201 | }
202 |
203 | /**
204 | * Ensure it returns true under default conditions.
205 | *
206 | * @return void
207 | */
208 | public function test_should_use_cache_returns_true_under_default_conditions() {
209 | stubs(
210 | [
211 | 'wp_get_environment_type' => 'production',
212 | ]
213 | );
214 |
215 | $module_init = \TenupFramework\ModuleInitialization::instance();
216 | $reflection = new \ReflectionClass( $module_init );
217 | $method = $reflection->getMethod( 'should_use_cache' );
218 | $method->setAccessible( true );
219 |
220 | $this->assertTrue( $method->invoke( $module_init ) );
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/src/PostTypes/AbstractPostType.php:
--------------------------------------------------------------------------------
1 |
101 | */
102 | public function get_editor_supports() {
103 | $supports = [
104 | 'title',
105 | 'editor',
106 | 'author',
107 | 'thumbnail',
108 | 'excerpt',
109 | 'revisions',
110 | ];
111 |
112 | return $supports;
113 | }
114 |
115 | /**
116 | * Get the options for the post type.
117 | *
118 | * @return array{
119 | * labels?: array,
120 | * description?: string,
121 | * public?: bool,
122 | * hierarchical?: bool,
123 | * exclude_from_search?: bool,
124 | * publicly_queryable?: bool,
125 | * show_ui?: bool,
126 | * show_in_menu?: bool,
127 | * show_in_nav_menus?: bool,
128 | * show_in_admin_bar?: bool,
129 | * menu_position?: int,
130 | * menu_icon?: string,
131 | * capability_type?: string|array,
132 | * capabilities?: array,
133 | * map_meta_cap?: bool,
134 | * supports?: array|false,
135 | * register_meta_box_cb?: callable,
136 | * taxonomies?: array,
137 | * has_archive?: bool|string,
138 | * rewrite?: bool|array{
139 | * slug?: string,
140 | * with_front?: bool,
141 | * feeds?: bool,
142 | * pages?: bool,
143 | * ep_mask?: int,
144 | * },
145 | * query_var?: bool|string,
146 | * can_export?: bool,
147 | * delete_with_user?: bool,
148 | * show_in_rest?: bool,
149 | * rest_base?: string,
150 | * rest_namespace?: string,
151 | * rest_controller_class?: string,
152 | * _builtin?: bool,
153 | * template?: array>,
154 | * template_lock?: string|false,
155 | * }
156 | */
157 | public function get_options() {
158 | $options = [
159 | 'labels' => $this->get_labels(),
160 | 'public' => true,
161 | 'has_archive' => true,
162 | 'show_ui' => true,
163 | 'show_in_menu' => true,
164 | 'show_in_nav_menus' => false,
165 | 'show_in_rest' => true,
166 | 'supports' => $this->get_editor_supports(),
167 | 'menu_icon' => $this->get_menu_icon(),
168 | 'hierarchical' => $this->is_hierarchical(),
169 | ];
170 |
171 | $menu_position = $this->get_menu_position();
172 |
173 | if ( null !== $menu_position ) {
174 | $options['menu_position'] = $menu_position;
175 | }
176 |
177 | return $options;
178 | }
179 |
180 | /**
181 | * Get the labels for the post type.
182 | *
183 | * @return array
184 | */
185 | public function get_labels() {
186 | $plural_label = $this->get_plural_label();
187 | $singular_label = $this->get_singular_label();
188 |
189 | // phpcs:disable WordPress.WP.I18n.MissingTranslatorsComment -- ignoring template strings without translators placeholder since this is dynamic
190 | $labels = [
191 | 'name' => $plural_label,
192 | // Already translated via get_plural_label().
193 | 'singular_name' => $singular_label,
194 | // Already translated via get_singular_label().
195 | 'add_new' => sprintf( __( 'Add New %s', 'tenup-plugin' ), $singular_label ),
196 | 'add_new_item' => sprintf( __( 'Add New %s', 'tenup-plugin' ), $singular_label ),
197 | 'edit_item' => sprintf( __( 'Edit %s', 'tenup-plugin' ), $singular_label ),
198 | 'new_item' => sprintf( __( 'New %s', 'tenup-plugin' ), $singular_label ),
199 | 'view_item' => sprintf( __( 'View %s', 'tenup-plugin' ), $singular_label ),
200 | 'view_items' => sprintf( __( 'View %s', 'tenup-plugin' ), $plural_label ),
201 | 'search_items' => sprintf( __( 'Search %s', 'tenup-plugin' ), $plural_label ),
202 | 'not_found' => sprintf( __( 'No %s found.', 'tenup-plugin' ), strtolower( $plural_label ) ),
203 | 'not_found_in_trash' => sprintf( __( 'No %s found in Trash.', 'tenup-plugin' ), strtolower( $plural_label ) ),
204 | 'parent_item_colon' => sprintf( __( 'Parent %s:', 'tenup-plugin' ), $plural_label ),
205 | 'all_items' => sprintf( __( 'All %s', 'tenup-plugin' ), $plural_label ),
206 | 'archives' => sprintf( __( '%s Archives', 'tenup-plugin' ), $singular_label ),
207 | 'attributes' => sprintf( __( '%s Attributes', 'tenup-plugin' ), $singular_label ),
208 | 'insert_into_item' => sprintf( __( 'Insert into %s', 'tenup-plugin' ), strtolower( $singular_label ) ),
209 | 'uploaded_to_this_item' => sprintf( __( 'Uploaded to this %s', 'tenup-plugin' ), strtolower( $singular_label ) ),
210 | 'filter_items_list' => sprintf( __( 'Filter %s list', 'tenup-plugin' ), strtolower( $plural_label ) ),
211 | 'items_list_navigation' => sprintf( __( '%s list navigation', 'tenup-plugin' ), $plural_label ),
212 | 'items_list' => sprintf( __( '%s list', 'tenup-plugin' ), $plural_label ),
213 | 'item_published' => sprintf( __( '%s published.', 'tenup-plugin' ), $singular_label ),
214 | 'item_published_privately' => sprintf( __( '%s published privately.', 'tenup-plugin' ), $singular_label ),
215 | 'item_reverted_to_draft' => sprintf( __( '%s reverted to draft.', 'tenup-plugin' ), $singular_label ),
216 | 'item_scheduled' => sprintf( __( '%s scheduled.', 'tenup-plugin' ), $singular_label ),
217 | 'item_updated' => sprintf( __( '%s updated.', 'tenup-plugin' ), $singular_label ),
218 | 'menu_name' => $plural_label,
219 | 'name_admin_bar' => $singular_label,
220 | ];
221 | // phpcs:enable WordPress.WP.I18n.MissingTranslatorsComment
222 |
223 | return $labels;
224 | }
225 |
226 | /**
227 | * Registers a post type and associates its taxonomies.
228 | *
229 | * @uses $this->get_name() to get the post's type name.
230 | * @return Bool Whether this theme has supports for this post type.
231 | */
232 | public function register() {
233 | $this->register_post_type();
234 | $this->register_taxonomies();
235 |
236 | $this->after_register();
237 |
238 | return true;
239 | }
240 |
241 | /**
242 | * Registers the current post type with WordPress.
243 | *
244 | * @return void
245 | */
246 | public function register_post_type() {
247 | register_post_type(
248 | $this->get_name(),
249 | $this->get_options()
250 | );
251 | }
252 |
253 | /**
254 | * Registers the taxonomies declared with the current post type.
255 | *
256 | * @return void
257 | */
258 | public function register_taxonomies() {
259 | $taxonomies = $this->get_supported_taxonomies();
260 |
261 | $object_type = $this->get_name();
262 |
263 | if ( ! empty( $taxonomies ) ) {
264 | foreach ( $taxonomies as $taxonomy ) {
265 | register_taxonomy_for_object_type(
266 | $taxonomy,
267 | $object_type
268 | );
269 | }
270 | }
271 | }
272 |
273 | /**
274 | * Returns the default supported taxonomies. The subclass should declare the
275 | * Taxonomies that it supports here if required.
276 | *
277 | * @return array
278 | */
279 | public function get_supported_taxonomies() {
280 | return [];
281 | }
282 |
283 | /**
284 | * Run any code after the post type has been registered.
285 | *
286 | * @return void
287 | */
288 | public function after_register() {
289 | // Do nothing.
290 | }
291 | }
292 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------