<?php

/**
 * @uri /policy/files 0
 */
class PolicyBrowser extends CfProtectedResource
{
    /**
     * Get policies file and directory lists
     *
     * @param $request
     *
     * @rbacName Get file and directory lists
     * @rbacGroup Policy analyzer
     * @rbacAlias policyBrowser.get
     *
     *
     * @return Response
     * @throws Exception
     */
    public function get($request)
    {
        $response = new Response($request);
        $fReader = new FileSystemReader();
        $payload = $fReader->getFiles(POLICY_PATH);

        if ($payload) {
            $response->code = Response::OK;
            $response->body = json_encode($payload);
        }

        return $response;
    }
}

/**
 * @uri /policy/contents 0
 */
class PolicyContent extends CfProtectedResource
{
    /**
     * Get policy content
     *
     * @param $request
     *
     * @rbacName Get policy content
     * @rbacGroup Policy analyzer
     * @rbacAlias policyContent.get
     *
     * @return Response
     * @throws Exception
     */
    public function get($request)
    {
        $response = new Response($request);

        $path = Utils::queryParam('path');

        if (!isset($path) || empty($path)) {
            throw new HttpInvalidParamException('Path is required parameter.');
        }

        $fReader = new FileSystemReader();
        $fullPath = realpath(POLICY_PATH .'/'. $path);

        if (!file_exists($fullPath)) {
            throw new Pest_NotFound('File does not exist.');
        }

        if (!strstr($fullPath, POLICY_PATH)) {
            throw new Pest_NotAcceptable('Resolved absolute path must be a sub directory of ' . POLICY_PATH);
        }

        $payload = $fReader->getFileContent($fullPath);

        if ($payload) {
            $response->code = Response::OK;
            $response->body = $payload;
        }

        return $response;
    }
}
