Skip to content

Commit

Permalink
Remove references to SapphireTest::is_running_test()
Browse files Browse the repository at this point in the history
Upgrade various code
  • Loading branch information
Damian Mooyman committed Jun 20, 2017
1 parent de079c0 commit 001d559
Show file tree
Hide file tree
Showing 18 changed files with 144 additions and 150 deletions.
10 changes: 9 additions & 1 deletion src/Control/Controller.php
Expand Up @@ -52,6 +52,14 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
*/
protected static $controller_stack = array();

/**
* Assign templates for this controller.
* Map of action => template name
*
* @var array
*/
protected $templates = [];

/**
* @var bool
*/
Expand Down Expand Up @@ -507,7 +515,7 @@ public function render($params = null)
$template = $this->getViewer($this->getAction());

// if the object is already customised (e.g. through Controller->run()), use it
$obj = ($this->customisedObj) ? $this->customisedObj : $this;
$obj = $this->getCustomisedObj() ?: $this;

if ($params) {
$obj = $this->customise($params);
Expand Down
60 changes: 25 additions & 35 deletions src/Control/Director.php
Expand Up @@ -8,7 +8,6 @@
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Kernel;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\ArrayLib;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\Requirements;
Expand Down Expand Up @@ -254,7 +253,7 @@ public static function test(
$_REQUEST = ArrayLib::array_merge_recursive((array) $getVars, (array) $postVars);
$_GET = (array) $getVars;
$_POST = (array) $postVars;
$_SESSION = $session ? $session->inst_getAll() : array();
$_SESSION = $session ? $session->getAll() : array();
$_COOKIE = $cookieJar->getAll(false);
Injector::inst()->registerService($cookieJar, Cookie_Backend::class);
$_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
Expand Down Expand Up @@ -288,7 +287,7 @@ public static function test(
}
}

$output = $requestProcessor->postRequest($request, $result, $model);
$output = $requestProcessor->postRequest($request, $result);
if ($output === false) {
throw new HTTPResponse_Exception("Invalid response");
}
Expand Down Expand Up @@ -836,17 +835,15 @@ public static function absoluteBaseURLWithAuth()
* Skip any further processing and immediately respond with a redirect to the passed URL.
*
* @param string $destURL
* @throws HTTPResponse_Exception
*/
protected static function force_redirect($destURL)
{
// Redirect to installer
$response = new HTTPResponse();
$response->redirect($destURL, 301);

HTTP::add_cache_headers($response);

// TODO: Use an exception - ATM we can be called from _config.php, before Director#handleRequest's try block
$response->output();
die;
throw new HTTPResponse_Exception($response);
}

/**
Expand Down Expand Up @@ -877,19 +874,23 @@ protected static function force_redirect($destURL)
*
* @param array $patterns Array of regex patterns to match URLs that should be HTTPS.
* @param string $secureDomain Secure domain to redirect to. Defaults to the current domain.
*
* @return bool|string String of URL when unit tests running, boolean FALSE if patterns don't match request URI.
* @return bool true if already on SSL, false if doesn't match patterns (or cannot redirect)
* @throws HTTPResponse_Exception Throws exception with redirect, if successful
*/
public static function forceSSL($patterns = null, $secureDomain = null)
{
// Calling from the command-line?
// Already on SSL
if (static::is_https()) {
return true;
}

// Can't redirect without a url
if (!isset($_SERVER['REQUEST_URI'])) {
return false;
}

$matched = false;

if ($patterns) {
$matched = false;
$relativeURL = self::makeRelative(Director::absoluteURL($_SERVER['REQUEST_URI']));

// protect portions of the site based on the pattern
Expand All @@ -899,31 +900,20 @@ public static function forceSSL($patterns = null, $secureDomain = null)
break;
}
}
} else {
// protect the entire site
$matched = true;
}

if ($matched && !self::is_https()) {
// if an domain is specified, redirect to that instead of the current domain
if ($secureDomain) {
$url = 'https://' . $secureDomain . $_SERVER['REQUEST_URI'];
} else {
$url = $_SERVER['REQUEST_URI'];
if (!$matched) {
return false;
}
}

$destURL = str_replace('http:', 'https:', Director::absoluteURL($url));

// This coupling to SapphireTest is necessary to test the destination URL and to not interfere with tests
if (class_exists('SilverStripe\\Dev\\SapphireTest', false) && SapphireTest::is_running_test()) {
return $destURL;
} else {
self::force_redirect($destURL);
return true;
}
} else {
return false;
// if an domain is specified, redirect to that instead of the current domain
if (!$secureDomain) {
$secureDomain = static::host();
}
$url = 'https://' . $secureDomain . $_SERVER['REQUEST_URI'];

// Force redirect
self::force_redirect($url);
return true;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/Control/Email/Email.php
Expand Up @@ -263,7 +263,7 @@ public function getSwiftMessage()
public function setSwiftMessage($swiftMessage)
{
$swiftMessage->setDate(DBDatetime::now()->getTimestamp());
if (!$swiftMessage->getFrom() && ($defaultFrom = $this->config()->admin_email)) {
if (!$swiftMessage->getFrom() && ($defaultFrom = $this->config()->get('admin_email'))) {
$swiftMessage->setFrom($defaultFrom);
}
$this->swiftMessage = $swiftMessage;
Expand Down Expand Up @@ -304,7 +304,7 @@ public function addFrom($address, $name = null)
}

/**
* @return array
* @return string
*/
public function getSender()
{
Expand Down
13 changes: 12 additions & 1 deletion src/Dev/DevelopmentAdmin.php
Expand Up @@ -42,6 +42,16 @@ class DevelopmentAdmin extends Controller
'generatesecuretoken',
);

/**
* Assume that CLI equals admin permissions
* If set to false, normal permission model will apply even in CLI mode
* Applies to all development admin tasks (E.g. TaskRunner, DatabaseAdmin)
*
* @config
* @var bool
*/
private static $allow_all_cli = true;

protected function init()
{
parent::init();
Expand All @@ -52,10 +62,11 @@ protected function init()

// We allow access to this controller regardless of live-status or ADMIN permission only
// if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
$allowAllCLI = static::config()->get('allow_all_cli');
$canAccess = (
$requestedDevBuild
|| Director::isDev()
|| Director::is_cli()
|| (Director::is_cli() && $allowAllCLI)
// Its important that we don't run this check if dev/build was requested
|| Permission::check("ADMIN")
);
Expand Down
6 changes: 2 additions & 4 deletions src/Dev/SapphireTest.php
Expand Up @@ -33,12 +33,10 @@
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\SS_List;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\Security;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\Requirements;
use SilverStripe\View\SSViewer;
use SilverStripe\View\ThemeManifest;
Expand Down Expand Up @@ -183,12 +181,12 @@ class SapphireTest extends PHPUnit_Framework_TestCase
*
* @return boolean
*/
public static function is_running_test()
protected static function is_running_test()
{
return self::$is_running_test;
}

public static function set_is_running_test($bool)
protected static function set_is_running_test($bool)
{
self::$is_running_test = $bool;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Dev/TaskRunner.php
Expand Up @@ -29,12 +29,12 @@ protected function init()
{
parent::init();

$isRunningTests = (class_exists('SilverStripe\\Dev\\SapphireTest', false) && SapphireTest::is_running_test());
$allowAllCLI = DevelopmentAdmin::config()->get('allow_all_cli');
$canAccess = (
Director::isDev()
// We need to ensure that DevelopmentAdminTest can simulate permission failures when running
// "dev/tasks" from CLI.
|| (Director::is_cli() && !$isRunningTests)
|| (Director::is_cli() && $allowAllCLI)
|| Permission::check("ADMIN")
);
if (!$canAccess) {
Expand Down
1 change: 0 additions & 1 deletion src/Forms/GridField/GridField_FormAction.php
Expand Up @@ -3,7 +3,6 @@
namespace SilverStripe\Forms\GridField;

use SilverStripe\Control\Controller;
use SilverStripe\Control\Session;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;

Expand Down
20 changes: 3 additions & 17 deletions src/ORM/DataObject.php
Expand Up @@ -528,7 +528,7 @@ public function newClassInstance($newClassName)
$originalClass = $this->ClassName;

/** @var DataObject $newInstance */
$newInstance = Injector::inst()->create($newClassName, $this->record, false, $this->model);
$newInstance = Injector::inst()->create($newClassName, $this->record, false);

// Modify ClassName
if ($newClassName != $originalClass) {
Expand Down Expand Up @@ -1526,7 +1526,7 @@ public function getComponent($componentName)
}

if (empty($component)) {
$component = $this->model->$class->newObject();
$component = Injector::inst()->create($class);
if ($polymorphic) {
$component->{$joinField.'ID'} = $this->ID;
$component->{$joinField.'Class'} = static::class;
Expand Down Expand Up @@ -1582,10 +1582,6 @@ public function getComponents($componentName)
$result = HasManyList::create($componentClass, $joinField);
}

if ($this->model) {
$result->setDataModel($this->model);
}

return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
Expand Down Expand Up @@ -1707,9 +1703,6 @@ public function inferReciprocalComponent($remoteClass, $remoteRelation)
$joinField = "{$remoteRelation}ID";
$componentClass = $schema->classForField($remoteClass, $joinField);
$result = HasManyList::create($componentClass, $joinField);
if ($this->model) {
$result->setDataModel($this->model);
}
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($this->ID);
Expand Down Expand Up @@ -1753,9 +1746,6 @@ public function inferReciprocalComponent($remoteClass, $remoteRelation)
$manyMany['childField'], // Reversed parent / child field
$extraFields
);
if ($this->model) {
$result->setDataModel($this->model);
}
$this->extend('updateManyManyComponents', $result);

// If this is called on a singleton, then we return an 'orphaned relation' that can have the
Expand Down Expand Up @@ -1814,10 +1804,6 @@ public function getManyManyComponents($componentName)
$query->setQueryParam('Component.ExtraFields', $extraFields);
});

if ($this->model) {
$result->setDataModel($this->model);
}

$this->extend('updateManyManyComponents', $result);

// If this is called on a singleton, then we return an 'orphaned relation' that can have the
Expand Down Expand Up @@ -3126,7 +3112,7 @@ public function requireDefaultRecords()
if (!$hasData) {
$className = static::class;
foreach ($defaultRecords as $record) {
$obj = $this->model->$className->newObject($record);
$obj = Injector::inst()->create($className, $record);
$obj->write();
}
DB::alteration_message("Added default records to $className table", "created");
Expand Down
14 changes: 5 additions & 9 deletions src/ORM/DatabaseAdmin.php
Expand Up @@ -6,16 +6,13 @@
use SilverStripe\Control\Controller;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Dev\DevelopmentAdmin;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Versioned\Versioned;
use SilverStripe\Security\Security;
use SilverStripe\Security\Permission;

// Include the DB class
require_once("DB.php");

/**
* DatabaseAdmin class
*
Expand Down Expand Up @@ -58,13 +55,13 @@ protected function init()
// if on CLI or with the database not ready. The latter makes it less errorprone to do an
// initial schema build without requiring a default-admin login.
// Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
$isRunningTests = (class_exists('SilverStripe\\Dev\\SapphireTest', false) && SapphireTest::is_running_test());
$allowAllCLI = DevelopmentAdmin::config()->get('allow_all_cli');
$canAccess = (
Director::isDev()
|| !Security::database_is_ready()
// We need to ensure that DevelopmentAdminTest can simulate permission failures when running
// "dev/tests" from CLI.
|| (Director::is_cli() && !$isRunningTests)
|| (Director::is_cli() && $allowAllCLI)
|| Permission::check("ADMIN")
);
if (!$canAccess) {
Expand All @@ -87,14 +84,14 @@ public function groupedDataClasses()
$allClasses = get_declared_classes();
$rootClasses = [];
foreach ($allClasses as $class) {
if (get_parent_class($class) == 'SilverStripe\ORM\DataObject') {
if (get_parent_class($class) == DataObject::class) {
$rootClasses[$class] = array();
}
}

// Assign every other data object one of those
foreach ($allClasses as $class) {
if (!isset($rootClasses[$class]) && is_subclass_of($class, 'SilverStripe\ORM\DataObject')) {
if (!isset($rootClasses[$class]) && is_subclass_of($class, DataObject::class)) {
foreach ($rootClasses as $rootClass => $dummy) {
if (is_subclass_of($class, $rootClass)) {
$rootClasses[$rootClass][] = $class;
Expand Down Expand Up @@ -260,7 +257,6 @@ public function doBuild($quiet = false, $populate = true, $testMode = false)
// Initiate schema update
$dbSchema = DB::get_schema();
$dbSchema->schemaUpdate(function () use ($dataClasses, $testMode, $quiet) {
/** @var SilverStripe\ORM\DataObjectSchema $dataObjectSchema */
$dataObjectSchema = DataObject::getSchema();

foreach ($dataClasses as $dataClass) {
Expand Down

0 comments on commit 001d559

Please sign in to comment.