Beispiel #1
0
 public function testSecuritySchemesParse()
 {
     $parser = new Parser();
     $definition = $parser->parse(__DIR__ . '/../raml/security-schemes.raml');
     $this->assertInstanceOf(Definition::class, $definition);
     $this->assertInstanceOf(SecuritySchemes::class, $definition->securitySchemes());
 }
    /**
     * Returns a valid api def
     *
     * @throws \Exception
     *
     * @return \Raml\ApiDefinition
     */
    private function getValidDef()
    {
        $raml = <<<RAML
#%RAML 0.8
title: Users API
version: 1.2
baseUri: https://{apiDomain}.someapi.com/{version}
/users:
  displayName: retrieve all users
  baseUriParameters:
    apiDomain:
      enum: [ "api" ]
  /{userId}/image:
    displayName: access users pictures
    baseUriParameters:
      apiDomain:
        enum: [ "static" ]
    get:
      displayName: retrieve a user's picture
    put:
      displayName: update a user's picture
      baseUriParameters:
        apiDomain:
          enum: [ "content-update" ]
RAML;
        return $this->parser->parseFromString($raml, '');
    }
 /** @test */
 public function shouldReturnAnArrayOfTypes()
 {
     $apiDefinition = $this->parser->parse(__DIR__ . '/fixture/multipleTypes.raml');
     $resource = $apiDefinition->getResourceByUri('/');
     $method = $resource->getMethod('post');
     $body = $method->getBodyByType('application/x-www-form-urlencoded');
     $this->assertInstanceOf('\\Raml\\WebFormBody', $body);
 }
 /** @test */
 public function shouldCorrectlyValidateInvalidJson()
 {
     $simpleRaml = $this->parser->parse(__DIR__ . '/fixture/simple.raml');
     $resource = $simpleRaml->getResourceByUri('/songs');
     $method = $resource->getMethod('get');
     $response = $method->getResponse(200);
     $body = $response->getBodyByType('application/json');
     $schema = $body->getSchema();
     $this->setExpectedException('\\Raml\\Exception\\InvalidJsonException');
     try {
         $schema->validate('{');
     } catch (\Raml\Exception\InvalidJsonException $e) {
         $this->assertEquals(4, $e->getErrorCode());
         throw $e;
     }
 }
Beispiel #5
0
 /** @test */
 public function shouldParseCustomSettingsOnMethodWithOAuthParser()
 {
     $apiDefinition = $this->parser->parse(__DIR__ . '/fixture/securedByCustomProps.raml');
     $resource = $apiDefinition->getResourceByUri('/test');
     $method = $resource->getMethod('get');
     $schemes = $method->getSecuritySchemes();
     $settingsObject = $schemes['oauth_2_0']->getSettings();
     $this->assertSame($settingsObject->getScopes(), array('ADMINISTRATOR', 'USER'));
     $this->assertSame($settingsObject->getAuthorizationUri(), 'https://www.dropbox.com/1/oauth2/authorize');
 }
    /** @test */
    public function shouldCorrectlyParseBaseUriParameters()
    {
        $raml = <<<RAML
#%RAML 0.8
title: User API
version: 1.2
/user:
  /{userId}:
    displayName: Get a user
    uriParameters:
      userId:
        type: integer
    get:
      displayName: retrieve a user's picture
RAML;
        $apiDef = $this->parser->parseFromString($raml, '');
        $resource = $apiDef->getResourceByUri('/user/1');
        $this->assertInstanceOf('\\Raml\\Resource', $resource);
    }
    /** @test */
    public function shouldCorrectlyParseRegexUriParameters()
    {
        $raml = <<<RAML
#%RAML 0.8
title: User API
version: 1.2
/user:
  /{userName}:
    displayName: Get a user by name
    uriParameters:
      userName:
        type: string
        pattern: ^[a-z0-9]+\$
    get:
      displayName: retrieve a user's picture by user name
RAML;
        $apiDef = $this->parser->parseFromString($raml, '');
        $resource = $apiDef->getResourceByUri('/user/alec');
        $this->assertInstanceOf('\\Raml\\Resource', $resource);
    }
 /** @test */
 public function shouldApplyAnnotationsOnMethod()
 {
     $apiDefinition = $this->parser->parse(__DIR__ . '/fixture/annotations.raml');
     $resource = $apiDefinition->getResourceByUri('/songs');
     $method = $resource->getMethod('get');
     $annotations = $method->getAnnotations();
     $this->assertArrayHasKey('permission', $annotations);
     $annotation = $annotations['permission'];
     $this->assertInstanceOf(Raml\Annotation::class, $annotation);
     $this->assertSame(array('key' => 'songs.list'), $annotation->getValue());
 }
 /**
  * {@inheritDoc}
  */
 public function convert($filename, $namespace)
 {
     $def = $this->parser->parse($filename);
     $namespace = $this->buildNamespace($def, $namespace);
     $controllers = array();
     if ($def->getResources()) {
         foreach ($def->getResources() as $resource) {
             $controller = new SymfonyController(ucfirst($resource->getDisplayName()) . 'Controller', $namespace, $resource->getDescription());
             $this->addActions($controller, $resource);
             $controllers[] = $controller;
         }
     }
     return $controllers;
 }
 /** @test */
 public function shouldParseResourcePathNameCorrectly()
 {
     $apiDefinition = $this->parser->parse(__DIR__ . '/fixture/resourcePathName.raml');
     $foo = $apiDefinition->getResources()['/foo'];
     $fooId = $foo->getResources()['/foo/{fooId}'];
     $bar = $fooId->getResources()['/foo/{fooId}/bar'];
     $this->assertEquals('Get a list of foo', $foo->getDescription());
     $this->assertEquals('Get a single foo', $fooId->getDescription());
     $this->assertEquals('Get a list of bar', $bar->getDescription());
     $baz = $apiDefinition->getResources()['/baz'];
     $bazId = $baz->getResources()['/baz/{bazId}'];
     $qux = $bazId->getResources()['/baz/{bazId}/qux'];
     $this->assertEquals('Get a list of bazDisplayname', $baz->getDescription());
     $this->assertEquals('Get a single bazDisplayname', $bazId->getDescription());
     $this->assertEquals('Get a list of quxDisplayname', $qux->getDescription());
 }
    /** @test */
    public function shouldThrowExceptionOnInvalidFile()
    {
        $raml = <<<RAML
#%RAML 0.8
title: Test named parameters
/:
  post:
    body:
      application/x-www-form-urlencoded:
        formParameters:
          param:
            type: file
            default: 1
RAML;
        $this->setExpectedException('Exception', 'A default value cannot be set for a file');
        $this->parser->parseFromString($raml, '');
    }
Beispiel #12
0
    /** @test */
    public function shouldSupportGenericResponseType()
    {
        $raml = <<<'RAML'
#%RAML 0.8
title: Test body
/:
  get:
    description: A post to do something
    responses:
      200:
        body:
          "*/*":
            description: A generic description
RAML;
        $apiDefinition = $this->parser->parseFromString($raml, '');
        $resource = $apiDefinition->getResourceByUri('/');
        $method = $resource->getMethod('get');
        $response = $method->getResponse(200);
        $body = $response->getBodyByType('text/xml');
        $this->assertEquals('A generic description', $body->getDescription());
    }
    /** @test */
    public function shouldBeAbleToGetAllParameters()
    {
        $raml = <<<RAML
#%RAML 0.8
title: Test named parameters
/:
  post:
    body:
      multipart/form-data:
        formParameters:
          string:
            type: string
            default: A string
RAML;
        $apiDefinition = $this->parser->parseFromString($raml, '');
        $resource = $apiDefinition->getResourceByUri('/');
        $method = $resource->getMethod('post');
        $body = $method->getBodyByType('multipart/form-data');
        $parameters = $body->getParameters();
        $expectedParameter = new \Raml\NamedParameter('string');
        $expectedParameter->setDefault('A string');
        $this->assertEquals(['string' => $expectedParameter], $parameters);
    }
 /** @test */
 public function shouldThrowInvalidProtocolExceptionIfWrongProtocol()
 {
     $this->setExpectedException('Raml\\Exception\\BadParameter\\InvalidProtocolException');
     $this->parser->parse(__DIR__ . '/fixture/protocols/invalidProtocolsSpecified.raml');
 }
Beispiel #15
0
 /**
  * @param string $ramlFile
  */
 public function generateRest($ramlFile, Local $directoryOutput)
 {
     $parser = new Parser();
     try {
         /*
          * file di routing symfony
          * @var array
          */
         $routing = [];
         /*
          * Mappa delle proprieta dei controller da generare
          * @var array
          */
         $mappaClassDef = [];
         $this->apiDef = $parser->parse($ramlFile);
         $this->logger->info('Title: ' . $this->apiDef->getTitle());
         $baseUrl = $this->apiDef->getBaseUrl();
         $parametriBaseUrl = $this->apiDef->getBaseUriParameters();
         /** @var \Raml\BaseUriParameter $definition */
         foreach ($parametriBaseUrl as $varName => $definition) {
             if (!array_key_exists($varName, $this->mapExternalInfo)) {
                 $this->error('Missing: ' . $varName . ' -> ' . $definition->getDescription());
                 $this->mapExternalInfo[$varName] = 'undefined';
             }
             $baseUrl = str_replace($varName, $this->mapExternalInfo[$varName], $baseUrl);
         }
         $this->info('BaseUrl ' . $baseUrl);
         //corrisponde a host: "{subdomain}.example.com" dentro routing.yml
         $enabledProtocols = $this->apiDef->getProtocols();
         //serve per fare controlli su http/https -> schemes:  [https] dentro routing.yml
         $infoSecuritySchema = $this->apiDef->getSecuredBy();
         // descrive i vari security schema usati nelle varie risorse
         /* @var: \Raml\Resource[] */
         $resources = $this->apiDef->getResources();
         $namespace = $this->bundleName . '\\Controller';
         /** @var: \Raml\Resource $resource */
         foreach ($resources as $resource) {
             $displayName = $resource->getDisplayName();
             $this->info('Controller per path: ' . $displayName);
             $names = explode('/', $displayName);
             preg_match_all("/(\\/{[a-zA-Z]+}(\\/)?)+/i", $displayName, $methodParam);
             array_walk($names, [$this, 'removeGraph']);
             $className = implode('', $names);
             $methods = $resource->getMethods();
             if (count($methods) > 0) {
                 /** @var \Raml\Method $method */
                 foreach ($methods as $method) {
                     $controllerName = ucfirst($className);
                     // Creo $appBundle / $workspace Controller . php
                     $this->info('Genera: ' . $namespace . $controllerName . 'Controller');
                     $controllerProperties = [];
                     $controllerProperties['name'] = $controllerName . 'Controller';
                     $controllerProperties['namespace'] = $namespace;
                     $controllerProperties['extend'] = 'Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller';
                     $methodListParams = implode(',', $methodParam[0]);
                     $type = strtolower($method->getType());
                     $methodCallName = $type . $controllerName;
                     $actionName = $methodCallName . 'Action';
                     $this->info('Call Method: ' . $actionName . '(' . $methodListParams . ')');
                     $controllerProperties['methods'] = [];
                     $controllerProperties['methods'][$actionName] = [];
                     $controllerProperties['methods'][$actionName]['params'] = [];
                     $description = $method->getDescription();
                     $this->info('Description: ' . $description);
                     $entryName = strtolower($className) . '_' . $type;
                     $routing[$entryName]['path'] = $displayName;
                     $routing[$entryName]['defaults']['_controller'] = $this->bundleName . ':' . $controllerName . ':' . $methodCallName;
                     $routing[$entryName]['host'] = $baseUrl;
                     $routing[$entryName]['methods'] = [];
                     $routing[$entryName]['methods'][] = strtoupper($type);
                     $routing[$entryName]['schemas'] = $enabledProtocols;
                     $routing[$entryName]['requirements'] = [];
                     $routing[$entryName]['requirements'][] = 'FIXME';
                     $mappaClassDef[$controllerName . 'Controller'] = $controllerProperties;
                 }
                 //fine methods
             }
             /* @var \Raml\Resource $subResources */
             $subResources = $resource->getResources();
             foreach ($subResources as $subResource) {
                 //$this->analyzeResource($subResource, $directoryOutput);
                 //// SAMPLE:
                 // /Workspace GET => Workspace/GetWorkspace.php
                 // /Workspace POST => Workspace/POSTWorkspace.php
                 // /Workspace/{id} GET => Workspace/GetWorkspaceById.php
             }
         }
         //fine reousrces
         $indent = 4;
         $inline = 2;
         $yaml = new Dumper($indent);
         $this->currentFile = $yaml->dump($routing, $inline, 0, 0);
         $this->_createFileOnDir($directoryOutput, $this->bundleName . '/Resources/config/routing.yml');
         foreach ($mappaClassDef as $className => $controllerProp) {
             $this->info('Devo creare ' . $className);
             $gClassgen = new ClassGenerator($namespace, $className);
             $gClassgen->setLogger($this->logger);
             $config = new ClassConfig();
             $typesReferenceArray = [];
             $typesDescArray = [];
             $gClassgen->generateClassType($controllerProp, $typesReferenceArray, $typesDescArray, $config);
             $gClassgen->createFileOnDir($directoryOutput);
         }
         $this->info('Scrittura su ' . $directoryOutput);
     } catch (InvalidJsonException $e) {
         $this->error('[' . $e->getErrorCode() . '] ' . $e->getMessage());
         $this->error($e->getTraceAsString());
     } catch (RamlParserException $e) {
         $this->error('[' . $e->getErrorCode() . '] ' . $e->getMessage());
     }
 }
 /**
  * @param string $fixturePath
  * @return ValidatorSchemaHelper
  */
 public function getHelperForSchema($fixturePath)
 {
     $apiDefinition = $this->parser->parse($fixturePath);
     return new ValidatorSchemaHelper($apiDefinition);
 }
Beispiel #17
0
 /**
  * @param string $input file from generate
  */
 public function parse($input)
 {
     $this->base_dir_raml = str_replace(basename($input), '', $input);
     $this->specification = $this->parser->parse($input, true);
 }
 /**
  * Common to all tests
  * @return \Raml\Schema\Definition\XmlSchemaDefinition
  */
 private function loadXmlSchema()
 {
     $xmlRaml = $this->parser->parse(__DIR__ . '/fixture/xmlSchema.raml');
     return $xmlRaml->getResourceByUri('/jobs')->getMethod('get')->getResponse(200)->getBodyByType('text/xml')->getSchema();
 }
Beispiel #19
0
 /**
  * @param $rawFileName
  */
 public function __construct($rawFileName)
 {
     $parser = new Parser();
     $this->ramlParser = $parser->parse($rawFileName);
 }
 /**
  * @param string $fixturePath
  * @return RequestValidator
  */
 private function getValidatorForSchema($fixturePath)
 {
     $apiDefinition = $this->parser->parse($fixturePath);
     $helper = new ValidatorSchemaHelper($apiDefinition);
     return new RequestValidator($helper);
 }
Beispiel #21
0
<?php

use Raml\Parser;
require_once __DIR__ . '/../vendor/autoload.php';
$parser = new Parser();
$definition = $parser->parse(__DIR__ . '/raml/security-schemes.raml');
print_r($definition);