Code Monkey home page Code Monkey logo

raml-php-parser's Introduction

RAML.org Website

This repository contains the source code for the raml.org website written in Jekyll

Requirements

Running locally

Pull the code locally:

$ git clone [email protected]:raml-org/raml-org.git

Enter directory:

$ cd raml-org

Install all dependencies:

$ bundle install

Build & run the site:

$ bundle exec jekyll serve

How to add projects to the projects page?

RAML.org includes a projects page that lists tools around RAML that either are community or commercial driven. If you think, your project should be in this list, please fork this repository, add it into the projects.yml file, and send us a PR. We will review and let you know if we will be able to list it.

Another way to make sure your project is linked to our projects page is through assigning topics to your Github project. Links to each topics are below the list of projects on the projects page. The following topics are available:

Topic Description
raml-design Includes projects that specifically support people with the design of RAML documents.
raml-document Includes projects that focus on the documentation of APIs using RAML documents.
raml-build Includes projects that focus on build client or server code based on RAML documents.
raml-parser Includes projects that parses/validates RAML documents.
raml-test Includes projects that support people testing APIs based on RAML documents.
raml-utilities Includes other projects that do not fall into the other topics like converters.

Topics need to be assigned and managed by the owner of a project. Additionally, we still recommend people to search on Github for more projects that might not have these topics assigned.

Contribution

RAML's website is in fact an open source project and your contribution is very much appreciated. Before you start, you should check for open issues or open a fresh issue to start a discussion around an idea that you'd like to see on our website or a bug. If you want to support us fixing issues, please follow the steps below:

  1. Fork the repository on Github and make your changes on the develop branch (or branch off of it).
  2. Run the website to see if you fixed the issue.
  3. Send a pull request (with the develop branch as the target).

We will review your PR, comment if necessary, and merge it into our staging branch stg.

You can contribute to the following:

  • spelling mistakes
  • new projects
  • blog posts
  • and others, after carefully reviewing the issue you created

raml-php-parser's People

Contributors

akostylev0 avatar alecsammon avatar arheyy avatar cozylife avatar denisovmaksim avatar dice4x4 avatar eduard-sukharev avatar h4cc avatar infopactmloos avatar isize1ce avatar jefferson-lima avatar jeromemacias avatar jmlamodiere avatar kubawerlos avatar lstrojny avatar martin-georgiev avatar nacmartin avatar nofirg avatar peter279k avatar philzen avatar pies avatar qpautrat avatar retfu avatar rgeraads avatar rgzp avatar thesebas avatar titomiguelcosta avatar toflar avatar vbartusevicius avatar yannickroger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

raml-php-parser's Issues

Reserved parameters are not replaced

Hi there,

I figured out reserved parameters resourcePathand resourcePathName are not replaced when resource type is not an array.

Working:

/songs:
  type: { collection: {} }

Not working:

/songs:
  type: collection

I'm working on this at this moment. Pull request will come shortly.

Resource URI seems invalid

This is more of a question than a bug, not sure. When we have subresources, at the moment, the URI does not take into consideration the parent resource URI, this end ups with invalid URI. For instance, I have a resource /users and a subresource /{id}, I would expect the URI of the subresource to be /users/{id}, not just {id}. Should we change the implementation of the Resource class, line 63, to pass the $uri to the constructor of the subresource, instead of the first argument being just $key, it would be $uri.$key.

Multiple exception types

Currently the library throws \Exception objects. This would be much nicer if we threw custom exceptions that showed more clearly what the error is. I.e.\Raml\Exception\ParseException

[BUG] null Security Scheme is invalid

The Problem
When defining security schemes, you don't enter the "null" security scheme, but you do use the placeholder "null" in "securedBy" as stated in the official RAML 0.8 spec. When referencing the "null" security scheme, the project complains that it couldn't located it as a "securitySchemes" entry.

The solution
Change L#175 of \Raml\Method as follows.

                if (empty($securedBy)) {
                    $method->addSecurityScheme(SecurityScheme::createFromArray('null', array(), $apiDefinition));
                } else {
                    $method->addSecurityScheme($apiDefinition->getSecurityScheme($securedBy));
                }

class Raml\ParseConfiguration not found in ... error message

I am getting errors stating Raml\ParseConfiguration not found in xyz...

Class 'Raml\ParseConfiguration' not found in /cygdrive/c/src/myapp/Raml/Parser.php on line 83

Have I done a step incorrectly, what is the correct method to autoload the php-raml-parser? I have followed the instructions in the readme, i'm guessing I've done something wrong - any suggestions?

my index.php file -

require ('Raml/Parser.php');
use Raml\Parser;

$parser = new \Raml\Parser();
$filename= 'basic.raml';
$apiDef = $parser->parse($filename, true);

$title = $apiDef->getTitle();

Replace parameter by json string

Hi,

Use case:

resourceTypes:
 - collection:
    get:
      description: Get a collection of <<resourcePathName>>.
      responses:
        200:
          body:
            application/json:
              example: |
                {
                  "items":
                <<example>>
                }

/songs:
  type:
    collection:
      example: |
        [
          {
            "id": 2,
            "title": "test"
          }
        ]

In this scenario, applyTraitVariables throws a JSON_ERROR_SYNTAX.

Is there any particular reason to json_encode then json_decode values @alecsammon ?

I would like to propose a way without convert array to string.

[SECURITY FLAW] LFI vulnerability in file inclusion

The Problem
RAML could be used by more than just a developer working on their own API, and when groups of people have access to write RAML code on a managed service, parsing included files could be dangerous, however some files may be useful for inclusion.

The program protects against RFI attacks, and allows for file inclusion to be shut off, but when file inclusion is enabled, it allows for usage of ../ in the path name. The following is a valid path.

__DIR__.'/my/chosen/root/../outside_of_root/bad_file.php'

See L#440 of Parser.php

Proposed Solution
Use str_replace() to remove any occurrences of ../ in the RAML file included filename. If you're concerned about compatibility, consider an extra parameter to allow for developers to shut off arbitrary path names. The root directory should allow for arbitrary path names, as that's not part of the YAML file.

Resource types not parsing

When I parse a .raml file that uses resource types the following error appears:

Malformed inline YAML string ({ collection }) in /home/dennis/www/api-toolkit/src/ApiToolkit/Bundle/AppBundle/Parser/../Resources/raml/simple.raml at line 77 (near "type: { collection }").

Is this something you are working on?

When parsing raml with traits it throws: Warning: array_replace_recursive(): Argument #1 is not an array

Hi.

I am trying to parse this raml spec link to Github
with your parser and it throws an error Warning: array_replace_recursive(): Argument # 1 is not an array in ..\vendor\alecsammon\php-raml-parser\src\Parser.php on line 298.
Here to be more precise:

if (isset($newArray[$key])) {
  $newArray[$key] = array_replace_recursive($newArray[$key], $newValue);
} else {
  $newArray[$key] = $newValue;
}

I think you should also add: is_array($newArray[$key])

parse() should expect a string, not a file path

One thing that bothered me when doing unit tests was that mass of fixtures due to the fact that parse() expects a path and you cannot just pass a string.
I think this part of the library should be improved. It relies on the SF2 Yaml component and cannot be substituted. Also, methods like parseYaml and loadAndParseFile etc. look like their specific to the SF2 Yaml component.

What do you think about an interface and a default behavior implementing that interface and providing the current functionality? Or at least modify parse() in a way that it supports a direct string input?

[BUG?] Unable to require 1.0.0

For some reason Composer can't locate the 1.0.0 branch for PHP RAML Parser. I stuck it in require as "alecsammon/php-raml-parser": "1.0.0" and also tried setting the @dev flag and appending -dev with no luck. Originally my composer.json had a minimum stability of "dev", but I've since removed that for best practices. It was on there from the original repo I had the JSON from, so I tried requiring this repo with it on without any luck. Composer was scanning the tags for the repo, but not the branches.

I've been picking at this problem for some time now, and I'm starting to wonder if it's not my configuration that's the problem, but possibly something on the repository that's causing it. Can you look into it and let me know if it's something on your end, please?

API validation in Laravel/Lumen

Hi,

is there any guidance available how to use this parser to perform REST API validation in Laravel/Lumen against the RAML description?

Thanks!

Bad parsing of SecuritySchemas

securitySchemes:
  - oauth_2_0: !include external/oauth2.spec.yml

This genarates the follwing structure:

array (
  0 => 
  array (
    'oauth_2_0' => '!include external/oauth2.spec.yml',
  ),
)

So when trying to get the oauth_2_0 security scheme you are looking in the wrong array and this get the following error.

Notice: Undefined index: oauth_2_0

from the ApiDefinition ->getSecurityScheme ('oauth_2_0') call.

Is is possible to get the expected result using

securitySchemes:
  oauth_2_0: !include external/oauth2.spec.yml

But that is not compatible with the Spec and breaks tools like Mulesoft's Anypoint Platform.

Spec example from docs is:

#%RAML 0.8
title: Dropbox API
version: 1
baseUri: https://api.dropbox.com/{version}
securedBy: [oauth_2_0]
securitySchemes:
    - oauth_2_0: !include oauth_2_0.yml
    - oauth_1_0: !include oauth_1_0.yml
/users:
    get:
        securedBy: [oauth_2_0, oauth_1_0]

Parser adds ID property to external JSON example

I've run into a wierd situation -- JSON example, loaded from external file (!include) is changed by the parser - it contains ID element with path to itself.

PHPUnit output:

phpunit --filter doesNotAddIdTo
PHPUnit 4.6.7 by Sebastian Bergmann and contributors.

Configuration read from /opt/web/vendor/alecsammon/php-raml-parser/phpunit.xml

F.

Time: 5.18 seconds, Memory: 9.25Mb

There was 1 failure:

1) ParseTest::doesNotAddIdToExternalExampleJson
External example should not contain forced ID property
Failed asserting that object of class "stdClass" does not have attribute "id".

/opt/web/vendor/alecsammon/php-raml-parser/test/ParseTest.php:793
/opt/web/vendor/phpunit/phpunit/src/TextUI/Command.php:151
/opt/web/vendor/phpunit/phpunit/src/TextUI/Command.php:103

(unit tests)

/external

stdClass Object
(
    [title] => this is not an ID
    [id] => file:///opt/web/vendor/alecsammon/php-raml-parser/test/fixture/exampleWithoutId.json
)

/internal

stdClass Object
(
    [title] => this is not an ID
)

Problem (for me) is that this breaks tests on my projects that validates all examples against JSON schema that has "additionalProperties": false.

For now -- I didn't dig in to try to fix this. Please advise.

Bug on the Method class

In the constructor of the method class, if there are queryParameters, the data variable gets overwritten in the foreach (line 60), so when we get to the properties sections, the data variable is not anymore the one passed to the constructor. Or we move the assignment to the top of the constructor (line 68 to 70) or we rename the variable $data in the foreach.

Another thing, the Response class is missing getters for the description and status code.

[BUGS] Security scheme parsing messed up

The settings in the configuration object for parseSecuritySchemes don't function properly. I've changed the code to correctly parse the settings array, and the switch tells the script to use only the default parser or not. (Avoids the invalid key issue when looking for the settings.) Also, I added back in the code to select if the security call data should merge with the main call or not. (Backwards compatible). Plus, I've added a way to grab the array of settings data from the default security settings parser so people don't need to make one-off calls to every setting they need.

Validation fails on requests/responses with no body

The RequestValidator class does not appear to handle validating requests without a body defined in the RAML (e.g. a standard GET request).

Calling validateRequest() will result in an error like the one below because no content-type header is set and therefore there are no bodies that match:

Schema for GET /test with content type was not found in API definition

The ResponseValidator class also appears to have the same issue when validating responses without a body defined (e.g. for a 204 response).

Is there any reason why this would be the intended behavior? When the content-type header is not set on the request/response object, the body validation should just get skipped, shouldn't it?

Call for maintainers ๐Ÿ’ก

@alecsammon does not have the bandwidth to maintain the project anymore. He has agreed to hand over the project to whoever is willing to take over. We could also consider hosting it under the https://github.com/raml-org organization.

I am tagging a few people here based on the latest PRs. I also think those PRs would be a good starting point for a new release.

@vbartusevicius
@InfopactMLoos
@AnzeDspot
@therealgambo
@jefferson-lima
@RETFU

(I apologize in advance if you're not interested but this seemed like the best way to do this)

Type support for RAML 1.0

Hello,

I have noticed that parser does not support parsing examples/definitions of responses with new "Type" that was introduced in RAML 1.0, however it still support schema only which is deprecated and will be eventually removed.

Since I want to use RAML 1.0 with all new feature fork will be created and this functionality(Type definitions) implemented.

However for sure it will be useful for someone else too, so can we define and discuss everything regarding this so the output of the commit will be best generic code.

/test:
  get:
    responses:
      200:
        body:
          application/json:
            type: TestType
types:
  TestType:
    type: !include type/index.raml
    example: !include example/index.json

Example is pure json and just need to be included, but type is an object and should be parsed with all it's parameters.

type: object
properties:
    id: integer
    name: string
    created:
        type: datetime
        format: rfc3339
    modified:
        type: datetime
        format: rfc3339

Basically it should support keys defined in specification:

[FEATURE] Custom settings in securedBy

The official RAML specs state that the securedBy field can specify custom settings for the security scheme. The syntax shown on the official documentation is incompatable with the Symfony YAML parser, but an alternative syntax makes the custom settings possible.

Official syntax

securedBy: [null, oauth_2_0: { scopes: [ ADMINISTRATOR ] } ]

Compatable Syntax

securedBy: [null, {oauth_2_0: { scopes: [ADMINISTRATOR] } } ]

Update notes

The only difference in the alternative syntax is that you make each parameter receiving alternate values an array. My update adds the custom settings functionality for the resource and method securedBy parameters, but doesn't alter references when you use securedBy at the root. (Just set those settings in the security schemes as the defaults.)

I've also added a couple extra features to make it easier to work with security schema settings objects. In addition to the existing functionality to add settings for RAML specified entries, you can now add custom settings for your authentication methods. Call getSettings() on the settings object to grab an array of all settings data. The parsers now use the createFromArray() method to populate data.

SecurityScheme->getKey return string(4) "null" instead of NULL

example.raml

#%RAML 0.8

title: Example API
securitySchemes:
    - oauth_2_0: !include oauth_2_0.yml

/api/example/request
  get:
    securedBy: [oauth_2_0, null]
...

testcode.php

$ramlParser = new RamlParser();
foreach ($ramlParser->parse('example.raml', true)->getResources() as $resource) {
          foreach ($resource->getMethods() as $method) {
                $securitySchemes =$method->getSecuritySchemes();
                foreach ($securitySchemes as $scheme) {
                    var_dump($scheme->getKey());
                }
            }
        }
}

Result of code execution.
Actual result:
string(9) "oauth_2_0"
string(4) "null"

Expected result:
string(9) "oauth_2_0"
NULL

Stable version

What do we need to get a first stable version out?

My current thoughts

  • More support of the complete RAML spec
  • A fixed interface for the classes
  • A refactor of the tests
  • Better test coverage, with more full example RAML files

A nice to have would be the ability to convert the API Definition back into a RAML file. This would be a useful feature anyway, but also would make testing quite easy. Parse a RAML file, convert it back to RAML and ensure that they are the same.

resourcePathName in nested resource not working as expected

Using resourcePathName a resourceType always gets replaced by the top level path name (foo), not the current one (bar).

I am using version 2.1.0
Reference: 28b74edef23606a428e3443de464372780feb9b7

I made a really simple example to show the problem:

# api.raml

#%RAML 1.0

---
title: Test API

resourceTypes:
    - test:
        description: Get a list of <<resourcePathName>>.

/foo:
    type: test
    /bar:
        type: test
// index.php
$api = (new Raml\Parser())->parse('api.raml');

$foo = $api->getResources()['/foo'];
$bar = $foo->getResources()['/foo/bar'];

var_export(transform($foo));
var_export(transform($bar));

function transform($resource) {
    return [
        'uri' => $resource->getUri(),
        'description' => $resource->getDescription(),
    ];
}
// output
array (
  'uri' => '/foo',
  'description' => 'Get a list of foo.',
)
array (
  'uri' => '/foo/bar',
  'description' => 'Get a list of foo.', // Here I would expect "Get a list of bar"
)

The dependencies defined for Composer are to tight

Do you think we could review the versions in the composer.json file? Ideally, the constraint would require a package version equal or higher than the given one. Composer supports this, so it should not be a problem. It's even better than using an asterisk on the minor version, for instance.

json-schema integration not up to the spec

Scenario:

#%RAML 0.8
title: Sample for Schema Support
version: 1
baseUri: http://some.example.com
protocols: [ HTTPS, HTTP ]
mediaType: application/hal+json
schemas:
  - account: |
      {
        "type": "object",
        "$schema": "http://json-schema.org/draft-03/schema",
        "id": "http://jsonschema.net",
        "required": true,

        "properties": {
          "id": {
            "type": "string",
            "required": false
          },
          "emails": {
              "type": "array",
              "items": { "$ref": "email" }
          }
        }
      }
  - email: |
      {
        "type": "object",
        "$schema": "http://json-schema.org/draft-03/schema",
        "id": "http://jsonschema.net",
        "required": true,
        "properties": {
          "id": {
            "type": "string",
            "required": false
          },
          "address": {
            "type": "string",
            "required": true
          },
          "primary": {
            "type": "boolean",
            "required": true
          },
          "confirmed": {
            "type": "boolean",
            "required": true
          }
        }
      }

/accounts:
  displayName: Accounts
  description: Handles all account operations
  get:
    description: Find and list accounts
    responses:
      200:
        body:
          application/json:
            schema: account

Using the above example i should get a valid result to navigate (raml successfully parsed), and (as a bonus) my json-schema would load the email entity inside the account emails property.

However it tries to load email as if its a remote json-schema file


Fatal error: Uncaught exception 'JsonSchema\Exception\ResourceNotFoundException' with message 'JSON schema not found at file://./email' in vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php on line 38

JsonSchema\Exception\ResourceNotFoundException: JSON schema not found at file://./email in vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php on line 38

I believe this is an issue in how processing is handed over to json-schema but i'm not entirely sure where the blame lies.

I tried other RAML parsers:

  • js: raml was parsed. json-schema $ref was ignored
{ body: { 'application/json': { schema: '{
  "type": "object",
  "$schema": "http://json-schema.org/draft-03/schema",
  "id": "http://jsonschema.net",
  "required": true,

  "properties": {
    "id": {
      "type": "string",
      "required": false
    },
    "emails": {
        "type": "array",
        "items": { "$ref": "email" }
    }
  }
}
' } } }
  • python-raml: raml was parsed, schema not expanded
{'body': OrderedDict([('application/json', {'notNull': None, 'formParameters': None, 'example': None, 'schema': 'account'})]), 'headers': None, 'description': None, 'notNull': None}

in the schemas property $ref was also not expanded.

Is there an option to avoid the complete crash and just keep going with the superficial data from schema?

[BUG] A test throws warnings when it can't find the tree/songs.raml fixture.

I just updated my software to your latest commit and I ran the tests. Below is the new output.

PHPUnit 4.6.2 by Sebastian Bergmann and contributors.

Configuration read from /var/www/api/fuel/vendor/alecsammon/php-raml-parser/phpunit.xml

...............................................................  63 / 108 ( 58%)
..................................PHP Warning:  Attempt to assign property of non-object in /var/www/api/fuel/vendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriRetriever.php on line 141
.
Warning: Attempt to assign property of non-object in /var/www/api/fuel/vendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriRetriever.php on line 141
PHP Warning:  file_get_contents(file:///var/www/api/fuel/vendor/alecsammon/php-raml-parser/test/fixture/tree/song.json): failed to open stream: No such file or directory in /var/www/api/fuel/vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php on line 36
.
Warning: file_get_contents(file:///var/www/api/fuel/vendor/alecsammon/php-raml-parser/test/fixture/tree/song.json): failed to open stream: No such file or directory in /var/www/api/fuel/vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php on line 36
.........

Time: 1.25 seconds, Memory: 15.00Mb

OK (108 tests, 244 assertions)

[BUG] getValidationPattern() is unreliable.

The Problem
\Raml\NamedParameter uses getValidationPattern() to pull type checking regex, as well as the RAML defined "pattern" data.

When the RAML data doesn't include a "pattern" entry, you get the pattern for the type checking. RegEx is slower than PHP type checking with is_string() or is_int() or the like, so that really shouldn't be part of the getter IMO.

However, the real issue is that when a validation pattern is present in the RAML data, you don't have any way to know if you've just validated the value off of the pattern supplied in the RAML data or if you just validated it with a generic type checking method, including the default patterns to match everything one character or longer.

I prefer to perform type and length checking without RegEx to help make my programs more efficient, but if a pattern is present in the RAML data, I'd like to keep with the spec, and validate against it. However, in the current setup, I'm unable to reliably verify that I'm only validating against the RAML supplied pattern.

The solution
Add an optional parameter to force the return of the RAML supplied value if it exists, just like the other getters do.

array_replace_recursive being called with values other than arrays

Hi, Alec.

I found a bit of code that might be lacking some validation.

I'm getting an error when array_replace_recursive is called with the second argument not being an array.

The method Raml\Parser::replaceTraits will indeed call itself recursively, and return its argument $raml when it finds it's not an array - the problem is that it calls itself and it passes the returned value directly to array_replace_recursive.

    private function replaceTraits($raml, $traits, $path, $name)
    {
        if (!is_array($raml)) {
            return $raml;
        }

And then.

                    $newArray = array_replace_recursive($newArray, $this->replaceTraits($trait, $traits, $path, $name));
                }
            } else {
                $newValue = $this->replaceTraits($value, $traits, $path, $name);

                if (isset($newArray[$key])) {
                    $newArray[$key] = array_replace_recursive($newArray[$key], $newValue);

Any chances we might get a patch soon?

Thanks!

Replace schema name by schema root value

Hi @alecsammon ,

Considering following example,

#%RAML 0.8
title: Schema from root chema

schemas:
 - song: |
    {
      "type": "object",
      "$schema": "http://json-schema.org/draft-03/schema",
      "id": "http://jsonschema.net",
      "required": true,
      "properties": {
        "songTitle": {
          "type": "string",
          "required": true
        },
        "albumId": {
          "type": "string",
          "required": true,
          "minLength": 36,
          "maxLength": 36
        }
      }
    }

/songs:
  /{id}:
    get:
      responses:
        200:
          body:
            application/json:
              schema: song

an Exception: Invalid JSON in schema is thrown.

I think it can be a nice addition for 1.0.0 to implements schema root replacement.

@alecsammon your opinion ?

Handle Parameters Transformers

Hi guys,

What do you think about parameters transformer ?
Is there any idea on how to handle it (what php inflection library to use for example) ?

This would be a great feature.

Schemas returned as stdClass

Hi, great work!

is there any reason why the JSON schemas are returned as stdObjects instead of arrays?

I want to start a PR to add the ability of retrieving the schemas defined in the root of the API (not only in resources), but I would really like them to be arrays instead of arrays of stdObjects. Is there any special motive for this decission?

[FEATURE] Apply securedBy to resources, and not always merge with methods

The Problem
The RAML spec shows that the securedBy parameter may appear on both methods, and resources. The current setup does not allow for resources to use securedBy. Also, the current setup doesn't allow for security restrictions using secondary servers. Method simply merges all securityScheme data into the current request.

The Solution
I've changed the code to allow for backwards compatible new features. You can change whether or not the parser will merge securedBy data with the method or not. I propose that in version 2.0.0 of PHP RAML Parser that we default to not merging the securedBy data as people can merge it later by calling \Raml\Method::addSecurityScheme() with the $merge parameter set to true. That allows for more extensibility, as you'll need to use array_diff() and the like to remove securityScheme data from the method data.

I've also added the ability to add securedBy data to resources. securitySchemes entries are incompatible with resource merging, so there's no need to add that functionality.

[BUG] formParameters and Named Parameters not correct for the method

The Problem
When creating a method which utilizes the "body" parameter, \Raml\Method::createFromArray() checks for valid types. If the valid type exists, then it sets the valid type as a key, and passes its contents to \Raml\WebFormBody::createFromArray(), an alias for \Raml\NamedParameter::createFromArray().

The NamedParameter class is intended to process data for a named parameter as described in the RAML 0.8 spec for Named Parameters. However, the RAML format specifies an extra entry of "formParameters" after the "body" token's valid media types, and before a named parameter even shows up as defined by the spec. (See Named Parameters with Multiple Types)

Also, the Named Parameter should use the key for each named parameter, not the valid media type as a key. The valid media type doesn't implement the same data structure as a Named Parameter, so even omitting the "formParameters" token doesn't allow for parsing any Named Parameters.

#%RAML 0.8
title: Amazon simple storage API
version: 1
baseUri: https://{destinationBucket}.s3.amazonaws.com
/:
  post:
    description: The POST operation adds an object to a specified bucket using HTML forms.
    body:
      application/x-www-form-urlencoded:
        formParameters:
          AWSAccessKeyId:
            description: The AWS Access Key ID of the owner of the bucket who grants an Anonymous user access for a request that satisfies the set of constraints in the Policy.
            type: string
          acl:
            description: Specifies an Amazon S3 access control list. If an invalid access control list is specified, an error is generated.
            type: string
          file:
            - type: string
              description: Text content. The text content must be the last field in the form.
            - type: file
              description: File to upload. The file must be the last field in the form.

Proposed Solution
Create \Raml\WebFormBody::createFromArray() and have it loop over each named parameter and run \Raml\NamedParameter::createFromArray(). Store each named parameter in a private array local to the \Raml\WebFormBody class, and have a getter/setter method to add and retrieve named parameters.

Therefore, the code:

\V1\RAML::parse()->getResourceByUri('/')->getMethod('POST')->getBodyByType('application/x-www-form-urlencoded')->getNamedParameters();

Should return an array of \Raml\NamedParameter objects to work with.

[FEATURE] Apply a trait based security scheme to the whole API

Three Features
This thread actually describes three separate things. First, the RAML 0.8 spec states that a security scheme can be added to the root data for an API to signify that it secured the whole API. That allows for the second function.

When making OAuth calls, you make multiple API calls, so having all the security scheme data merged with the call that has the securedBy token created bogus entries in the main call, and could accidentally override Named Parameters in the main call. Therefore, since the RAML spec doesn't differentiate between multiple call, and single call security structures (yet?), the parser should allow for a method to pick and chose between both methods.

When creating a program to automatically call an API, you can always check what's securing each call, and merge that data in as needed. However, you can't always remove bogus entries once they're merged and expect to maintain system security. So, to keep things simple, and compliant, the root defined secured by shouldn't be merged with the methods. Only the method defined securedBy should be merged with the method.

As for the third portion of this thread, the RAML 0.8 spec states that the describedBy attribute MAY be used to apply a trait-based structure to the security schema. Therefore, since traits are equivalent to the data in a method, they could contain body data. (Ex. POST data)

Good News
I've already built that functionality, and I've updated my repo. Now the pull request has that functionality, too.

Define minimal php version required

Currently, the require section of composer.json does not state the minimal php version supported by the lib. I've tried using it on PHP 5.3 (please don't judge ^^) but the code uses short array syntax [] supported since PHP 5.4.

It could be a great idea to decide which version is supported, and add it in composer.json. Does someone knows if PHP 5.4 is enough for this lib ? Or knows about a cool static code analyser that can check that ?

I can push a PR, but basically you just have to add it :

...
  "require": {
    "php": ">=5.4",
    ...

Body/WebFormBody can't handle null bodies.

The current implementation of Body/WebFormBody's createFromArray method does not support the shortcut: !!null. Judging by the spec, this is legitimate:

/jobs:
  post:
    description: Create a Job
    body:
      text/xml: !!null
      application/json: !!null

At present, using RamlParser over that schema will result in:

PHP Catchable fatal error:  Argument 2 passed to Raml\Body::createFromArray() must be of the type array, string given, called in alecsammon/php-raml-parser/src/Method.php on line 143 and defined in alecsammon/php-raml-parser/src/Body.php on line 87

We currently call createFromArray from three locations, Method, Response and SecuritySchemeDescribedBy and unfortunately, we are inconsistent.

Response does not check the key for a valid media type, and it attempts to loosely handle a 'falsey' body by passing an empty array. Unfortunately !!null isn't going to trigger this logic, so it too will also fail.

I suggest we update all three calling locations to correctly handle !!null

justinrainbow/json-schema 2.0 support

I've investigated the possibility of updating the json-schema parser to 2.0, but the problem is that it has no notion of parsing a string. It could of course be worked out by extending the json-schema parser to be able to parse strings, but wouldn't it make sense to just resolve things as they are loaded (as that parser does)?

Is the two-stage first-load-then-parse process necessary?

QueryParamters type always returns string

I am having an issue that all the query parameters have the type string, no matter what I assign in the raml files. Seems that we check the resource types files to check if there is some configuration, but no matter what I put, it gets ignored.

After debugging, I think the problem relies on the Parser class, method replaceTypes. We check for the particular case when key has the value 'type' and then execute some "magic", but in the end, if one of the conditions is true, we reassign the variable $type with another value, instead of adding to the array (line 303, $type was assigned an empty array). Still, I think this is not the problem, but in the instruction afterwards, we call array_replace_recursive, but the base array, does not contain any key 'type', so, in the end, the $newArray, will always be left untouched. I fixed the problem by commenting out the line 317 (the one with the array_replace_recursive), and assign straight away to $newArray[''] the result of the computation inside the if/elseif (line 312 and 314).

This is a lot of blah blah, I know, I can make a PR, but first I would like to make sure we actually need all this logic for the type field. Why is so special about it? And the QueryParameter class is ignoring other important fields, part of the RAML specification, e.g., description, example and required. I think we should add them, I can include it on my PR. What do you guys think?

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.