{"id":23289784,"url":"https://github.com/cmatosbc/coderpress-endpoints","last_synced_at":"2025-10-27T22:30:49.135Z","repository":{"id":268379596,"uuid":"904165116","full_name":"cmatosbc/coderpress-endpoints","owner":"cmatosbc","description":"Complete WP Rest API custom endpoints frameworks, including caching, logging, middlewares and more.","archived":false,"fork":false,"pushed_at":"2024-12-16T11:31:58.000Z","size":31,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-24T05:15:43.601Z","etag":null,"topics":["middlewares","php-library","php8","wordpress","wordpress-api","wordpress-cache","wordpress-endpoint","wp","wp-api","wp-rest-api"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cmatosbc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-16T11:22:57.000Z","updated_at":"2024-12-20T12:25:16.000Z","dependencies_parsed_at":"2024-12-16T12:38:38.493Z","dependency_job_id":null,"html_url":"https://github.com/cmatosbc/coderpress-endpoints","commit_stats":null,"previous_names":["cmatosbc/coderpress-endpoints"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Fcoderpress-endpoints","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Fcoderpress-endpoints/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Fcoderpress-endpoints/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmatosbc%2Fcoderpress-endpoints/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cmatosbc","download_url":"https://codeload.github.com/cmatosbc/coderpress-endpoints/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238563730,"owners_count":19492975,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["middlewares","php-library","php8","wordpress","wordpress-api","wordpress-cache","wordpress-endpoint","wp","wp-api","wp-rest-api"],"created_at":"2024-12-20T04:18:08.108Z","updated_at":"2025-10-27T22:30:48.795Z","avatar_url":"https://github.com/cmatosbc.png","language":"PHP","readme":"# WP CoderPress Endpoints\n\nThis package intends to provide a more straightforward way to add custom endpoints to Wordpress Rest API (added to mu-plugins with no hooks, as a suggestion), also using a Facade pattern which allows:\n* To attach PSR-16 compliant cache drivers of any nature\n* To attach as many middlewares as you want to modify the request or provide a particular response\n* Interfere in the way cached responses are stored and retrieved (JSON, serialize(), igbinary_serialize())\n* Provide a port to add multiple custom endpoints without repeating code and sharing cache, middleware and variables within, including a dynamic endpoint generation\n* Offer common middlewares to handle common scenarios in REST API development\n\n## Installation\n\nEasily install the package using composer:\n\n```bash\ncomposer require coderpress/wp-coderpress-endpoints\n```\n\n# Basic Example\n\nThe following example creates a very simple example endpoint to the rest API that comes with two middlewares attached (as \\Closure objects). The first one modifies any passed parameter to \"id = 123\", which triggers the second middleware and returns a WP_REST_Response - this also prevents the cache to be done.\n\nIf the second middleware is removed, the endpoint is no longer short-circuited, so the results are now serialized and cached in a file within wp-content/cache/. In the example, the cache is managed by FileCache, but this package also includes usable drivers for Redis (using redis-php extension) and MySQL cache, using a custom DB table.\n\n```php\nuse CoderPress\\Rest\\{RestEndpointFacade, AbstractRestEndpoint};\nuse CoderPress\\Cache\\{RedisCache, MySqlCache, FileCache};\n\nrequire __DIR__ . '/vendor/autoload.php';\n\n$cacheInstance = new FileCache(WP_CONTENT_DIR . '/cache/');\n\n$custom = RestEndpointFacade::createEndpoint(\n    /** The five first arguments stand as they are for register_rest_route()\n     * but with callbacks now accepting \\Closure functions instead.\n     * \n     * The middlewares arguments accepts an array of closures which will be\n     * sequentially executed and MUST have a $request parameter.\n     * \n     * The cache mechanism is automatically applied to the endpoint and accepts\n     * any PSR-16 compliant object. Optionally, the expire time and the type\n     * of serialization can be changed. Expires accepts any value in seconds as\n     * integer or a Datetime object (and then the time in seconds between that and\n     * the current time will be automatically extracted)\n     * \n     */\n    namespace: 'testing/v1', \n    route: 'custom/',\n    args: [\n      'id' =\u003e [\n        'validate_callback' =\u003e function($param, $request, $key) {\n          return is_numeric($param);\n        }\n      ],\n    ],\n    callback: function (\\WP_REST_Request $request) {\n        $postId = $request-\u003eget_param('id');\n        $postCategoryIds = wp_get_object_terms($postId, ['category'], ['fields' =\u003e 'ids']);\n\n        return get_posts([\n          'post_status' =\u003e 'publish',\n          'category__in' =\u003e $postCategoryIds,\n          'order' =\u003e 'relevance'\n        ]);\n    },\n    permissionCallback: function () {\n        return is_user_logged_in();\n    },\n    /**\n     * Accepts any number of /Closure middleware functions - to each one of them,\n     * the $request object must be passed. For changes made to the WP_REST_Request object,\n     * the closure must return void(). However, the middleware can also return a response\n     * to the request easily by return a new WP_REST_Response object instead. \n     */\n    middlewares: [\n        function (\\WP_REST_Request $request) {\n            $request-\u003eset_param('id', 123);\n        },\n        function (\\WP_REST_Request $request) {\n            if ($request-\u003eget_param('id') == 123) {\n                return new \\WP_REST_Response(['message' =\u003e 'Invalid value'], 201);\n            }\n        }\n    ],\n    /**\n     * Accepts any instance PSR-16 compliant (CacheInterface contract),\n     * this package comes with 3 usable examples (file, Redis and custom MySQL\n     * table caching drivers). \n     */\n    cache: $cacheInstance,\n    /**\n     * Accepts 3 different serialize/unserialize methods - defaults to serialize(),\n     * but can be using JSON - AbstractRestEndpoint::SERIALIZE_JSON - or igbinary PHP \n     * extension which offers a more efficient serializing version\n     *  - AbstractRestEndpoint::SERIALIZE_IGBINARY. \n     */\n    cacheSerializingMethod: AbstractRestEndpoint::SERIALIZE_PHP,\n    /**\n     * Accepts seconds as integer value, but also DateTime objects - for the latter,\n     * the system will get the interval between NOW and the passed DateTime object time,\n     * so the cache will work as scheduled.\n     */\n    cacheExpires: (new \\DateTime())-\u003emodify('+1 day')\n);\n```\n\n# Middlewares\n\nThe package includes several built-in middlewares to handle common scenarios in REST API development:\n\n## CORS Middleware\n\nThe CORS (Cross-Origin Resource Sharing) middleware allows you to configure cross-origin requests to your API endpoints. Here's how to use it:\n\n```php\nuse CoderPress\\Rest\\RestEndpointFacade;\nuse CoderPress\\Rest\\Middleware\\MiddlewareFactory;\n\n// Create an endpoint with CORS support\nRestEndpointFacade::createEndpoint(\n    namespace: 'api/v1',\n    route: 'posts',\n    callback: function($request) {\n        return ['data' =\u003e 'Your API response'];\n    },\n    permissionCallback: function() {\n        return true;\n    },\n    args: [],\n    methods: ['GET', 'POST', 'OPTIONS'],\n    middlewares: [\n        MiddlewareFactory::cors(\n            allowedOrigins: ['https://your-domain.com'],\n            allowedMethods: ['GET', 'POST'],\n            allowedHeaders: ['Content-Type', 'X-Custom-Header'],\n            maxAge: 7200\n        )\n    ]\n);\n```\n\nThe CORS middleware provides:\n- Origin validation against a whitelist\n- Configurable HTTP methods\n- Customizable allowed headers\n- Preflight request handling\n- Configurable cache duration for preflight responses\n- Credentials support\n\nAll parameters are optional and come with sensible defaults for typical API usage.\n\n## Sanitization Middleware\n\nThe Sanitization middleware provides comprehensive input sanitization and validation for your API endpoints. It helps prevent XSS attacks, SQL injection, and ensures data consistency:\n\n```php\nuse CoderPress\\Rest\\RestEndpointFacade;\nuse CoderPress\\Rest\\Middleware\\MiddlewareFactory;\n\nRestEndpointFacade::createEndpoint(\n    namespace: 'api/v1',\n    route: 'posts',\n    callback: function($request) {\n        return ['data' =\u003e $request-\u003eget_params()];\n    },\n    permissionCallback: function() {\n        return true;\n    },\n    args: [\n        'title' =\u003e [\n            'required' =\u003e true,\n            'type' =\u003e 'string'\n        ],\n        'content' =\u003e [\n            'required' =\u003e true,\n            'type' =\u003e 'string'\n        ]\n    ],\n    methods: ['POST'],\n    middlewares: [\n        MiddlewareFactory::sanitization(\n            rules: [\n                // Custom sanitization rules for specific fields\n                'title' =\u003e fn($value) =\u003e sanitize_title($value),\n                'content' =\u003e fn($value) =\u003e wp_kses_post($value)\n            ],\n            stripTags: true,\n            encodeSpecialChars: true,\n            allowedHtmlTags: [\n                'p' =\u003e [],\n                'a' =\u003e ['href' =\u003e [], 'title' =\u003e []],\n                'b' =\u003e [],\n                'i' =\u003e []\n            ]\n        )\n    ]\n);\n```\n\nThe middleware provides:\n- Field-specific sanitization rules using callbacks\n- HTML tag stripping with configurable allowed tags\n- Special character encoding\n- UTF-8 validation\n- Recursive array sanitization\n- WordPress-specific sanitization functions integration\n- XSS and SQL injection protection\n\nAll parameters are optional and come with secure defaults. Use the `rules` parameter to define custom sanitization logic for specific fields.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmatosbc%2Fcoderpress-endpoints","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcmatosbc%2Fcoderpress-endpoints","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmatosbc%2Fcoderpress-endpoints/lists"}