Rob Sawyer
Rob Sawyer

Reputation: 2183

Swagger-PHP and CakePHP

I'm trying to use Swagger-PHP with my CakePHP project and I'm having some issues. Has anyone set this up? Do you have any advice? I've successfully installed swagger-php via composer and it's loaded within my Controller (see below). I'm trying to render a spec via a web view and I'm not quite sure why registry isn't being populated or if even needs to be.

The following is inside of ApiController.php

use Swagger\Annotations as SWG; 
use Swagger\Swagger;

public function swagger(){
    $path = APP . 'Model'; //Path to the app directory
$swagger = Swagger::discover($path,APP . 'Model/Behavior');
debug($swagger);
 //$swagger->jsonEncode($swagger->registry['/api']);
$swagResults = $swagger->registry;
debug($swagResults);
$this->set(array(
    'results' => $swagResults,
    '_serialize' => 'results'
));
}

Results

object(Swagger\Swagger) {
    resourceList => array()
    registry => array()
    models => array()
    [protected] fileList => array(
        (int) 0 => '~/Sites/com/sitename-api/app/Model/[ModelName].php',
        ... All of my models
    )
    [protected] path => '~/Sites/com/sitename-api/app/Model'
    [protected] excludePath => '~/Sites/com/sitename-api/app/Model/Behavior'
    [protected] cache => object(Doctrine\Common\Cache\ArrayCache) {
        [private] data => array(
            'DoctrineNamespaceCacheKey[]' => (int) 1,
            '[][1]' => 'a:4:{s:8:"registry";a:0:{}s:6:"models";a:0:{}s:4:"path";N;s:11:"excludePath";N;}',
            '[cd9db43f54f6017ba1a20037c1577eb4d2017868][1]' => 'a:4:{s:8:"registry";a:0:{}s:6:"models";a:0:{}s:4:"path";s:56:"~/Sites/com/sitename-api/app/Model";s:11:"excludePath";s:65:"~/Sites/com/sitename-api/app/Model/Behavior";}'
        )
    }
    [protected] cacheKey => 'cd9db43f54f6017ba1a20037c1577eb4d2017868'
}

So, basically $swagResults is empty and I'm guessing this shouldn't be, right?

Upvotes: 0

Views: 4170

Answers (2)

Rob Sawyer
Rob Sawyer

Reputation: 2183

Thanks for your answer Bob, I realized how to actually exclude directories. Anyway, the following is working out so far. Now I just need to get a better handle on the actual Swagger spec.

In your model, add the following:

use Swagger\Annotations as SWG;

/**
 * User Model
 * @SWG\Model(
 *      id="User",
 *      description="Defines a user."
 * )
 */

In the controller, add the following. Note: controller_name is what will be passed to swagger method.

use Swagger\Annotations as SWG;

/**
 * @SWG\Resource(
 *      resourcePath="/users"
 * )
 */

Build a method like the following in an API controller.

/**
 * swagger method
 * This method renders the Swagger spec
 * @param string $controller The controller a.k.a resource to pull Swagger docs for
 * @return array
 */
public function swagger($controller = ''){
    if(!empty($resource)) {
        $this->request->query['resource'] = '/'.$controller;
    }
    $path = APP; //Path to the app directory
    $path = substr($path, 0, -1);
    $swagger = Swagger::discover(
            $path, 
            APP . 'Plugin:' . 
            APP . 'Vendor:' . 
            APP . 'Config:' . 
            APP . 'Test:' .
            APP . 'Console:' .
            //APP . 'Model:' .
            APP . 'View/Helper:' .
            APP . 'Controller/Component:' .
            APP . 'webroot:' .
            APP . 'tmp:' .
            APP . 'index.php:' .
            'libs:' .
            'plugins:' .
            'vendors' 
        );
    $swagger->setDefaultApiVersion(Configure::read('CC.version'));
    $swagger->setDefaultBasePath(Configure::read('CC.site_url') . DS . Configure::read('CC.version'));
    $swagger->setDefaultSwaggerVersion(SWAGGER_VERSION);
    $this->autoRender = false;
    if (isset($this->request->query['resource'])) {
        return $swagger->getResource($this->request->query['resource']);
    }
    $list = array(
        "apiVersion" => API_VERSION,
        "swaggerVersion" => "1.1",
        "basePath" => Router::url(array('?' => array('resource' =>'')), true),
        "apis" => array()
    );
    if (isset($this->request->query['resource'])) {
        return $swagger->getResource($this->request->query['resource']);
    }
    $list['apis'][] = $swagger->registry;
    $this->set(array(
        'results' => $list,
        '_serialize' => 'results'
    ));
}

A method comment might look something like:

/**
 * info method
 * This provides an app with basic user information. 
 * @param int id The user id
 * @return array 
 * @SWG\Api(
 *      path="/users/info/{user_id}.{format}",
 *      description="This provides an app with basic user information.",
 *      @SWG\Operations(
 *          @SWG\Operation(
 *              httpMethod="GET",
 *              summary="User Basic Info",
 *              notes="",
 *              responseClass="List[User]",
 *              nickname="getUserInfo",
 *              group="users",
 *              @SWG\Parameters(
 *                  @SWG\Parameter(
 *                      name="format",
 *                      description="The format that the data will be returned in.",
 *                      paramType="path",
 *                      required="true",
 *                      allowMultiple="false",
 *                      dataType="Array",
 *                      @SWG\AllowableValues(
 *                          valueType="LIST",
 *                          values="['json', 'xml']"
 *                      )
 *                  ),
 *                  @SWG\Parameter(
 *                      name="user_id",
 *                      description="The user id",
 *                      paramType="path",
 *                      required="true",
 *                      allowMultiple="false",
 *                      dataType="int"
 *                  ),
 *                  @SWG\Parameter(
 *                      name="client_id",
 *                      description="Your client id",
 *                      paramType="query",
 *                      required="true",
 *                      allowMultiple="false",
 *                      dataType="string",
 *                      threescale_name="client_ids"
 *                  )
 *              ),
 *              @SWG\ErrorResponses(
 *                  @SWG\ErrorResponse(
 *                      code="404",
 *                      reason="User not found"
 *                  )
 *              )
 *          )
 *      )
 *  )
 */

Note: threescale_name and groups are custom Operations and Parameters that I've added. Just added these to the zircote/swagger-php/library/Swagger/Annotations/(Parameter and Operation).php files if you want to use these. These are 3scale.net specific items.

Upvotes: 0

Bob Fanger
Bob Fanger

Reputation: 29897

I wrote a Controller that generates all the swagger documentation (which requires swagger-php 0.6 or newer):

<?php
use Swagger\Swagger;
class SwaggerController extends AppController {

    function index() {
        $swagger = Swagger::discover(APP, TMP.':'.APP.'Vendor');

        $this->autoRender = false;
        if (isset($this->request->query['resource'])) {
            return $swagger->getResource($this->request->query['resource']);
        }
        $list = array(
            "apiVersion" => "1.0",
            "swaggerVersion" => "1.1",
            "basePath" => Router::url(array('?' => array('resource' =>'')), true),
            "apis" => array()
        );
        foreach ($swagger->registry as $name => $resource) {
            $item = array("path" => $name);
            foreach ($resource->apis as $api) {
                if ($api->description !== null) {
                    $item['description'] = $api->description;
                    break;
                }
            }
            $list['apis'][] = $item;
        }
        return json_encode($list);
    }
}

Upvotes: 2

Related Questions