Skip to content

Commit

Permalink
Merge pull request #37 from open-sausages/pulls/4.0/update-styles
Browse files Browse the repository at this point in the history
Update config / code styles for 4.0
  • Loading branch information
dhensby authored Nov 23, 2017
2 parents acaaf95 + 24cf40b commit 978a5a1
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 83 deletions.
18 changes: 12 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
language: php

dist: precise
dist: trusty

sudo: false
cache:
directories:
- $HOME/.composer/cache/files

php:
- 5.6
- 7.0
- 7.1

env:
- DB=SQLITE CORE_RELEASE=4 PDO=1
global:
- DB=SQLITE
- PDO=1

matrix:
fast_finish: true
include:
- php: 5.6
env: DB=SQLITE CORE_RELEASE=4 PDO=0
env: PDO=0 PHPCS_TEST=1

before_script:
# Init PHP
- printf "\n" | pecl install imagick
- phpenv rehash
- phpenv config-rm xdebug.ini
- export PATH=~/.composer/vendor/bin:$PATH
- echo 'memory_limit = 2048M' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini

# Install composer dependencies
- composer validate
- composer require symfony/config:^3.2 silverstripe/framework:4.0.x-dev silverstripe/cms:4.0.x-dev silverstripe/siteconfig:4.0.x-dev silverstripe/config:1.0.x-dev silverstripe/admin:1.0.x-dev silverstripe/assets:1.0.x-dev silverstripe/versioned:1.0.x-dev --no-update
- composer require --no-update silverstripe/recipe-cms:1.0.x-dev
- composer install --prefer-dist --no-interaction --no-progress --no-suggest --optimize-autoloader --verbose --profile
- if [[ $PHPCS_TEST ]]; then composer global require squizlabs/php_codesniffer:^3 --prefer-dist --no-interaction --no-progress --no-suggest -o; fi

script:
- vendor/bin/phpunit vendor/silverstripe/framework/tests
- if [[ $PHPCS_TEST ]]; then composer run-script lint; fi
29 changes: 20 additions & 9 deletions _configure_database.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
<?php

// Script called from ConfigureFromEnv.php
global $databaseConfig;
if(strpos($databaseConfig['type'], 'SQLite') === 0) {
// Called from DatabaseAdapterRegistry::autoconfigure($config)
use SilverStripe\Core\Environment;
use SilverStripe\SQLite\SQLite3Database;

if(defined('SS_SQLITE_DATABASE_PATH')) {
$databaseConfig['path'] = SS_SQLITE_DATABASE_PATH;
}
if (!isset($databaseConfig)) {
global $databaseConfig;
}

// Get path
$path = Environment::getEnv(SQLite3Database::ENV_PATH);
if ($path) {
$databaseConfig['path'] = $path;
} elseif (defined(SQLite3Database::ENV_PATH)) {
$databaseConfig['path'] = constant(SQLite3Database::ENV_PATH);
}

if(defined('SS_SQLITE_DATABASE_KEY')) {
$databaseConfig['key'] = SS_SQLITE_DATABASE_KEY;
}
// Get key
$key = Environment::getEnv(SQLite3Database::ENV_KEY);
if ($key) {
$databaseConfig['key'] = $key;
} elseif (defined(SQLite3Database::ENV_KEY)) {
$databaseConfig['key'] = constant(SQLite3Database::ENV_KEY);
}
60 changes: 30 additions & 30 deletions _register_database.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,51 @@
use SilverStripe\SQLite\SQLiteDatabaseConfigurationHelper;

$sqliteDatabaseAdapterRegistryFields = array(
'path' => array(
'title' => 'Directory path<br /><small>Absolute path to directory, writeable by the webserver user.<br />'
. 'Recommended to be outside of your webroot</small>',
'default' => dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . '.sqlitedb'
),
'database' => array(
'title' => 'Database filename (extension .sqlite)',
'default' => 'database.sqlite'
)
'path' => array(
'title' => 'Directory path<br /><small>Absolute path to directory, writeable by the webserver user.<br />'
. 'Recommended to be outside of your webroot</small>',
'default' => dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . '.sqlitedb'
),
'database' => array(
'title' => 'Database filename (extension .sqlite)',
'default' => 'database.sqlite'
)
);

// Basic SQLLite3 Database
/** @skipUpgrade */
DatabaseAdapterRegistry::register(
array(
'class' => 'SQLite3Database',
array(
'class' => 'SQLite3Database',
'module' => 'sqlite3',
'title' => 'SQLite 3.3+ (using SQLite3)',
'helperPath' => __DIR__.'/code/SQLiteDatabaseConfigurationHelper.php',
'title' => 'SQLite 3.3+ (using SQLite3)',
'helperPath' => __DIR__.'/code/SQLiteDatabaseConfigurationHelper.php',
'helperClass' => SQLiteDatabaseConfigurationHelper::class,
'supported' => class_exists('SQLite3'),
'missingExtensionText' => 'The <a href="http://php.net/manual/en/book.sqlite3.php">SQLite3</a>
'supported' => class_exists('SQLite3'),
'missingExtensionText' => 'The <a href="http://php.net/manual/en/book.sqlite3.php">SQLite3</a>
PHP Extension is not available. Please install or enable it of them and refresh this page.',
'fields' => array_merge($sqliteDatabaseAdapterRegistryFields, array('key' => array(
'title' => 'Encryption key<br><small>This function is experimental and requires configuration of an '
. 'encryption module</small>',
'default' => ''
)))
)
'fields' => array_merge($sqliteDatabaseAdapterRegistryFields, array('key' => array(
'title' => 'Encryption key<br><small>This function is experimental and requires configuration of an '
. 'encryption module</small>',
'default' => ''
)))
)
);

// PDO database
/** @skipUpgrade */
DatabaseAdapterRegistry::register(
array(
'class' => 'SQLite3PDODatabase',
array(
'class' => 'SQLite3PDODatabase',
'module' => 'sqlite3',
'title' => 'SQLite 3.3+ (using PDO)',
'helperPath' => __DIR__.'/code/SQLiteDatabaseConfigurationHelper.php',
'title' => 'SQLite 3.3+ (using PDO)',
'helperPath' => __DIR__.'/code/SQLiteDatabaseConfigurationHelper.php',
'helperClass' => SQLiteDatabaseConfigurationHelper::class,
'supported' => (class_exists('PDO') && in_array('sqlite', PDO::getAvailableDrivers())),
'missingExtensionText' =>
'Either the <a href="http://php.net/manual/en/book.pdo.php">PDO Extension</a> or the
'supported' => (class_exists('PDO') && in_array('sqlite', PDO::getAvailableDrivers())),
'missingExtensionText' =>
'Either the <a href="http://php.net/manual/en/book.pdo.php">PDO Extension</a> or the
<a href="http://php.net/manual/en/book.sqlite3.php">SQLite3 PDO Driver</a>
are unavailable. Please install or enable these and refresh this page.',
'fields' => $sqliteDatabaseAdapterRegistryFields
)
'fields' => $sqliteDatabaseAdapterRegistryFields
)
);
4 changes: 2 additions & 2 deletions code/SQLite3Connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function parsePreparedParameters($parameters)
case 'array':
case 'unknown type':
default:
user_error("Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)", E_USER_ERROR);
$this->databaseError("Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)");
break;
}
$values[] = array(
Expand Down Expand Up @@ -176,7 +176,7 @@ public function escapeString($value)
public function selectDatabase($name)
{
if ($name !== $this->databaseName) {
user_error("SQLite3Connector can't change databases. Please create a new database connection", E_USER_ERROR);
$this->databaseError("SQLite3Connector can't change databases. Please create a new database connection");
}
return true;
}
Expand Down
53 changes: 42 additions & 11 deletions code/SQLite3Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ class SQLite3Database extends Database
{
use Configurable;

/**
* Global environment config for setting 'path'
*/
const ENV_PATH = 'SS_SQLITE_DATABASE_PATH';

/**
* Global environment config for setting 'key'
*/
const ENV_KEY = 'SS_SQLITE_DATABASE_KEY';

/**
* Extension added to every database name
*
Expand Down Expand Up @@ -178,7 +188,8 @@ public function getLivesInMemory()
*
* @return string|null
*/
public function getPath() {
public function getPath()
{
if ($this->getLivesInMemory()) {
return null;
}
Expand Down Expand Up @@ -278,14 +289,22 @@ public function random()
* @param bool $invertedMatch
* @return PaginatedList DataObjectSet of result pages
*/
public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $sortBy = "Relevance DESC",
$extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false
public function searchEngine(
$classesToSearch,
$keywords,
$start,
$pageLength,
$sortBy = "Relevance DESC",
$extraFilter = "",
$booleanSearch = false,
$alternativeFileFilter = "",
$invertedMatch = false
) {
$keywords = $this->escapeString(str_replace(array('*', '+', '-', '"', '\''), '', $keywords));
$htmlEntityKeywords = htmlentities(utf8_decode($keywords));

$pageClass = 'SilverStripe\\CMS\\Model\\SiteTree';
$fileClass = 'SilverStripe\\Assets\\File';
$fileClass = 'SilverStripe\\Assets\\File';

$extraFilters = array($pageClass => '', $fileClass => '');

Expand All @@ -311,17 +330,24 @@ public function searchEngine($classesToSearch, $keywords, $start, $pageLength, $

$notMatch = $invertedMatch ? "NOT " : "";
if ($keywords) {
$match[$pageClass] = "
(Title LIKE '%$keywords%' OR MenuTitle LIKE '%$keywords%' OR Content LIKE '%$keywords%' OR MetaDescription LIKE '%$keywords%' OR
Title LIKE '%$htmlEntityKeywords%' OR MenuTitle LIKE '%$htmlEntityKeywords%' OR Content LIKE '%$htmlEntityKeywords%' OR MetaDescription LIKE '%$htmlEntityKeywords%')
";
$match[$pageClass] =
"(Title LIKE '%$keywords%' OR MenuTitle LIKE '%$keywords%' OR Content LIKE '%$keywords%'"
. " OR MetaDescription LIKE '%$keywords%' OR Title LIKE '%$htmlEntityKeywords%'"
. " OR MenuTitle LIKE '%$htmlEntityKeywords%' OR Content LIKE '%$htmlEntityKeywords%'"
. " OR MetaDescription LIKE '%$htmlEntityKeywords%')";
$fileClassSQL = Convert::raw2sql($fileClass);
$match[$fileClass] = "(Name LIKE '%$keywords%' OR Title LIKE '%$keywords%') AND ClassName = '$fileClassSQL'";
$match[$fileClass] =
"(Name LIKE '%$keywords%' OR Title LIKE '%$keywords%') AND ClassName = '$fileClassSQL'";

// We make the relevance search by converting a boolean mode search into a normal one
$relevanceKeywords = $keywords;
$htmlEntityRelevanceKeywords = $htmlEntityKeywords;
$relevance[$pageClass] = "(Title LIKE '%$relevanceKeywords%' OR MenuTitle LIKE '%$relevanceKeywords%' OR Content LIKE '%$relevanceKeywords%' OR MetaDescription LIKE '%$relevanceKeywords%') + (Title LIKE '%$htmlEntityRelevanceKeywords%' OR MenuTitle LIKE '%$htmlEntityRelevanceKeywords%' OR Content LIKE '%$htmlEntityRelevanceKeywords%' OR MetaDescription LIKE '%$htmlEntityRelevanceKeywords%')";
$relevance[$pageClass] =
"(Title LIKE '%$relevanceKeywords%' OR MenuTitle LIKE '%$relevanceKeywords%'"
. " OR Content LIKE '%$relevanceKeywords%' OR MetaDescription LIKE '%$relevanceKeywords%')"
. " + (Title LIKE '%$htmlEntityRelevanceKeywords%' OR MenuTitle LIKE '%$htmlEntityRelevanceKeywords%'"
. " OR Content LIKE '%$htmlEntityRelevanceKeywords%' OR MetaDescriptio "
. " LIKE '%$htmlEntityRelevanceKeywords%')";
$relevance[$fileClass] = "(Name LIKE '%$relevanceKeywords%' OR Title LIKE '%$relevanceKeywords%')";
} else {
$relevance[$pageClass] = $relevance[$fileClass] = 1;
Expand Down Expand Up @@ -464,7 +490,12 @@ public function clearTable($table)
$this->query("DELETE FROM \"$table\"");
}

public function comparisonClause($field, $value, $exact = false, $negate = false, $caseSensitive = null,
public function comparisonClause(
$field,
$value,
$exact = false,
$negate = false,
$caseSensitive = null,
$parameterised = false
) {
if ($exact && !$caseSensitive) {
Expand Down
49 changes: 37 additions & 12 deletions code/SQLite3SchemaManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ public function databaseList()
$databases = array();
if ($files !== false) {
foreach ($files as $file) {

// Filter non-files
if (!is_file("$directory/$file")) {
continue;
Expand Down Expand Up @@ -172,8 +171,14 @@ public function createTable($table, $fields = null, $indexes = null, $options =
return $table;
}

public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null,
$alteredIndexes = null, $alteredOptions = null, $advancedOptions = null
public function alterTable(
$tableName,
$newFields = null,
$newIndexes = null,
$alteredFields = null,
$alteredIndexes = null,
$alteredOptions = null,
$advancedOptions = null
) {
if ($newFields) {
foreach ($newFields as $fieldName => $fieldSpec) {
Expand Down Expand Up @@ -310,10 +315,12 @@ public function renameField($tableName, $oldName, $newName)
}

// SQLite doesn't support direct renames through ALTER TABLE
$oldColsStr = implode(',', $oldCols);
$newColsSpecStr = implode(',', $newColsSpec);
$queries = array(
"BEGIN TRANSACTION",
"CREATE TABLE \"{$tableName}_renamefield_{$oldName}\" (" . implode(',', $newColsSpec) . ")",
"INSERT INTO \"{$tableName}_renamefield_{$oldName}\" SELECT " . implode(',', $oldCols) . " FROM \"$tableName\"",
"CREATE TABLE \"{$tableName}_renamefield_{$oldName}\" ({$newColsSpecStr})",
"INSERT INTO \"{$tableName}_renamefield_{$oldName}\" SELECT {$oldColsStr} FROM \"$tableName\"",
"DROP TABLE \"$tableName\"",
"ALTER TABLE \"{$tableName}_renamefield_{$oldName}\" RENAME TO \"$tableName\"",
"COMMIT"
Expand All @@ -329,9 +336,24 @@ public function renameField($tableName, $oldName, $newName)

// Recreate the indexes
foreach ($oldIndexList as $indexName => $indexSpec) {
// Rename columns to new columns
$indexSpec['value'] = preg_replace("/\"$oldName\"/i", "\"$newName\"", $indexSpec['value']);
$this->createIndex($tableName, $indexName, $indexSpec);
// Map index columns
$columns = array_filter(array_map(function ($column) use ($newName, $oldName) {
// Unchanged
if ($column !== $oldName) {
return $column;
}
// Skip obsolete fields
if (stripos($newName, '_obsolete_') === 0) {
return null;
}
return $newName;
}, $indexSpec['columns']));

// Create index if column count unchanged
if (count($columns) === count($indexSpec['columns'])) {
$indexSpec['columns'] = $columns;
$this->createIndex($tableName, $indexName, $indexSpec);
}
}
}

Expand All @@ -344,8 +366,10 @@ public function fieldList($table)

$fieldList = array();
if ($sqlCreate && $sqlCreate['sql']) {
preg_match('/^[\s]*CREATE[\s]+TABLE[\s]+[\'"]?[a-zA-Z0-9_\\\]+[\'"]?[\s]*\((.+)\)[\s]*$/ims',
$sqlCreate['sql'], $matches
preg_match(
'/^[\s]*CREATE[\s]+TABLE[\s]+[\'"]?[a-zA-Z0-9_\\\]+[\'"]?[\s]*\((.+)\)[\s]*$/ims',
$sqlCreate['sql'],
$matches
);
$fields = isset($matches[1])
? preg_split('/,(?=(?:[^\'"]*$)|(?:[^\'"]*[\'"][^\'"]*[\'"][^\'"]*)*$)/x', $matches[1])
Expand Down Expand Up @@ -411,7 +435,6 @@ public function indexList($table)

// Enumerate each index and related fields
foreach ($this->query("PRAGMA index_list(\"$table\")") as $index) {

// The SQLite internal index name, not the actual Silverstripe name
$indexName = $index["name"];
$indexType = $index['unique'] ? 'unique' : 'index';
Expand Down Expand Up @@ -501,7 +524,9 @@ public function enum($values)

// Ensure the cache table exists
if (empty($this->enum_map)) {
$this->query("CREATE TABLE IF NOT EXISTS \"SQLiteEnums\" (\"TableColumn\" TEXT PRIMARY KEY, \"EnumList\" TEXT)");
$this->query(
"CREATE TABLE IF NOT EXISTS \"SQLiteEnums\" (\"TableColumn\" TEXT PRIMARY KEY, \"EnumList\" TEXT)"
);
}

// Ensure the table row exists
Expand Down
Loading

0 comments on commit 978a5a1

Please sign in to comment.