Coder Social home page Coder Social logo

mixerapi-dev's Introduction

Logo

A CakePHP Plugin for RESTful API Development

Packagist Build Status Coverage Status CakePHP ^4.2 PHP ^8.0 Software License

Streamline development of modern RESTful APIs for your teams CakePHP project. Designed around a component-based architecture, MixerAPI enables developers to pick and choose the functionality they need for developing REST APIs.

Documentation | Demo Application | Demo Source Code

Features

  • Rapid Prototyping: Scaffold your API in seconds with a custom Bake template geared towards modern REST architecture.
  • OpenAPI: Automatically generates OpenAPI from your existing code into Swagger and Redoc. Attributes provided, but not required.
  • Error Handling: Handles exception rendering in XML or JSON.
  • Data Formats: Formats responses in JSON, XML, HAL+JSON, or JSON-LD.
  • Integrations: Integrates well with other CakePHP 4 compatible plugins.
  • Minimalist Configuration: Built for developing, not writing YAML configurations. Most components require zero configuration files.
  • Non-opinionated: Develop your way.

This is a read-only repository. Please submit issues and PRs to mixerapi/mixerapi-dev

For install steps head over to https://mixerapi.com/install

MixerAPI Core Plugins

MixerAPI automatically installs the following plugins for your RESTful API project:

Plugin Description
MixerApi/Bake A custom bake template focused on creating RESTful CakePHP controllers in seconds
MixerApi/CollectionView A Collection View for displaying configurable pagination meta-data in JSON or XML collection responses
MixerApi/ExceptionRender Handles rendering entity validation errors and other exceptions for your API
MixerApi/HalView A Hypertext Application Language (HAL+JSON) View for CakePHP
MixerApi/JsonLdView A JSON-LD View for CakePHP
SwaggerBake A delightfully tasty tool for generating Swagger documentation with OpenApi 3.0.0 schema

Recommended Plugins

Plugin Description
MixerApi/Crud A service provider for CRUD (Create/Read/Update/Delete) operations. Since this plugin uses the experimental CakePHP dependency injection it must be enabled separately.
MixerApi/JwtAuth A JWT authentication library for CakePHP supporting both HMAC (HS256 or HS512) and RSA (RS256 or RS512) with JSON Web Keys.
Search Search provides a simple interface to create paginate-able filters for your CakePHP application.

mixerapi-dev's People

Contributors

amayer5125 avatar cnizzardini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mixerapi-dev's Issues

[MixerApi] Update installer

Installer needs the following updates:

  • config/swagger_bake.php
  • config/swagger.yml
  • WelcomeController.php swap out annotations with attributes
  • Update installation and setup steps in readme

[Rest] - Lib/assets/routes.php breaks preload

What Happened

Unable to add Lib/assets/routes.php to preload file.

Expected Behavior

Should be able to add Rest files to preload

Steps to Reproduce

  1. Add Lib/assets/routes.php to preload file.
  2. Restart PHP

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2.3
  • MixerApi Version: 0.2.8

[ExceptionRender] Exceptions without $this->error still set the exceptions array when rendered

What Happened
First off, not sure if this is an actual defect or if I'm throwing exceptions incorrectly. Feel free to let me know if it's the latter.

My tests broke as of Mixer 1.1.6 and I noticed the bugfix (#128) involving the $exceptions property in the exceptions renderer, here is the specific test failure I'm encountering:

 ✘ Authenticate rejects invalid base 64 encoded payloads
   ┐
   ├ Failed asserting that two strings are equal.
   ┊ ---·Expected
   ┊ +++·Actual
   ┊ @@ @@
   ┊ -'{"exception":"BadRequestException","message":"<error message>","url":"\/users\/authenticate","code":400}'
   ┊ +'{"exception":"BadRequestException","message":"<error message>","url":"\/users\/authenticate","code":400,"exceptions":[{}]}'
   │
   ╵ /Users/path/to/my/Code/tests/TestCase/Controller/UsersControllerTest.php:165
   ┴

Note the EMPTY exceptions property in the rendered exception. Here's the test that throws this error:

$this->assertEquals(400, $this->_response->getStatusCode());
$expected = [
    'exception' => 'BadRequestException',
    'message' => AuthzError::REQUEST_AUTHORIZATION_HEADER_PAYLOAD_FAIL
    'url' => '/users/authenticate',
    'code' => 400,
    // 'exceptions' => [new stdClass()],          <-----  if I don't have this line, test fails
];
$expected = json_encode($expected);
$this->assertEquals($expected, (string) $this->_response->getBody());

See how I have to have the exceptions key in my array, with its value set to an array of a single stdClass object? That's yucky, no? It certainly feels very hacky to me. So I started tracking down where it could have come from.

It turns out that the exception getting rendered doesn't have the $this->error property set (unknown why) and so these lines (in the MixerApiExceptionRender):

$exceptions = [$exception];               // this is the offending line
$previous = $exception->getPrevious();
while ($previous != null) {
    $exceptions[] = $previous;
    $previous = $previous->getPrevious();
}

are resulting in an array with a single null entry, which gets encoded to the weird JSON as shown above.

Expected Behavior
I feel like the way it should behave is to do a null check on $this->error and set $exceptions = []; if it is null.

Steps to Reproduce
I'm just throwing basic exceptions from my controller like this, but as I mentioned above this could be wrong:

throw new BadRequestException(
    AuthzError::REQUEST_AUTHORIZATION_HEADER_REQUIRES_BASIC_SCHEME->description(true)
);

One other solution I considered was wrapping the Cake exceptions in my own custom exceptions which make sure to set $this->error but it also seems like a null check would be beneficial here.

Version and Platform (please complete the following information):

  • OS/Platform: macOS
  • CakePHP: 4.4.8
  • MixerApi Version: 1.1.6

Attachments
N/A

JsonLdView - JsonLdContext::build is brittle and needs refactoring

This method is currently locating an Entity by string, inflection and direct instantiation of the table instance. This seems fraught with problems. Instead, the method should take a table alias string, use the TableLocator class, and then pass that into the ModelDecorator.

[MixerApi/Crud] Add getQuery to Read

Add getQuery methods to Read service and interface. There are scenarios where a user may want to use the DI service add modify the query, associations etc...

[ExceptionRender] - incorrect status code reported for record not found exception

What Happened
A \Cake\Datasource\Exception\RecordNotFoundException was thrown and a 500 status code was given.

Expected Behavior
A 404 status code

Steps to Reproduce

  1. Throw a \Cake\Datasource\Exception\RecordNotFoundException

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2
  • MixerApi Version: 0.2.4

Attachments
If applicable, add screenshots or swagger.json

[MixerApi\ExceptionRender] - ValidationException not working in docblock

What happened
Unable to use @throws \MixerApi\ExceptionRender\ValidationException in docblock on add() method to specify status code in openapi.

2021-01-04 10:54:19 Error: [InvalidArgumentException] Invalid status code: 0. Use a valid HTTP status code in range 1xx - 5xx. in /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Response.php on line 634
Stack Trace:

  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Response.php:618
  • /var/www/personal/mixerapi/mixerapi-dev/plugins/exception-render/src/MixerApiExceptionRenderer.php:66
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php:143
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Error/Middleware/ErrorHandlerMiddleware.php:125
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Runner.php:73
  • /var/www/personal/mixerapi/demo/vendor/cakephp/debug_kit/src/Middleware/DebugKitMiddleware.php:60
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Runner.php:73
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Runner.php:58
  • /var/www/personal/mixerapi/demo/vendor/cakephp/cakephp/src/Http/Server.php:90
  • /var/www/personal/mixerapi/demo/webroot/index.php:40

Expected
HTTP 422 to appear in OpenAPI/Swagger/Redoc

Steps to Reproduce

  1. Add @throws \MixerApi\ExceptionRender\ValidationException to docblock in a controller add() action.

Swagger can't handle exceptions on HTTP delete

What Happened
Tried deleting a record that doesn't exist via swagger interface. An exception is generated which causes swagger to crash.

Expected Behavior
404 response

Steps to Reproduce

  1. Send HTTP delete for a recrod that does not exist

Version and Platform (please complete the following information):

  • OS/Platform: Linux/Docker
  • CakePHP: 4.2.*
  • MixerApi Version: 0.2.4

[JsonLdView] - Class not found run time exception

What Happened
In demo went to http://localhost:8080/public/contexts/actors and encountered exception:

Class not found for actorsTable in App\Model\Table\

Expected Behavior

JsonLdContext is rendered

Steps to Reproduce

  1. Go to http://localhost:8080/public/contexts/actors

Fix in JsonLdContextComponent::build

        $table = NamespaceUtility::findClass(
            Configure::read('App.namespace') . '\Model\Table\\',
            Inflector::camelize(Inflector::pluralize($entityName)) . 'Table'
        );

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2.5
  • MixerApi Version: 0.2.9

[JsonLdView] - Throw custom exception

When there is an entity mismatch throw custom exception instead of letting cake throw a serialization exception.

This occurs when the return value of getJsonLdContext() cannot be mapped to an entity,

[Bake] - Incorrect namespace for MethodNotAllowedException

What Happened
\Cake\Datasource\Exception\MethodNotAllowedException is invalid

Expected Behavior
\Cake\Http\Exception\MethodNotAllowedException

Steps to Reproduce

  1. Bake a controller

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2
  • MixerApi Version: 0.2.5

[MixerApi/ExceptionRender] - Add stack trace to responses

Add stack trace to responses when debug mode is enabled.

Example:

{
  "exception": "RecordNotFoundException",
  "message": "Record not found in table \"actors\"",
  "url": "/admin/actors/123123",
  "code": 500,
  "trace": [
    {
      "file": "/var/www/api/vendor/cakephp/cakephp/src/Datasource/QueryTrait.php",
      "line": 514
    },
    {
      "file": "/var/www/api/vendor/cakephp/cakephp/src/ORM/Table.php",
      "line": 1545,
      "function": "firstOrFail",
      "class": "Cake\\ORM\\Query",
      "type": "->",
      "args": []
    },
    {
      "file": "/var/www/api/plugins/AdminApi/src/Controller/ActorsController.php",
      "line": 125,
      "function": "get",
      "class": "Cake\\ORM\\Table",
      "type": "->",
      "args": [
        [
          "123123"
        ],
        {
          "contain": []
        }
      ]
    },

[MixerApi\Core] - Event Listener Loader

An EventListenerLoader which loads all events in App\Event by default. The load() method can accept a string which is used to load listeners from another namespace.

[Bake] - Incorrect namespace for MethodNotAllowedException

What Happened
\Cake\Datasource\Exception\MethodNotAllowedException is incorrect

Expected Behavior
Use @throws \Cake\Http\Exception\MethodNotAllowedException

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2
  • MixerApi Version: 0.2.5

Update ResponseModifier

Adding additional mimetypes for hal and jsonld can be removed from MixerApi\Core\Response\ResponseModifier. These were added since support for CakePHP 4.1 or lower didn't have these types, but only CakePHP 4.2 or higher will be supported now.

[ExceptionRender] - Not showing stack trace

What Happened
RunTimeException was thrown and cake debug is not showing stack trace

Notice (8): Undefined variable: trace [CORE/templates/element/exception_stack_trace_nav.php, line 21]
Warning (2): Invalid argument supplied for foreach() [CORE/templates/element/exception_stack_trace_nav.php, line 21]

Expected Behavior
Shows stack trace

Steps to Reproduce
See steps in #64

Potential fix in MixerApiExceptionRenderer::debugViewVars

        if (!Configure::read('debug')) {
            return $viewVars;
        }

Version and Platform (please complete the following information):

  • OS/Platform: Alpine/Docker
  • CakePHP: 4.2.5
  • MixerApi Version: 0.2.9

ExceptionRender outputting PHP Warnings in CakePHP 4.4.6

To Reproduce:

Throw a BadRequestException

What Happened:

Output:

Warning (2) : Undefined variable $exceptions [in /srv/app/vendor/cakephp/cakephp/templates/element/exception_stack_trace.php, line 20]
Warning (2) : foreach() argument must be of type array|object, null given [in /srv/app/vendor/cakephp/cakephp/templates/element/exception_stack_trace.php, line 20]

If you want to customize this error message, create templates/Error/error400.php

Expected:

Output does not contain php warnings

[ExceptionRender] - Outputting web exceptions in CLI

What Happened

Web exceptions (html) output to CLI when an exception is encountered running a command.

Expected Behavior

CLI exceptions are displayed.

Steps to Reproduce

  1. Throw an exception in a cake command

Proposed change:

    public function render(): ResponseInterface
    {
        if (PHP_SAPI === 'cli') {
            $request = $request ?? Router::getRequest();
            return (new ConsoleExceptionRenderer($this->error, $request, $this->_config))->render();
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.