[TASK] Add CLI option to set DB socket for functional tests
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Tests / FunctionalTestCaseBootstrapUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Tests;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 /**
18 * Utility class to set up and bootstrap TYPO3 CMS for functional tests
19 */
20 class FunctionalTestCaseBootstrapUtility {
21
22 /**
23 * @var string Identifier calculated from test case class
24 */
25 protected $identifier;
26
27 /**
28 * @var string Absolute path to test instance document root
29 */
30 protected $instancePath;
31
32 /**
33 * @var string Name of test database
34 */
35 protected $databaseName;
36
37 /**
38 * @var string Name of original database
39 */
40 protected $originalDatabaseName;
41
42 /**
43 * @var array These extensions are always loaded
44 */
45 protected $defaultActivatedCoreExtensions = array(
46 'core',
47 'backend',
48 'frontend',
49 'cms',
50 'lang',
51 'extbase',
52 'install',
53 );
54
55 /**
56 * @var array These folder are always created
57 */
58 protected $defaultFoldersToCreate = array(
59 '',
60 '/fileadmin',
61 '/typo3temp',
62 '/typo3conf',
63 '/typo3conf/ext',
64 '/uploads'
65 );
66
67 /**
68 * Set up creates a test instance and database.
69 *
70 * @param string $testCaseClassName Name of test case class
71 * @param array $coreExtensionsToLoad Array of core extensions to load
72 * @param array $testExtensionsToLoad Array of test extensions to load
73 * @param array $pathsToLinkInTestInstance Array of source => destination path pairs to be linked
74 * @param array $configurationToUse Array of TYPO3_CONF_VARS that need to be overridden
75 * @param array $additionalFoldersToCreate Array of folder paths to be created
76 * @return string Path to TYPO3 CMS test installation for this test case
77 */
78 public function setUp(
79 $testCaseClassName,
80 array $coreExtensionsToLoad,
81 array $testExtensionsToLoad,
82 array $pathsToLinkInTestInstance,
83 array $configurationToUse,
84 array $additionalFoldersToCreate
85 ) {
86 $this->setUpIdentifier($testCaseClassName);
87 $this->setUpInstancePath();
88 if ($this->recentTestInstanceExists()) {
89 $this->setUpBasicTypo3Bootstrap();
90 $this->initializeTestDatabase();
91 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(TRUE);
92 } else {
93 $this->removeOldInstanceIfExists();
94 $this->setUpInstanceDirectories($additionalFoldersToCreate);
95 $this->setUpInstanceCoreLinks();
96 $this->linkTestExtensionsToInstance($testExtensionsToLoad);
97 $this->linkPathsInTestInstance($pathsToLinkInTestInstance);
98 $this->setUpLocalConfiguration($configurationToUse);
99 $this->setUpPackageStates($coreExtensionsToLoad, $testExtensionsToLoad);
100 $this->setUpBasicTypo3Bootstrap();
101 $this->setUpTestDatabase();
102 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(TRUE);
103 $this->createDatabaseStructure();
104 }
105
106 return $this->instancePath;
107 }
108
109 /**
110 * Checks whether the current test instance exists and is younger than
111 * some minutes.
112 *
113 * @return bool
114 */
115 protected function recentTestInstanceExists() {
116 if (@file_get_contents($this->instancePath . '/last_run.txt') <= (time() - 300)) {
117 return FALSE;
118 } else {
119 // Test instance exists and is pretty young -> re-use
120 return TRUE;
121 }
122 }
123
124 /**
125 * Calculate a "unique" identifier for the test database and the
126 * instance patch based on the given test case class name.
127 *
128 * As a result, the database name will be identical between different
129 * test runs, but different between each test case.
130 */
131 protected function setUpIdentifier($testCaseClassName) {
132 // 7 characters of sha1 should be enough for a unique identification
133 $this->identifier = substr(sha1($testCaseClassName), 0, 7);
134 }
135
136 /**
137 * Calculates path to TYPO3 CMS test installation for this test case.
138 *
139 * @return void
140 */
141 protected function setUpInstancePath() {
142 $this->instancePath = ORIGINAL_ROOT . 'typo3temp/functional-' . $this->identifier;
143 }
144
145 /**
146 * Remove test instance folder structure in setUp() if it exists.
147 * This may happen if a functional test before threw a fatal.
148 *
149 * @return void
150 */
151 protected function removeOldInstanceIfExists() {
152 if (is_dir($this->instancePath)) {
153 $this->removeInstance();
154 }
155 }
156
157 /**
158 * Create folder structure of test instance.
159 *
160 * @param array $additionalFoldersToCreate Array of additional folders to be created
161 * @throws Exception
162 * @return void
163 */
164 protected function setUpInstanceDirectories(array $additionalFoldersToCreate = array()) {
165 $foldersToCreate = array_merge($this->defaultFoldersToCreate, $additionalFoldersToCreate);
166 foreach ($foldersToCreate as $folder) {
167 $success = mkdir($this->instancePath . $folder);
168 if (!$success) {
169 throw new Exception(
170 'Creating directory failed: ' . $this->instancePath . $folder,
171 1376657189
172 );
173 }
174 }
175
176 // Store the time we created this directory
177 file_put_contents($this->instancePath . '/last_run.txt', time());
178 }
179
180 /**
181 * Link TYPO3 CMS core from "parent" instance.
182 *
183 * @throws Exception
184 * @return void
185 */
186 protected function setUpInstanceCoreLinks() {
187 $linksToSet = array(
188 ORIGINAL_ROOT . 'typo3' => $this->instancePath . '/typo3',
189 ORIGINAL_ROOT . 'index.php' => $this->instancePath . '/index.php'
190 );
191 foreach ($linksToSet as $from => $to) {
192 $success = symlink($from, $to);
193 if (!$success) {
194 throw new Exception(
195 'Creating link failed: from ' . $from . ' to: ' . $to,
196 1376657199
197 );
198 }
199 }
200 }
201
202 /**
203 * Link test extensions to the typo3conf/ext folder of the instance.
204 *
205 * @param array $extensionPaths Contains paths to extensions relative to document root
206 * @throws Exception
207 * @return void
208 */
209 protected function linkTestExtensionsToInstance(array $extensionPaths) {
210 foreach ($extensionPaths as $extensionPath) {
211 $absoluteExtensionPath = ORIGINAL_ROOT . $extensionPath;
212 if (!is_dir($absoluteExtensionPath)) {
213 throw new Exception(
214 'Test extension path ' . $absoluteExtensionPath . ' not found',
215 1376745645
216 );
217 }
218 $destinationPath = $this->instancePath . '/typo3conf/ext/' . basename($absoluteExtensionPath);
219 $success = symlink($absoluteExtensionPath, $destinationPath);
220 if (!$success) {
221 throw new Exception(
222 'Can not link extension folder: ' . $absoluteExtensionPath . ' to ' . $destinationPath,
223 1376657142
224 );
225 }
226 }
227 }
228
229 /**
230 * Link paths inside the test instance, e.g. from a fixture fileadmin subfolder to the
231 * test instance fileadmin folder
232 *
233 * @param array $pathsToLinkInTestInstance Contains paths as array of source => destination in key => value pairs of folders relative to test instance root
234 * @throws \TYPO3\CMS\Core\Tests\Exception if a source path could not be found
235 * @throws \TYPO3\CMS\Core\Tests\Exception on failing creating the symlink
236 * @return void
237 * @see \TYPO3\CMS\Core\Tests\FunctionalTestCase::$pathsToLinkInTestInstance
238 */
239 protected function linkPathsInTestInstance(array $pathsToLinkInTestInstance) {
240 foreach ($pathsToLinkInTestInstance as $sourcePathToLinkInTestInstance => $destinationPathToLinkInTestInstance) {
241 $sourcePath = $this->instancePath . '/' . ltrim($sourcePathToLinkInTestInstance, '/');
242 if (!file_exists($sourcePath)) {
243 throw new Exception(
244 'Path ' . $sourcePath . ' not found',
245 1376745645
246 );
247 }
248 $destinationPath = $this->instancePath . '/' . ltrim($destinationPathToLinkInTestInstance, '/');
249 $success = symlink($sourcePath, $destinationPath);
250 if (!$success) {
251 throw new Exception(
252 'Can not link the path ' . $sourcePath . ' to ' . $destinationPath,
253 1389969623
254 );
255 }
256 }
257 }
258
259 /**
260 * Create LocalConfiguration.php file in the test instance
261 *
262 * @param array $configurationToMerge
263 * @throws Exception
264 * @return void
265 */
266 protected function setUpLocalConfiguration(array $configurationToMerge) {
267 $databaseName = getenv('typo3DatabaseName');
268 $databaseHost = getenv('typo3DatabaseHost');
269 $databaseUsername = getenv('typo3DatabaseUsername');
270 $databasePassword = getenv('typo3DatabasePassword');
271 $databasePort = getenv('typo3DatabasePort');
272 $databaseSocket = getenv('typo3DatabaseSocket');
273 if ($databaseName || $databaseHost || $databaseUsername || $databasePassword || $databasePort || $databaseSocket) {
274 // Try to get database credentials from environment variables first
275 $originalConfigurationArray = array(
276 'DB' => array(),
277 );
278 if ($databaseName) {
279 $originalConfigurationArray['DB']['database'] = $databaseName;
280 }
281 if ($databaseHost) {
282 $originalConfigurationArray['DB']['host'] = $databaseHost;
283 }
284 if ($databaseUsername) {
285 $originalConfigurationArray['DB']['username'] = $databaseUsername;
286 }
287 if ($databasePassword) {
288 $originalConfigurationArray['DB']['password'] = $databasePassword;
289 }
290 if ($databasePort) {
291 $originalConfigurationArray['DB']['port'] = $databasePort;
292 }
293 if ($databaseSocket) {
294 $originalConfigurationArray['DB']['socket'] = $databaseSocket;
295 }
296 } elseif (file_exists(ORIGINAL_ROOT . 'typo3conf/LocalConfiguration.php')) {
297 // See if a LocalConfiguration file exists in "parent" instance to get db credentials from
298 $originalConfigurationArray = require ORIGINAL_ROOT . 'typo3conf/LocalConfiguration.php';
299 } else {
300 throw new Exception(
301 'Database credentials for functional tests are neither set through environment'
302 . ' variables, and can not be found in an existing LocalConfiguration file',
303 1397406356
304 );
305 }
306
307 // Base of final LocalConfiguration is core factory configuration
308 $finalConfigurationArray = require ORIGINAL_ROOT . 'typo3/sysext/core/Configuration/FactoryConfiguration.php';
309
310 $this->mergeRecursiveWithOverrule($finalConfigurationArray, require ORIGINAL_ROOT . 'typo3/sysext/core/Build/Configuration/FunctionalTestsConfiguration.php');
311 $this->mergeRecursiveWithOverrule($finalConfigurationArray, $configurationToMerge);
312 $finalConfigurationArray['DB'] = $originalConfigurationArray['DB'];
313 // Calculate and set new database name
314 $this->originalDatabaseName = $originalConfigurationArray['DB']['database'];
315 $this->databaseName = $this->originalDatabaseName . '_ft' . $this->identifier;
316
317 // Maximum database name length for mysql is 64 characters
318 if (strlen($this->databaseName) > 64) {
319 $maximumOriginalDatabaseName = 64 - strlen('_ft' . $this->identifier);
320 throw new Exception(
321 'The name of the database that is used for the functional test (' . $this->databaseName . ')' .
322 ' exceeds the maximum length of 64 character allowed by MySQL. You have to shorten your' .
323 ' original database name to ' . $maximumOriginalDatabaseName . ' characters',
324 1377600104
325 );
326 }
327
328 $finalConfigurationArray['DB']['database'] = $this->databaseName;
329
330 $result = $this->writeFile(
331 $this->instancePath . '/typo3conf/LocalConfiguration.php',
332 '<?php' . chr(10) .
333 'return ' .
334 $this->arrayExport(
335 $finalConfigurationArray
336 ) .
337 ';' . chr(10) .
338 '?>'
339 );
340 if (!$result) {
341 throw new Exception('Can not write local configuration', 1376657277);
342 }
343 }
344
345 /**
346 * Compile typo3conf/PackageStates.php containing default packages like core,
347 * a functional test specific list of additional core extensions, and a list of
348 * test extensions.
349 *
350 * @param array $coreExtensionsToLoad Additional core extensions to load
351 * @param array $testExtensionPaths Paths to extensions relative to document root
352 * @throws Exception
353 * @TODO Figure out what the intention of the upper arguments is
354 */
355 protected function setUpPackageStates(array $coreExtensionsToLoad, array $testExtensionPaths) {
356 $packageStates = array(
357 'packages' => array(),
358 'version' => 4,
359 );
360
361 // Register default list of extensions and set active
362 foreach ($this->defaultActivatedCoreExtensions as $extensionName) {
363 $packageStates['packages'][$extensionName] = array(
364 'state' => 'active',
365 'packagePath' => 'typo3/sysext/' . $extensionName . '/',
366 'classesPath' => 'Classes/',
367 );
368 }
369
370 // Register additional core extensions and set active
371 foreach ($coreExtensionsToLoad as $extensionName) {
372 if (isset($packageSates['packages'][$extensionName])) {
373 throw new Exception(
374 $extensionName . ' is already registered as default core extension to load, no need to load it explicitly',
375 1390913893
376 );
377 }
378 $packageStates['packages'][$extensionName] = array(
379 'state' => 'active',
380 'packagePath' => 'typo3/sysext/' . $extensionName . '/',
381 'classesPath' => 'Classes/',
382 );
383 }
384
385 // Activate test extensions that have been symlinked before
386 foreach ($testExtensionPaths as $extensionPath) {
387 $extensionName = basename($extensionPath);
388 if (isset($packageSates['packages'][$extensionName])) {
389 throw new Exception(
390 $extensionName . ' is already registered as extension to load, no need to load it explicitly',
391 1390913894
392 );
393 }
394 $packageStates['packages'][$extensionName] = array(
395 'state' => 'active',
396 'packagePath' => 'typo3conf/ext/' . $extensionName . '/',
397 'classesPath' => 'Classes/',
398 );
399 }
400
401 $result = $this->writeFile(
402 $this->instancePath . '/typo3conf/PackageStates.php',
403 '<?php' . chr(10) .
404 'return ' .
405 $this->arrayExport(
406 $packageStates
407 ) .
408 ';' . chr(10) .
409 '?>'
410 );
411 if (!$result) {
412 throw new Exception('Can not write PackageStates', 1381612729);
413 }
414 }
415
416 /**
417 * Bootstrap basic TYPO3
418 *
419 * @return void
420 */
421 protected function setUpBasicTypo3Bootstrap() {
422 $_SERVER['PWD'] = $this->instancePath;
423 $_SERVER['argv'][0] = 'index.php';
424
425 define('TYPO3_MODE', 'BE');
426 define('TYPO3_cliMode', TRUE);
427
428 require_once $this->instancePath . '/typo3/sysext/core/Classes/Core/CliBootstrap.php';
429 \TYPO3\CMS\Core\Core\CliBootstrap::checkEnvironmentOrDie();
430
431 require_once $this->instancePath . '/typo3/sysext/core/Classes/Core/Bootstrap.php';
432 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()
433 ->baseSetup('')
434 ->loadConfigurationAndInitialize(TRUE)
435 ->loadTypo3LoadedExtAndExtLocalconf(TRUE)
436 ->applyAdditionalConfigurationSettings();
437 }
438
439 /**
440 * Populate $GLOBALS['TYPO3_DB'] and create test database
441 *
442 * @throws \TYPO3\CMS\Core\Tests\Exception
443 * @return void
444 */
445 protected function setUpTestDatabase() {
446 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->initializeTypo3DbGlobal();
447 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
448 $database = $GLOBALS['TYPO3_DB'];
449 if(!$database->sql_pconnect()) {
450 throw new Exception(
451 'TYPO3 Fatal Error: The current username, password or host was not accepted when the'
452 . ' connection to the database was attempted to be established!',
453 1377620117
454 );
455 }
456
457 // Drop database in case a previous test had a fatal and did not clean up properly
458 $database->admin_query('DROP DATABASE IF EXISTS `' . $this->databaseName . '`');
459 $createDatabaseResult = $database->admin_query('CREATE DATABASE `' . $this->databaseName . '`');
460 if (!$createDatabaseResult) {
461 $user = $GLOBALS['TYPO3_CONF_VARS']['DB']['username'];
462 $host = $GLOBALS['TYPO3_CONF_VARS']['DB']['host'];
463 throw new Exception(
464 'Unable to create database with name ' . $this->databaseName . '. This is probably a permission problem.'
465 . ' For this instance this could be fixed executing'
466 . ' "GRANT ALL ON `' . $this->originalDatabaseName . '_ft%`.* TO `' . $user . '`@`' . $host . '`;"',
467 1376579070
468 );
469 }
470 $database->setDatabaseName($this->databaseName);
471 $database->sql_select_db($this->databaseName);
472 }
473
474 /**
475 * Populate $GLOBALS['TYPO3_DB'] reusing an existing database with
476 * all tables truncated.
477 *
478 * @throws \TYPO3\CMS\Core\Tests\Exception
479 * @return void
480 */
481 protected function initializeTestDatabase() {
482 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->initializeTypo3DbGlobal();
483 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
484 $database = $GLOBALS['TYPO3_DB'];
485 if (!$database->sql_pconnect()) {
486 throw new Exception(
487 'TYPO3 Fatal Error: The current username, password or host was not accepted when the'
488 . ' connection to the database was attempted to be established!',
489 1377620117
490 );
491 }
492 $this->databaseName = $GLOBALS['TYPO3_CONF_VARS']['DB']['database'];
493 $database->setDatabaseName($this->databaseName);
494 $database->sql_select_db($this->databaseName);
495 foreach ($database->admin_get_tables() as $table) {
496 $database->admin_query('TRUNCATE ' . $table['Name'] . ';');
497 }
498 }
499
500 /**
501 * Create tables and import static rows
502 *
503 * @return void
504 */
505 protected function createDatabaseStructure() {
506 /** @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService $schemaMigrationService */
507 $schemaMigrationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Install\\Service\\SqlSchemaMigrationService');
508 /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */
509 $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
510 /** @var \TYPO3\CMS\Install\Service\SqlExpectedSchemaService $expectedSchemaService */
511 $expectedSchemaService = $objectManager->get('TYPO3\\CMS\\Install\\Service\\SqlExpectedSchemaService');
512
513 // Raw concatenated ext_tables.sql and friends string
514 $expectedSchemaString = $expectedSchemaService->getTablesDefinitionString(TRUE);
515 $statements = $schemaMigrationService->getStatementArray($expectedSchemaString, TRUE);
516 list($_, $insertCount) = $schemaMigrationService->getCreateTables($statements, TRUE);
517
518 $fieldDefinitionsFile = $schemaMigrationService->getFieldDefinitions_fileContent($expectedSchemaString);
519 $fieldDefinitionsDatabase = $schemaMigrationService->getFieldDefinitions_database();
520 $difference = $schemaMigrationService->getDatabaseExtra($fieldDefinitionsFile, $fieldDefinitionsDatabase);
521 $updateStatements = $schemaMigrationService->getUpdateSuggestions($difference);
522
523 $schemaMigrationService->performUpdateQueries($updateStatements['add'], $updateStatements['add']);
524 $schemaMigrationService->performUpdateQueries($updateStatements['change'], $updateStatements['change']);
525 $schemaMigrationService->performUpdateQueries($updateStatements['create_table'], $updateStatements['create_table']);
526
527 foreach ($insertCount as $table => $count) {
528 $insertStatements = $schemaMigrationService->getTableInsertStatements($statements, $table);
529 foreach ($insertStatements as $insertQuery) {
530 $insertQuery = rtrim($insertQuery, ';');
531 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
532 $database = $GLOBALS['TYPO3_DB'];
533 $database->admin_query($insertQuery);
534 }
535 }
536 }
537
538 /**
539 * Drop test database.
540 *
541 * @throws \TYPO3\CMS\Core\Tests\Exception
542 * @return void
543 */
544 protected function tearDownTestDatabase() {
545 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
546 $database = $GLOBALS['TYPO3_DB'];
547 $result = $database->admin_query('DROP DATABASE `' . $this->databaseName . '`');
548 if (!$result) {
549 throw new Exception(
550 'Dropping test database ' . $this->databaseName . ' failed',
551 1376583188
552 );
553 }
554 }
555
556 /**
557 * Removes instance directories and files
558 *
559 * @throws \TYPO3\CMS\Core\Tests\Exception
560 * @return void
561 */
562 protected function removeInstance() {
563 $success = $this->rmdir($this->instancePath, TRUE);
564 if (!$success) {
565 throw new Exception(
566 'Can not remove folder: ' . $this->instancePath,
567 1376657210
568 );
569 }
570 }
571
572 /**
573 * COPIED FROM GeneralUtility
574 *
575 * Wrapper function for rmdir, allowing recursive deletion of folders and files
576 *
577 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
578 * @param boolean $removeNonEmpty Allow deletion of non-empty directories
579 * @return boolean TRUE if @rmdir went well!
580 */
581 protected function rmdir($path, $removeNonEmpty = FALSE) {
582 $OK = FALSE;
583 // Remove trailing slash
584 $path = preg_replace('|/$|', '', $path);
585 if (file_exists($path)) {
586 $OK = TRUE;
587 if (!is_link($path) && is_dir($path)) {
588 if ($removeNonEmpty == TRUE && ($handle = opendir($path))) {
589 while ($OK && FALSE !== ($file = readdir($handle))) {
590 if ($file == '.' || $file == '..') {
591 continue;
592 }
593 $OK = $this->rmdir($path . '/' . $file, $removeNonEmpty);
594 }
595 closedir($handle);
596 }
597 if ($OK) {
598 $OK = @rmdir($path);
599 }
600 } else {
601 // If $path is a symlink to a folder we need rmdir() on Windows systems
602 if (!stristr(PHP_OS, 'darwin') && stristr(PHP_OS, 'win') && is_link($path) && is_dir($path . '/')) {
603 $OK = rmdir($path);
604 } else {
605 $OK = unlink($path);
606 }
607 }
608 clearstatcache();
609 } elseif (is_link($path)) {
610 $OK = unlink($path);
611 clearstatcache();
612 }
613 return $OK;
614 }
615
616 /**
617 * COPIED FROM GeneralUtility
618 *
619 * Writes $content to the file $file
620 *
621 * @param string $file Filepath to write to
622 * @param string $content Content to write
623 * @return boolean TRUE if the file was successfully opened and written to.
624 */
625 protected function writeFile($file, $content) {
626 if ($fd = fopen($file, 'wb')) {
627 $res = fwrite($fd, $content);
628 fclose($fd);
629 if ($res === FALSE) {
630 return FALSE;
631 }
632 return TRUE;
633 }
634 return FALSE;
635 }
636
637 /**
638 * COPIED FROM ArrayUtility
639 *
640 * Exports an array as string.
641 * Similar to var_export(), but representation follows the TYPO3 core CGL.
642 *
643 * See unit tests for detailed examples
644 *
645 * @param array $array Array to export
646 * @param integer $level Internal level used for recursion, do *not* set from outside!
647 * @return string String representation of array
648 * @throws \RuntimeException
649 */
650 protected function arrayExport(array $array = array(), $level = 0) {
651 $lines = 'array(' . chr(10);
652 $level++;
653 $writeKeyIndex = FALSE;
654 $expectedKeyIndex = 0;
655 foreach ($array as $key => $value) {
656 if ($key === $expectedKeyIndex) {
657 $expectedKeyIndex++;
658 } else {
659 // Found a non integer or non consecutive key, so we can break here
660 $writeKeyIndex = TRUE;
661 break;
662 }
663 }
664 foreach ($array as $key => $value) {
665 // Indention
666 $lines .= str_repeat(chr(9), $level);
667 if ($writeKeyIndex) {
668 // Numeric / string keys
669 $lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => ';
670 }
671 if (is_array($value)) {
672 if (count($value) > 0) {
673 $lines .= $this->arrayExport($value, $level);
674 } else {
675 $lines .= 'array(),' . chr(10);
676 }
677 } elseif (is_int($value) || is_float($value)) {
678 $lines .= $value . ',' . chr(10);
679 } elseif (is_null($value)) {
680 $lines .= 'NULL' . ',' . chr(10);
681 } elseif (is_bool($value)) {
682 $lines .= $value ? 'TRUE' : 'FALSE';
683 $lines .= ',' . chr(10);
684 } elseif (is_string($value)) {
685 // Quote \ to \\
686 $stringContent = str_replace('\\', '\\\\', $value);
687 // Quote ' to \'
688 $stringContent = str_replace('\'', '\\\'', $stringContent);
689 $lines .= '\'' . $stringContent . '\'' . ',' . chr(10);
690 } else {
691 throw new \RuntimeException('Objects are not supported', 1342294986);
692 }
693 }
694 $lines .= str_repeat(chr(9), ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . chr(10));
695 return $lines;
696 }
697
698 /**
699 * COPIED FROM ArrayUtility
700 *
701 * Merges two arrays recursively and "binary safe" (integer keys are
702 * overridden as well), overruling similar values in the original array
703 * with the values of the overrule array.
704 * In case of identical keys, ie. keeping the values of the overrule array.
705 *
706 * This method takes the original array by reference for speed optimization with large arrays
707 *
708 * The differences to the existing PHP function array_merge_recursive() are:
709 * * Keys of the original array can be unset via the overrule array. ($enableUnsetFeature)
710 * * Much more control over what is actually merged. ($addKeys, $includeEmptyValues)
711 * * Elements or the original array get overwritten if the same key is present in the overrule array.
712 *
713 * @param array $original Original array. It will be *modified* by this method and contains the result afterwards!
714 * @param array $overrule Overrule array, overruling the original array
715 * @param boolean $addKeys If set to FALSE, keys that are NOT found in $original will not be set. Thus only existing value can/will be overruled from overrule array.
716 * @param boolean $includeEmptyValues If set, values from $overrule will overrule if they are empty or zero.
717 * @param boolean $enableUnsetFeature If set, special values "__UNSET" can be used in the overrule array in order to unset array keys in the original array.
718 * @return void
719 */
720 protected function mergeRecursiveWithOverrule(array &$original, array $overrule, $addKeys = TRUE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
721 foreach (array_keys($overrule) as $key) {
722 if ($enableUnsetFeature && $overrule[$key] === '__UNSET') {
723 unset($original[$key]);
724 continue;
725 }
726 if (isset($original[$key]) && is_array($original[$key])) {
727 if (is_array($overrule[$key])) {
728 self::mergeRecursiveWithOverrule($original[$key], $overrule[$key], $addKeys, $includeEmptyValues, $enableUnsetFeature);
729 }
730 } elseif (
731 ($addKeys || isset($original[$key])) &&
732 ($includeEmptyValues || $overrule[$key])
733 ) {
734 $original[$key] = $overrule[$key];
735 }
736 }
737 // This line is kept for backward compatibility reasons.
738 reset($original);
739 }
740 }