Esempio n. 1
0
 protected function setUp()
 {
     $this->application = new Application();
     $this->application->unitTesting = true;
     $this->application->context()->simulateNonCli = false;
     $this->application->registerModule(new UnitTestingModule());
     $this->application->initialiseModules();
     ExceptionHandler::disableExceptionTrapping();
 }
Esempio n. 2
0
 public function testApplicationData()
 {
     $application = new Application();
     $array =& $application->getSharedArray("test-key");
     $array["key1"] = "value1";
     $array2 =& $application->getSharedArray("test-key");
     $this->assertEquals("value1", $array2["key1"]);
     $array2["that"] = "this";
     $this->assertEquals("this", $array["that"]);
 }
Esempio n. 3
0
 protected function initialiseDefaultValues()
 {
     parent::initialiseDefaultValues();
     $request = Application::current()->request();
     $host = $request->server("SERVER_NAME");
     $this->defaultSender = new EmailRecipient("donotreply@" . $host . ".com");
 }
 public function testDeploymentUrls()
 {
     $package = new ResourceDeploymentPackage();
     $package->resourcesToDeploy = [__FILE__, __DIR__ . "/../../../src/Deployment/Deployable.php"];
     $urls = $package->getDeployedUrls();
     $cwd = Application::current()->applicationRootPath;
     $this->assertEquals(["/deployed" . str_replace("\\", "/", str_replace($cwd, "", __FILE__)), "/deployed" . str_replace("\\", "/", str_replace($cwd, "", realpath(__DIR__ . "/../../../src/Deployment/Deployable.php")))], $urls);
 }
 public function testDeploymentCopiesFiles()
 {
     $cwd = Application::current()->applicationRootPath;
     $deploymentPackage = new RelocationResourceDeploymentProvider();
     $deploymentPackage->deployResource(__FILE__);
     $deployedFile = APPLICATION_ROOT_DIR . "/deployed" . str_replace($cwd, "", __FILE__);
     $this->assertFileExists($deployedFile);
     unlink($deployedFile);
 }
 public function testTheLoginUrlisExcludedFromRedirect()
 {
     $_SERVER["SCRIPT_NAME"] = "/defo/not/here/login/index/";
     $request = new WebRequest();
     $context = new PhpContext();
     $context->Request = $request;
     $request->initialise();
     $response = Application::current()->generateResponseForRequest($request);
     $this->assertInstanceOf(HtmlResponse::class, $response);
 }
 protected function setUp()
 {
     parent::setUp();
     Application::current()->registerModule(new CommunicationsModule());
     Application::current()->initialiseModules();
     Model::clearAllRepositories();
     CommunicationProcessor::setProviderClassName(EmailProvider::class, UnitTestingEmailProvider::class);
     Repository::setDefaultRepositoryClassName(Offline::class);
     Communication::clearObjectCache();
     CommunicationItem::clearObjectCache();
 }
Esempio n. 8
0
 public function storeSession(Session $session)
 {
     $context = Application::current()->context();
     if (!$context->isCliInvocation()) {
         session_start();
     }
     $namespace = get_class($session);
     $_SESSION[$namespace] = $session->extractSessionData();
     // Close the session to make sure we aren't locking other process for this user, e.g.
     // simultaneous AJAX requests.
     if (!$context->isCliInvocation()) {
         session_write_close();
     }
 }
 public function deployResource($resourceFilePath)
 {
     if (isset($this->alreadyDeployed[$resourceFilePath])) {
         return $this->alreadyDeployed[$resourceFilePath];
     }
     $originalResourceFilePath = $resourceFilePath;
     $resourceFilePath = realpath($resourceFilePath);
     if ($resourceFilePath === false) {
         throw new DeploymentException("The file {$originalResourceFilePath} could not be found. Please check the file exists.");
     }
     if (!file_exists("deployed")) {
         if (!mkdir("deployed", 0777, true)) {
             throw new DeploymentException("The deployment folder could not be created. Check file permissions to the 'deployed' folder.");
         }
     }
     if (!file_exists($resourceFilePath)) {
         throw new DeploymentException("The file {$resourceFilePath} could not be found. Please check file permissions.");
     }
     // Remove the current working directory from the resource path.
     $cwd = Application::current()->applicationRootPath;
     $urlPath = "/deployed" . str_replace("\\", "/", str_replace($cwd, "", $resourceFilePath));
     $localPath = $cwd . $urlPath;
     if (!file_exists(dirname($localPath))) {
         if (!mkdir(dirname($localPath), 0777, true)) {
             throw new DeploymentException("The deployment folder could not be created. Check file permissions to the '" . dirname($localPath) . "' folder.");
         }
     }
     if (!file_exists($localPath) || filemtime($resourceFilePath) > filemtime($localPath)) {
         $result = @copy($resourceFilePath, $localPath);
         if (!$result) {
             throw new DeploymentException("The file {$resourceFilePath} could not be deployed. Please check file permissions.");
         }
     }
     if (preg_match('/(\\.js|\\.css)$/', $resourceFilePath, $match)) {
         $urlPath .= '?' . filemtime($resourceFilePath) . $match[1];
     }
     $this->alreadyDeployed[$originalResourceFilePath] = $urlPath;
     return $urlPath;
 }
Esempio n. 10
0
 public function generateResponseForException(RhubarbException $er)
 {
     $context = Application::current()->context();
     if ($context->isXhrRequest()) {
         $response = new Response();
     } else {
         $response = new HtmlResponse();
     }
     $response->setResponseCode(Response::HTTP_STATUS_SERVER_ERROR_GENERIC);
     $response->setContent($er->getPublicMessage());
     return $response;
 }
Esempio n. 11
0
    /**
     * Returns two script tags, one loading the script manager and the second executing all other
     * scripts registered with AddScript.
     *
     * This takes a new approach - instead of adding all the scripts to the <head> tag when
     * rendering full HTML, we use the JS script manager. This means the approach is the same
     * whether the request is a normal HTML page, or an AJAX post. This is borne out of frustration
     * with finding some libraries like Google maps not working if added to the page via AJAX. Any client
     * side issues with the script loader will now become a major concern and should get addressed quickly.
     *
     * @see ResourceLoader::addResource()
     * @return string
     */
    public static function getResourceInjectionHtml()
    {
        $package = new ResourceDeploymentPackage();
        $package->resourcesToDeploy[] = __DIR__ . "/../../resources/resource-manager.js";
        $urls = $package->deploy();
        $html = "<script src=\"" . $urls[0] . "\" type=\"text/javascript\"></script>";
        $context = Application::current()->context();
        $preLoadedFiles = [];
        // CSS files are safe to load immediately and might avoid 'flicker' by so doing.
        if (!$context->isXhrRequest()) {
            foreach (self::$resources as $item) {
                $dependantResources = $item[1];
                foreach ($dependantResources as $resource) {
                    if (in_array($resource, $preLoadedFiles)) {
                        continue;
                    }
                    $parts = explode(".", $resource);
                    $extension = strtolower($parts[sizeof($parts) - 1]);
                    if ($extension == "css") {
                        $html .= "\n<link type=\"text/css\" rel=\"stylesheet\" href=\"" . $resource . "\" />";
                        $preLoadedFiles[] = $resource;
                    }
                    if ($extension == "js") {
                        $html .= "\n<script type=\"text/javascript\" src=\"" . $resource . "\"></script>";
                        $preLoadedFiles[] = $resource;
                    }
                }
            }
        }
        $groupedItems = [];
        foreach (self::$resources as $index => $resource) {
            $dependantResources = $resource[1];
            $dependantResources = array_diff($dependantResources, $preLoadedFiles);
            $urls = implode("", $dependantResources);
            if (!isset($groupedItems[$urls])) {
                $groupedItems[$urls] = [$resource[0], $dependantResources];
            } else {
                $groupedItems[$urls][0] .= "\n\t" . $resource[0];
            }
        }
        $tags = "";
        array_walk($groupedItems, function ($item) use(&$tags, $preLoadedFiles) {
            $source = trim($item[0]);
            $dependantResources = $item[1];
            if (sizeof($dependantResources) > 0) {
                $resourcesArray = '[ "' . implode('", "', $dependantResources) . '" ]';
                if ($source == "") {
                    $source = 'window.resourceManager.loadResources( ' . $resourcesArray . ' );';
                } else {
                    $source = 'window.resourceManager.loadResources( ' . $resourcesArray . ', function()
{
	' . $source . '
} );';
                }
            } else {
                if ($source != "") {
                    $source = 'window.resourceManager.runWhenDocumentReady( function()
{
	' . $source . '
} );';
                }
            }
            $tags .= $source . "\n";
        });
        if (trim($tags) != "") {
            $html .= <<<HTML
<script type="text/javascript">
//<![CDATA[
{$tags}
//]]>
</script>
HTML;
        }
        return $html;
    }
Esempio n. 12
0
 /**
  * Returns the active request from the currently running application.
  *
  * @return Request
  */
 public static final function current()
 {
     return Application::current()->request();
 }
 /**
  * Executes an HTTP transaction and returns the response.
  *
  * @param HttpRequest $request
  * @return HttpResponse
  */
 public function getResponse(HttpRequest $request)
 {
     $context = new PhpContext();
     $context->simulatedRequestBody = "";
     $headers = $request->getHeaders();
     foreach ($headers as $header => $value) {
         $_SERVER["HTTP_" . strtoupper($header)] = $value;
     }
     $_SERVER["REQUEST_METHOD"] = "GET";
     switch ($request->getMethod()) {
         case "head":
             $_SERVER["REQUEST_METHOD"] = "HEAD";
             break;
         case "delete":
             $_SERVER["REQUEST_METHOD"] = "DELETE";
             break;
         case "post":
             $_SERVER["REQUEST_METHOD"] = "POST";
             $context->simulatedRequestBody = $request->getPayload();
             break;
         case "put":
             $_SERVER["REQUEST_METHOD"] = "PUT";
             $context->simulatedRequestBody = $request->getPayload();
             break;
     }
     switch ($headers["Accept"]) {
         case "application/xml":
             $simulatedRequest = new JsonRequest();
             break;
         default:
             $simulatedRequest = new WebRequest();
             break;
     }
     $simulatedRequest->uri = $request->getUrl();
     $simulatedRequest->urlPath = $request->getUrl();
     $rawResponse = Application::current()->generateResponseForRequest($simulatedRequest);
     self::$request = $request;
     self::$requestHistory[] = $request;
     $response = new HttpResponse();
     $response->setResponseBody($rawResponse->formatContent());
     return $response;
 }
Esempio n. 14
0
 public function testLayoutCanBeAnonymousFunction()
 {
     LayoutModule::setLayoutClassName(function () {
         return TestLayout::class;
     });
     $request = new WebRequest();
     $request->urlPath = "/simple/";
     $response = Application::current()->generateResponseForRequest($request);
     $this->assertEquals("TopDon't change this content - it should match the unit test.Tail", $response->getContent());
 }
Esempio n. 15
0
 private function setHeaderInPhp($header)
 {
     if (!Application::current()->unitTesting) {
         header($header);
     }
 }
Esempio n. 16
0
 /**
  * Returns the current container for the running application
  */
 public static final function current()
 {
     return Application::current()->container();
 }
Esempio n. 17
0
 protected function setAsRunningApplication()
 {
     Application::$currentApplication = $this;
 }