From ee3b9460f352afa546bda8e78506bc25dc89423d Mon Sep 17 00:00:00 2001 From: Stefan Hagspiel Date: Sat, 13 Jul 2019 17:38:44 +0200 Subject: [PATCH] travis/CI --- .travis.yml | 61 +++ composer.json | 1 + easy-coding-standard.yml | 108 +++++ phpstan.neon | 13 + .../Configuration/Configuration.php | 4 +- .../Configuration/ConfigurationInterface.php | 3 +- .../DependencyInjection/Configuration.php | 2 +- .../DependencyInjection/DsLuceneExtension.php | 2 +- src/DsLuceneBundle/DsLuceneBundle.php | 1 - .../Index/Field/AbstractType.php | 2 +- .../Index/Field/BinaryField.php | 4 +- .../Index/Field/KeywordField.php | 4 +- src/DsLuceneBundle/Index/Field/TextField.php | 4 +- .../Index/Field/UnIndexedField.php | 2 +- .../Index/Field/UnStoredField.php | 4 +- .../Normalizer/DocumentKeyValueNormalizer.php | 8 +- .../Helper/LuceneDocumentDataExtractor.php | 5 +- .../AutoCompleteOutputChannel.php | 15 +- .../Modifier/Filter/QueryCleanTermFilter.php | 12 +- .../OutputChannel/SearchOutputChannel.php | 13 +- .../SuggestionsOutputChannel.php | 11 +- .../Provider/LuceneIndexProvider.php | 27 +- src/DsLuceneBundle/Service/LuceneHandler.php | 13 +- .../Service/LuceneHandlerInterface.php | 4 +- .../Service/LuceneStorageBuilder.php | 5 +- tests/_bootstrap.php | 19 + tests/_data/.gitkeep | 0 tests/_envs/local.yml | 0 tests/_envs/travis.yml | 1 + tests/_etc/bundle_configuration | 20 + tests/_etc/config/bundle/appKernel | 14 + .../config/bundle/extensions.template.php | 7 + .../config/bundle/symfony/config_default.yml | 0 tests/_etc/config/bundle/system.template.php | 172 +++++++ .../template/controller/DefaultController | 19 + .../_etc/config/bundle/template/views/default | 21 + tests/_etc/config/system/config.yml | 18 + tests/_etc/config/system/php.ini | 8 + tests/_etc/scripts/codeception | 12 + tests/_etc/scripts/ecs | 6 + tests/_etc/scripts/phpstan | 7 + tests/_etc/travis/install | 91 ++++ tests/_etc/travis/script | 6 + tests/_phpstan-bootstrap.php | 6 + tests/_support/App/TestAppKernel.php | 62 +++ .../MakeServicesPublicPass.php | 30 ++ .../MonologChannelLoggerPass.php | 27 ++ tests/_support/FunctionalTester.php | 13 + tests/_support/Helper/Browser/PhpBrowser.php | 207 +++++++++ tests/_support/Helper/PimcoreBackend.php | 436 ++++++++++++++++++ tests/_support/Helper/PimcoreBundleCore.php | 68 +++ tests/_support/Helper/PimcoreCore.php | 166 +++++++ tests/_support/Helper/PimcoreUser.php | 125 +++++ tests/_support/Helper/Unit.php | 16 + tests/_support/Test/DachcomBundleTestCase.php | 37 ++ tests/_support/UnitTester.php | 13 + tests/_support/Util/Autoloader.php | 28 ++ tests/_support/Util/FileGeneratorHelper.php | 76 +++ tests/_support/Util/SearchHelper.php | 33 ++ tests/_support/Util/VersionHelper.php | 64 +++ tests/_support/_boot/kernelBuilder.php | 19 + tests/functional.suite.dist.yml | 12 + tests/functional/_bootstrap.php | 2 + tests/unit.suite.dist.yml | 8 + tests/unit/_bootstrap.php | 2 + 65 files changed, 2124 insertions(+), 75 deletions(-) create mode 100644 .travis.yml create mode 100644 easy-coding-standard.yml create mode 100644 phpstan.neon create mode 100644 tests/_bootstrap.php create mode 100644 tests/_data/.gitkeep create mode 100644 tests/_envs/local.yml create mode 100644 tests/_envs/travis.yml create mode 100755 tests/_etc/bundle_configuration create mode 100644 tests/_etc/config/bundle/appKernel create mode 100644 tests/_etc/config/bundle/extensions.template.php create mode 100755 tests/_etc/config/bundle/symfony/config_default.yml create mode 100755 tests/_etc/config/bundle/system.template.php create mode 100644 tests/_etc/config/bundle/template/controller/DefaultController create mode 100644 tests/_etc/config/bundle/template/views/default create mode 100755 tests/_etc/config/system/config.yml create mode 100755 tests/_etc/config/system/php.ini create mode 100755 tests/_etc/scripts/codeception create mode 100755 tests/_etc/scripts/ecs create mode 100755 tests/_etc/scripts/phpstan create mode 100755 tests/_etc/travis/install create mode 100755 tests/_etc/travis/script create mode 100644 tests/_phpstan-bootstrap.php create mode 100644 tests/_support/App/TestAppKernel.php create mode 100644 tests/_support/DependencyInjection/MakeServicesPublicPass.php create mode 100644 tests/_support/DependencyInjection/MonologChannelLoggerPass.php create mode 100644 tests/_support/FunctionalTester.php create mode 100644 tests/_support/Helper/Browser/PhpBrowser.php create mode 100644 tests/_support/Helper/PimcoreBackend.php create mode 100644 tests/_support/Helper/PimcoreBundleCore.php create mode 100644 tests/_support/Helper/PimcoreCore.php create mode 100644 tests/_support/Helper/PimcoreUser.php create mode 100644 tests/_support/Helper/Unit.php create mode 100644 tests/_support/Test/DachcomBundleTestCase.php create mode 100644 tests/_support/UnitTester.php create mode 100644 tests/_support/Util/Autoloader.php create mode 100644 tests/_support/Util/FileGeneratorHelper.php create mode 100644 tests/_support/Util/SearchHelper.php create mode 100644 tests/_support/Util/VersionHelper.php create mode 100644 tests/_support/_boot/kernelBuilder.php create mode 100644 tests/functional.suite.dist.yml create mode 100644 tests/functional/_bootstrap.php create mode 100644 tests/unit.suite.dist.yml create mode 100644 tests/unit/_bootstrap.php diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..323fb47 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,61 @@ +sudo: true +language: php +addons: + mariadb: '10.2' +services: + - mysql +env: + global: + - PIMCORE_ENVIRONMENT=test + - DACHCOM_BUNDLE_TEST=1 + - PIMCORE_TEST_URL=http://localhost + - PIMCORE_TEST_DB_DSN="mysql://root@localhost/dachcom_bundle_test" + - SYMFONY_DEPRECATIONS_HELPER=weak + - DACHCOM_TEST_SECTION=codeception +matrix: + include: + - name: "PHPStan Static Analysis (Pimcore 5.8.x, PHP 7.3)" + sudo: required + php: 7.3 + env: + - PIMCORE_SKELETON_BRANCH="tags/v1.3.0" + - DACHCOM_TEST_SECTION=phpstan + - name: "PHP ECS (Pimcore 5.8.x, PHP 7.3)" + sudo: required + php: 7.3 + env: + - PIMCORE_SKELETON_BRANCH="tags/v1.3.0" + - DACHCOM_TEST_SECTION=ecs + - name: "Codeception Tests ( Pimcore 5.8.x, PHP 7.2)" + sudo: required + php: 7.2 + env: + - PIMCORE_SKELETON_BRANCH="tags/v1.3.0" + - name: "Codeception Tests ( Pimcore 5.8.x, PHP 7.3)" + sudo: required + php: 7.3 + env: + - PIMCORE_SKELETON_BRANCH="tags/v1.3.0" + allow_failures: + - env: + - PIMCORE_SKELETON_BRANCH="tags/v1.3.0" + - DACHCOM_TEST_SECTION=ecs + fast_finish: true + +cache: + directories: + - $HOME/.composer/cache + +install: + - tests/_etc/travis/install + +after_failure: + - cd $TRAVIS_BUILD_DIR + - cat ./lib/DynamicSearchBundle/tests/_output/* + +script: + - _etc/travis/script + +notifications: + email: + - shagspiel@dachcom.ch \ No newline at end of file diff --git a/composer.json b/composer.json index 1de11e0..0452aef 100755 --- a/composer.json +++ b/composer.json @@ -27,6 +27,7 @@ } }, "require": { + "pimcore/pimcore": "^5.8.0", "zf1/zend-search-lucene": "~1.12" } } \ No newline at end of file diff --git a/easy-coding-standard.yml b/easy-coding-standard.yml new file mode 100644 index 0000000..26db9c0 --- /dev/null +++ b/easy-coding-standard.yml @@ -0,0 +1,108 @@ +imports: + - { resource: '%vendor_dir%/symplify/easy-coding-standard/config/psr2.yml' } + +services: + PhpCsFixer\Fixer\Basic\BracesFixer: + allow_single_line_closure: true + PhpCsFixer\Fixer\PhpTag\BlankLineAfterOpeningTagFixer: ~ + PhpCsFixer\Fixer\Operator\ConcatSpaceFixer: + spacing: one + PhpCsFixer\Fixer\Operator\NewWithBracesFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocAlignFixer: + tags: + - method + - param + - property + - return + - throws + - type + - var + PhpCsFixer\Fixer\Operator\BinaryOperatorSpacesFixer: + align_double_arrow: true + PhpCsFixer\Fixer\Operator\IncrementStyleFixer: + style: post + PhpCsFixer\Fixer\Operator\UnaryOperatorSpacesFixer: ~ + PhpCsFixer\Fixer\Whitespace\BlankLineBeforeStatementFixer: ~ + PhpCsFixer\Fixer\CastNotation\CastSpacesFixer: ~ + PhpCsFixer\Fixer\LanguageConstruct\DeclareEqualNormalizeFixer: ~ + PhpCsFixer\Fixer\FunctionNotation\FunctionTypehintSpaceFixer: ~ + PhpCsFixer\Fixer\Comment\SingleLineCommentStyleFixer: + comment_types: + - hash + PhpCsFixer\Fixer\ControlStructure\IncludeFixer: ~ + PhpCsFixer\Fixer\CastNotation\LowercaseCastFixer: ~ + PhpCsFixer\Fixer\ClassNotation\ClassAttributesSeparationFixer: + elements: + - method + PhpCsFixer\Fixer\Casing\NativeFunctionCasingFixer: ~ + PhpCsFixer\Fixer\ClassNotation\NoBlankLinesAfterClassOpeningFixer: ~ + PhpCsFixer\Fixer\Phpdoc\NoBlankLinesAfterPhpdocFixer: ~ + PhpCsFixer\Fixer\Comment\NoEmptyCommentFixer: ~ + PhpCsFixer\Fixer\Phpdoc\NoEmptyPhpdocFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocSeparationFixer: ~ + PhpCsFixer\Fixer\Semicolon\NoEmptyStatementFixer: ~ + PhpCsFixer\Fixer\Whitespace\ArrayIndentationFixer: ~ + PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer: + tokens: + - curly_brace_block + - extra + - parenthesis_brace_block + - square_brace_block + - throw + - use + PhpCsFixer\Fixer\NamespaceNotation\NoLeadingNamespaceWhitespaceFixer: ~ + PhpCsFixer\Fixer\ArrayNotation\NoMultilineWhitespaceAroundDoubleArrowFixer: ~ + PhpCsFixer\Fixer\CastNotation\NoShortBoolCastFixer: ~ + PhpCsFixer\Fixer\Semicolon\NoSinglelineWhitespaceBeforeSemicolonsFixer: ~ + PhpCsFixer\Fixer\Whitespace\NoSpacesAroundOffsetFixer: ~ + PhpCsFixer\Fixer\ControlStructure\NoTrailingCommaInListCallFixer: ~ + PhpCsFixer\Fixer\ControlStructure\NoUnneededControlParenthesesFixer: ~ + PhpCsFixer\Fixer\ArrayNotation\NoWhitespaceBeforeCommaInArrayFixer: ~ + PhpCsFixer\Fixer\Whitespace\NoWhitespaceInBlankLineFixer: ~ + PhpCsFixer\Fixer\ArrayNotation\NormalizeIndexBraceFixer: ~ + PhpCsFixer\Fixer\Operator\ObjectOperatorWithoutWhitespaceFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocAnnotationWithoutDotFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocIndentFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocInlineTagFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocNoAccessFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocNoEmptyReturnFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocNoPackageFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocNoUselessInheritdocFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocReturnSelfReferenceFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocScalarFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocSingleLineVarSpacingFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocSummaryFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocToCommentFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocTrimFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocTypesFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocVarWithoutNameFixer: ~ + PhpCsFixer\Fixer\FunctionNotation\ReturnTypeDeclarationFixer: ~ + PhpCsFixer\Fixer\ClassNotation\SelfAccessorFixer: ~ + PhpCsFixer\Fixer\CastNotation\ShortScalarCastFixer: ~ + PhpCsFixer\Fixer\StringNotation\SingleQuoteFixer: ~ + PhpCsFixer\Fixer\Semicolon\SpaceAfterSemicolonFixer: ~ + PhpCsFixer\Fixer\Operator\StandardizeNotEqualsFixer: ~ + PhpCsFixer\Fixer\Operator\TernaryOperatorSpacesFixer: ~ + PhpCsFixer\Fixer\ArrayNotation\TrimArraySpacesFixer: ~ + PhpCsFixer\Fixer\ArrayNotation\WhitespaceAfterCommaInArrayFixer: ~ + PhpCsFixer\Fixer\ClassNotation\ClassDefinitionFixer: + singleLine: true + PhpCsFixer\Fixer\Casing\MagicConstantCasingFixer: ~ + PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer: ~ + PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer: + use: echo + PhpCsFixer\Fixer\Import\NoLeadingImportSlashFixer: ~ + PhpCsFixer\Fixer\Import\NoUnusedImportsFixer: ~ + PhpCsFixer\Fixer\PhpUnit\PhpUnitFqcnAnnotationFixer: ~ + PhpCsFixer\Fixer\Phpdoc\PhpdocNoAliasTagFixer: ~ + PhpCsFixer\Fixer\ClassNotation\ProtectedToPrivateFixer: ~ + PhpCsFixer\Fixer\NamespaceNotation\SingleBlankLineBeforeNamespaceFixer: ~ + PhpCsFixer\Fixer\ClassNotation\SingleClassElementPerStatementFixer: ~ + + # new since PHP-CS-Fixer 2.6 + PhpCsFixer\Fixer\ControlStructure\NoUnneededCurlyBracesFixer: ~ + PhpCsFixer\Fixer\ClassNotation\NoUnneededFinalMethodFixer: ~ + PhpCsFixer\Fixer\Semicolon\SemicolonAfterInstructionFixer: ~ + + # new since 2.11 + PhpCsFixer\Fixer\Operator\StandardizeIncrementFixer: ~ diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..b108445 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,13 @@ +includes: + - ../../vendor/phpstan/phpstan-symfony/extension.neon +parameters: + reportUnmatchedIgnoredErrors: false + autoload_files: + - %currentWorkingDirectory%/vendor/pimcore/pimcore/stubs/compatibility-v4.php + symfony: + container_xml_path: var/cache/dev/appDevDebugProjectContainer.xml + ignoreErrors: + # There is no global constants definition file we could include, ignore it: + - '#Constant PIMCORE_[A-Z\\_]+ not found\.#' + # Symfony DI (remove this line with symfony 4.2): + - '#Call to an undefined method Symfony\\Component\\Config\\Definition\\Builder\\NodeDefinition::children\(\)\.#' diff --git a/src/DsLuceneBundle/Configuration/Configuration.php b/src/DsLuceneBundle/Configuration/Configuration.php index f7e84b3..a7b9c22 100644 --- a/src/DsLuceneBundle/Configuration/Configuration.php +++ b/src/DsLuceneBundle/Configuration/Configuration.php @@ -18,7 +18,7 @@ public function setConfig($config = []) } /** - * @param $slot + * @param string $slot * * @return mixed */ @@ -26,4 +26,4 @@ public function get($slot) { return $this->config[$slot]; } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/Configuration/ConfigurationInterface.php b/src/DsLuceneBundle/Configuration/ConfigurationInterface.php index 89bd495..66f333c 100644 --- a/src/DsLuceneBundle/Configuration/ConfigurationInterface.php +++ b/src/DsLuceneBundle/Configuration/ConfigurationInterface.php @@ -11,5 +11,4 @@ interface ConfigurationInterface const INDEX_BASE_GENESIS = self::INDEX_BASE . '/genesis'; const INDEX_BASE_STABLE = self::INDEX_BASE . '/stable'; - -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/DependencyInjection/Configuration.php b/src/DsLuceneBundle/DependencyInjection/Configuration.php index 901d675..04ff20f 100644 --- a/src/DsLuceneBundle/DependencyInjection/Configuration.php +++ b/src/DsLuceneBundle/DependencyInjection/Configuration.php @@ -14,4 +14,4 @@ public function getConfigTreeBuilder() return $treeBuilder; } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/DependencyInjection/DsLuceneExtension.php b/src/DsLuceneBundle/DependencyInjection/DsLuceneExtension.php index c82fffc..8b3099b 100644 --- a/src/DsLuceneBundle/DependencyInjection/DsLuceneExtension.php +++ b/src/DsLuceneBundle/DependencyInjection/DsLuceneExtension.php @@ -26,4 +26,4 @@ public function load(array $configs, ContainerBuilder $container) //$configManagerDefinition = $container->getDefinition(BundleConfiguration::class); //$configManagerDefinition->addMethodCall('setConfig', [$config]); } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/DsLuceneBundle.php b/src/DsLuceneBundle/DsLuceneBundle.php index ebb52f0..de9e60b 100644 --- a/src/DsLuceneBundle/DsLuceneBundle.php +++ b/src/DsLuceneBundle/DsLuceneBundle.php @@ -30,4 +30,3 @@ protected function getComposerPackageName(): string return self::PACKAGE_NAME; } } - diff --git a/src/DsLuceneBundle/Index/Field/AbstractType.php b/src/DsLuceneBundle/Index/Field/AbstractType.php index eb24b76..db10ba2 100644 --- a/src/DsLuceneBundle/Index/Field/AbstractType.php +++ b/src/DsLuceneBundle/Index/Field/AbstractType.php @@ -7,4 +7,4 @@ abstract class AbstractType implements IndexFieldInterface { const UTF8 = 'UTF-8'; -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/Index/Field/BinaryField.php b/src/DsLuceneBundle/Index/Field/BinaryField.php index 17cf417..faac421 100644 --- a/src/DsLuceneBundle/Index/Field/BinaryField.php +++ b/src/DsLuceneBundle/Index/Field/BinaryField.php @@ -5,12 +5,12 @@ final class BinaryField extends AbstractType { /** - * {@inheritDoc} + * {@inheritdoc} */ public function build(string $name, $data, array $configuration = []) { $field = \Zend_Search_Lucene_Field::binary($name, $data); - // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; + // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; return $field; } diff --git a/src/DsLuceneBundle/Index/Field/KeywordField.php b/src/DsLuceneBundle/Index/Field/KeywordField.php index 94529bd..2783794 100644 --- a/src/DsLuceneBundle/Index/Field/KeywordField.php +++ b/src/DsLuceneBundle/Index/Field/KeywordField.php @@ -5,12 +5,12 @@ final class KeywordField extends AbstractType { /** - * {@inheritDoc} + * {@inheritdoc} */ public function build(string $name, $data, array $configuration = []) { $field = \Zend_Search_Lucene_Field::keyword($name, $data, self::UTF8); - // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; + // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; return $field; } diff --git a/src/DsLuceneBundle/Index/Field/TextField.php b/src/DsLuceneBundle/Index/Field/TextField.php index de7162b..d4bcb2d 100644 --- a/src/DsLuceneBundle/Index/Field/TextField.php +++ b/src/DsLuceneBundle/Index/Field/TextField.php @@ -5,12 +5,12 @@ final class TextField extends AbstractType { /** - * {@inheritDoc} + * {@inheritdoc} */ public function build(string $name, $data, array $configuration = []) { $field = \Zend_Search_Lucene_Field::text($name, $data, self::UTF8); - // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; + // $field->boost = $type->getBoost() > 1 ? $type->getBoost() : 1.0; return $field; } diff --git a/src/DsLuceneBundle/Index/Field/UnIndexedField.php b/src/DsLuceneBundle/Index/Field/UnIndexedField.php index 336eac0..d998ad8 100644 --- a/src/DsLuceneBundle/Index/Field/UnIndexedField.php +++ b/src/DsLuceneBundle/Index/Field/UnIndexedField.php @@ -5,7 +5,7 @@ final class UnIndexedField extends AbstractType { /** - * {@inheritDoc} + * {@inheritdoc} */ public function build(string $name, $data, array $configuration = []) { diff --git a/src/DsLuceneBundle/Index/Field/UnStoredField.php b/src/DsLuceneBundle/Index/Field/UnStoredField.php index d06f478..7fa60f6 100644 --- a/src/DsLuceneBundle/Index/Field/UnStoredField.php +++ b/src/DsLuceneBundle/Index/Field/UnStoredField.php @@ -2,12 +2,10 @@ namespace DsLuceneBundle\Index\Field; -use DynamicSearchBundle\Transformer\Container\FieldContainerInterface; - final class UnStoredField extends AbstractType { /** - * {@inheritDoc} + * {@inheritdoc} */ public function build(string $name, $data, array $configuration = []) { diff --git a/src/DsLuceneBundle/Normalizer/DocumentKeyValueNormalizer.php b/src/DsLuceneBundle/Normalizer/DocumentKeyValueNormalizer.php index 0fb7a72..b5a378f 100644 --- a/src/DsLuceneBundle/Normalizer/DocumentKeyValueNormalizer.php +++ b/src/DsLuceneBundle/Normalizer/DocumentKeyValueNormalizer.php @@ -15,7 +15,7 @@ class DocumentKeyValueNormalizer implements DocumentNormalizerInterface protected $options; /** - * {@inheritDoc} + * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setOptions(array $options) { @@ -35,7 +35,7 @@ public function setOptions(array $options) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function normalize(ContextDataInterface $contextData, string $outputChannelName, $data) { @@ -53,4 +53,4 @@ public function normalize(ContextDataInterface $contextData, string $outputChann return $normalizedDocuments; } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/Normalizer/Helper/LuceneDocumentDataExtractor.php b/src/DsLuceneBundle/Normalizer/Helper/LuceneDocumentDataExtractor.php index bd91394..fc6f46f 100644 --- a/src/DsLuceneBundle/Normalizer/Helper/LuceneDocumentDataExtractor.php +++ b/src/DsLuceneBundle/Normalizer/Helper/LuceneDocumentDataExtractor.php @@ -15,7 +15,6 @@ public function extract(\Zend_Search_Lucene_Search_QueryHit $hit) $data = []; foreach ($document->getFieldNames() as $fieldName) { - $field = null; $fieldDefinition = null; @@ -33,7 +32,5 @@ public function extract(\Zend_Search_Lucene_Search_QueryHit $hit) } return $data; - } - -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/OutputChannel/AutoCompleteOutputChannel.php b/src/DsLuceneBundle/OutputChannel/AutoCompleteOutputChannel.php index 500cea3..ce66b12 100644 --- a/src/DsLuceneBundle/OutputChannel/AutoCompleteOutputChannel.php +++ b/src/DsLuceneBundle/OutputChannel/AutoCompleteOutputChannel.php @@ -35,7 +35,7 @@ public function __construct(LuceneStorageBuilder $storageBuilder) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDispatcher) { @@ -43,7 +43,7 @@ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDi } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $runtimeOptionsProvider) { @@ -51,7 +51,7 @@ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $run } /** - * {@inheritDoc} + * {@inheritdoc} */ public function configureOptions(OptionsResolver $optionsResolver) { @@ -71,7 +71,7 @@ public function configureOptions(OptionsResolver $optionsResolver) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function execute(array $indexProviderOptions, array $options = [], array $contextOptions = []): array { @@ -110,7 +110,6 @@ public function execute(array $indexProviderOptions, array $options = [], array $suggestions = []; /** @var \Zend_Search_Lucene_Index_Term $term */ foreach ($terms as $term) { - $fieldText = $term->text; if (in_array($fieldText, $suggestions)) { @@ -141,7 +140,6 @@ public function execute(array $indexProviderOptions, array $options = [], array ]); return $eventData->getParameter('result'); - } /** @@ -167,7 +165,7 @@ protected function getWildcardTerms($queryStr, \Zend_Search_Lucene_Interface $in /** * @param string $queryStr * @param \Zend_Search_Lucene_Interface $index - * @param integer $prefixLength optionally specify prefix length, default 0 + * @param int $prefixLength optionally specify prefix length, default 0 * @param float $similarity optionally specify similarity, default 0.5 * * @return string[] $similarSearchTerms @@ -190,6 +188,5 @@ public function getFuzzyTerms($queryStr, \Zend_Search_Lucene_Interface $index, $ } return $terms; - } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/OutputChannel/Modifier/Filter/QueryCleanTermFilter.php b/src/DsLuceneBundle/OutputChannel/Modifier/Filter/QueryCleanTermFilter.php index a0f47f6..82739fc 100644 --- a/src/DsLuceneBundle/OutputChannel/Modifier/Filter/QueryCleanTermFilter.php +++ b/src/DsLuceneBundle/OutputChannel/Modifier/Filter/QueryCleanTermFilter.php @@ -7,13 +7,17 @@ class QueryCleanTermFilter implements OutputChannelModifierFilterInterface { /** - * {@inheritDoc} + * {@inheritdoc} */ public function dispatchFilter(string $outputChannelName, array $options) { return trim( - preg_replace('|\s{2,}|', ' ', - preg_replace('|[^\p{L}\p{N} ]/u|', ' ', + preg_replace( + '|\s{2,}|', + ' ', + preg_replace( + '|[^\p{L}\p{N} ]/u|', + ' ', strtolower( strip_tags( str_replace("\n", ' ', $options['raw_term']) @@ -23,4 +27,4 @@ public function dispatchFilter(string $outputChannelName, array $options) ) ); } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/OutputChannel/SearchOutputChannel.php b/src/DsLuceneBundle/OutputChannel/SearchOutputChannel.php index 3906ece..9e4e2dd 100644 --- a/src/DsLuceneBundle/OutputChannel/SearchOutputChannel.php +++ b/src/DsLuceneBundle/OutputChannel/SearchOutputChannel.php @@ -35,7 +35,7 @@ public function __construct(LuceneStorageBuilder $storageBuilder) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDispatcher) { @@ -43,7 +43,7 @@ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDi } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $runtimeOptionsProvider) { @@ -51,7 +51,7 @@ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $run } /** - * {@inheritDoc} + * {@inheritdoc} */ public function configureOptions(OptionsResolver $optionsResolver) { @@ -62,12 +62,12 @@ public function configureOptions(OptionsResolver $optionsResolver) $optionsResolver->setDefaults([ 'min_prefix_length' => 3, - 'max_per_page' => 10 + 'max_per_page' => 10 ]); } /** - * {@inheritDoc} + * {@inheritdoc} */ public function execute(array $indexProviderOptions, array $options = [], array $contextOptions = []): array { @@ -129,5 +129,4 @@ protected function parseQuery(string $query, array $options) { return $query; } - -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/OutputChannel/SuggestionsOutputChannel.php b/src/DsLuceneBundle/OutputChannel/SuggestionsOutputChannel.php index f701c89..0a83c53 100644 --- a/src/DsLuceneBundle/OutputChannel/SuggestionsOutputChannel.php +++ b/src/DsLuceneBundle/OutputChannel/SuggestionsOutputChannel.php @@ -35,7 +35,7 @@ public function __construct(LuceneStorageBuilder $storageBuilder) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDispatcher) { @@ -43,7 +43,7 @@ public function setEventDispatcher(OutputChannelModifierEventDispatcher $eventDi } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $runtimeOptionsProvider) { @@ -51,7 +51,7 @@ public function setRuntimeParameterProvider(RuntimeOptionsProviderInterface $run } /** - * {@inheritDoc} + * {@inheritdoc} */ public function configureOptions(OptionsResolver $optionsResolver) { @@ -75,7 +75,7 @@ public function configureOptions(OptionsResolver $optionsResolver) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function execute(array $indexProviderOptions, array $options = [], array $contextOptions = []): array { @@ -150,7 +150,6 @@ protected function parseQuery(string $query, array $options) $terms = []; foreach ($queryTerms as $i => $queryTerm) { - if ($i === count($queryTerms) - 1) { $parsedWildCardTerm = $this->checkWildcardTerm($queryTerm); $terms[] = sprintf('+%s*', $parsedWildCardTerm); @@ -196,4 +195,4 @@ protected function checkWildcardTerm(string $term) return $cleanTerm; } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/Provider/LuceneIndexProvider.php b/src/DsLuceneBundle/Provider/LuceneIndexProvider.php index da348db..df7b114 100644 --- a/src/DsLuceneBundle/Provider/LuceneIndexProvider.php +++ b/src/DsLuceneBundle/Provider/LuceneIndexProvider.php @@ -44,7 +44,7 @@ public function __construct( } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setOptions(array $configuration) { @@ -52,7 +52,7 @@ public function setOptions(array $configuration) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function warmUp(ContextDataInterface $contextData) { @@ -68,12 +68,11 @@ public function warmUp(ContextDataInterface $contextData) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function coolDown(ContextDataInterface $contextData) { if ($contextData->getContextDispatchType() !== ContextDataInterface::CONTEXT_DISPATCH_TYPE_INDEX) { - try { $this->storageBuilder->optimizeLuceneIndex($this->configuration['database_name'], ConfigurationInterface::INDEX_BASE_STABLE); } catch (\Throwable $e) { @@ -91,21 +90,21 @@ public function coolDown(ContextDataInterface $contextData) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function cancelledShutdown(ContextDataInterface $contextData) { } /** - * {@inheritDoc} + * {@inheritdoc} */ public function emergencyShutdown(ContextDataInterface $contextData) { } /** - * {@inheritDoc} + * {@inheritdoc} */ public function processDocument(ContextDataInterface $contextData, IndexDocument $indexDocument) { @@ -114,12 +113,15 @@ public function processDocument(ContextDataInterface $contextData, IndexDocument case ContextDataInterface::CONTEXT_DISPATCH_TYPE_INDEX: case ContextDataInterface::CONTEXT_DISPATCH_TYPE_INSERT: $this->executeIndex($contextData, $indexDocument); + break; case ContextDataInterface::CONTEXT_DISPATCH_TYPE_UPDATE: $this->executeUpdate($contextData, $indexDocument); + break; case ContextDataInterface::CONTEXT_DISPATCH_TYPE_DELETE: $this->executeDelete($contextData, $indexDocument); + break; default: throw new \Exception(sprintf('invalid context dispatch type "%s". cannot perform index provider dispatch.', $contextData->getContextDispatchType())); @@ -167,6 +169,7 @@ protected function executeInsert(ContextDataInterface $contextData, IndexDocumen DsLuceneBundle::PROVIDER_NAME, $contextData->getName() ); + return; } @@ -196,6 +199,7 @@ protected function executeUpdate(ContextDataInterface $contextData, IndexDocumen DsLuceneBundle::PROVIDER_NAME, $contextData->getName() ); + return; } @@ -203,7 +207,6 @@ protected function executeUpdate(ContextDataInterface $contextData, IndexDocumen $termDocuments = $luceneHandler->findTermDocuments($indexDocument->getDocumentId()); if (!is_array($termDocuments) || count($termDocuments) === 0) { - $createNewDocumentMessage = $this->configuration['force_adding_document'] === true ? ' Going to add new document (options "force_adding_document" is set to "true")' : ' Going to skip adding new document (options "force_adding_document" is set to "false")'; @@ -242,6 +245,7 @@ protected function executeDelete(ContextDataInterface $contextData, IndexDocumen DsLuceneBundle::PROVIDER_NAME, $contextData->getName() ); + return; } @@ -259,11 +263,10 @@ protected function executeDelete(ContextDataInterface $contextData, IndexDocumen } $luceneHandler->deleteDocuments($termDocuments); - } /** - * {@inheritDoc} + * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { @@ -281,6 +284,7 @@ public function configureOptions(OptionsResolver $resolver) /** * @return \Zend_Search_Lucene_Interface + * * @throws LuceneException */ protected function getStableIndex() @@ -290,10 +294,11 @@ protected function getStableIndex() /** * @return \Zend_Search_Lucene_Interface + * * @throws LuceneException */ protected function getGenesisIndex() { return $this->storageBuilder->getLuceneIndex($this->configuration['database_name'], ConfigurationInterface::INDEX_BASE_GENESIS); } -} \ No newline at end of file +} diff --git a/src/DsLuceneBundle/Service/LuceneHandler.php b/src/DsLuceneBundle/Service/LuceneHandler.php index 71bba6e..85e819c 100644 --- a/src/DsLuceneBundle/Service/LuceneHandler.php +++ b/src/DsLuceneBundle/Service/LuceneHandler.php @@ -20,21 +20,21 @@ public function __construct(\Zend_Search_Lucene_Interface $index) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function findTermDocuments($documentId) { $idTerm = new \Zend_Search_Lucene_Index_Term($documentId, 'id'); + return $this->index->termDocs($idTerm); } /** - * {@inheritDoc} + * {@inheritdoc} */ public function deleteDocuments(array $documentIds) { foreach ($documentIds as $documentId) { - try { $skip = $this->index->isDeleted($documentId); } catch (\Zend_Search_Lucene_Exception $e) { @@ -54,7 +54,7 @@ public function deleteDocuments(array $documentIds) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function createLuceneDocument(IndexDocument $indexDocument, bool $addToIndex, $commit = true) { @@ -65,13 +65,13 @@ public function createLuceneDocument(IndexDocument $indexDocument, bool $addToIn foreach ($indexDocument->getOptionFields() as $optionField) { if ($optionField->getName() === 'boost') { $doc->boost = $optionField->getData(); + break; } } } foreach ($indexDocument->getIndexFields() as $field) { - if (!$field->getData() instanceof \Zend_Search_Lucene_Field) { continue; } @@ -87,7 +87,7 @@ public function createLuceneDocument(IndexDocument $indexDocument, bool $addToIn } /** - * {@inheritDoc} + * {@inheritdoc} */ public function addDocumentToIndex(\Zend_Search_Lucene_Document $document, bool $commit = true) { @@ -98,4 +98,3 @@ public function addDocumentToIndex(\Zend_Search_Lucene_Document $document, bool } } } - diff --git a/src/DsLuceneBundle/Service/LuceneHandlerInterface.php b/src/DsLuceneBundle/Service/LuceneHandlerInterface.php index 310bdb1..1898c47 100644 --- a/src/DsLuceneBundle/Service/LuceneHandlerInterface.php +++ b/src/DsLuceneBundle/Service/LuceneHandlerInterface.php @@ -7,7 +7,7 @@ interface LuceneHandlerInterface { /** - * @param $documentId + * @param string $documentId * * @return array */ @@ -32,6 +32,4 @@ public function createLuceneDocument(IndexDocument $indexDocument, bool $addToIn * @param bool $commit */ public function addDocumentToIndex(\Zend_Search_Lucene_Document $document, bool $commit = true); - } - diff --git a/src/DsLuceneBundle/Service/LuceneStorageBuilder.php b/src/DsLuceneBundle/Service/LuceneStorageBuilder.php index 34776dc..44f6d25 100644 --- a/src/DsLuceneBundle/Service/LuceneStorageBuilder.php +++ b/src/DsLuceneBundle/Service/LuceneStorageBuilder.php @@ -25,6 +25,7 @@ public function __construct() * @param bool $killExistingInstance * * @return \Zend_Search_Lucene_Interface + * * @throws LuceneException */ public function createGenesisIndex(string $databaseName, $killExistingInstance = false) @@ -52,7 +53,6 @@ public function createGenesisIndex(string $databaseName, $killExistingInstance = } return $this->getLuceneIndex($databaseName); - } /** @@ -112,6 +112,7 @@ public function optimizeLuceneIndex(string $databaseName, string $state = Config * @param string $state * * @return \Zend_Search_Lucene_Interface + * * @throws LuceneException */ public function getLuceneIndex(string $databaseName, string $state = ConfigurationInterface::INDEX_BASE_GENESIS) @@ -157,6 +158,7 @@ public function indexExists(string $databaseName, string $state = ConfigurationI try { \Zend_Search_Lucene::open($indexDir); + return true; } catch (\Zend_Search_Lucene_Exception $e) { // fail silently @@ -195,4 +197,3 @@ protected function buildIndexPath($databaseName, $state = ConfigurationInterface return sprintf('%s/%s', $state, $databaseName); } } - diff --git a/tests/_bootstrap.php b/tests/_bootstrap.php new file mode 100644 index 0000000..b4253d7 --- /dev/null +++ b/tests/_bootstrap.php @@ -0,0 +1,19 @@ +addBundle(new \AppBundle\AppBundle()); + } + } +} \ No newline at end of file diff --git a/tests/_etc/config/bundle/extensions.template.php b/tests/_etc/config/bundle/extensions.template.php new file mode 100644 index 0000000..31476c7 --- /dev/null +++ b/tests/_etc/config/bundle/extensions.template.php @@ -0,0 +1,7 @@ + [ + "DynamicSearchBundle\\DynamicSearchBundle" => TRUE, + ] +]; diff --git a/tests/_etc/config/bundle/symfony/config_default.yml b/tests/_etc/config/bundle/symfony/config_default.yml new file mode 100755 index 0000000..e69de29 diff --git a/tests/_etc/config/bundle/system.template.php b/tests/_etc/config/bundle/system.template.php new file mode 100755 index 0000000..4db7979 --- /dev/null +++ b/tests/_etc/config/bundle/system.template.php @@ -0,0 +1,172 @@ + [ + "timezone" => "Europe/Berlin", + "path_variable" => "", + "domain" => "localhost", + "redirect_to_maindomain" => false, + "language" => "en", + "validLanguages" => "en,de,fr,it,de_DE,en_US,de_CH", + "fallbackLanguages" => [ + "en" => "", + "de" => "", + "fr" => "", + "it" => "", + "de_DE" => "de", + "de_CH" => "de", + "en_US" => "en", + ], + "defaultLanguage" => "en", + "loginscreencustomimage" => "", + "disableusagestatistics" => true, + "debug" => false, + "debug_ip" => "", + "http_auth" => [ + "username" => "", + "password" => "" + ], + "debug_admin_translations" => false, + "devmode" => false, + "instanceIdentifier" => "", + "show_cookie_notice" => false + ], + "database" => [ + "adapter" => "Pdo_Mysql", + "params" => [ + "host" => "localhost", + "username" => "root", + "password" => "", + "dbname" => "dachcom_bundle_test", + "port" => "3306" + ] + ], + "documents" => [ + "versions" => [ + "days" => null, + "steps" => 10 + ], + "default_controller" => "Default", + "default_action" => "default", + "error_pages" => [ + "default" => "/error" + ], + "createredirectwhenmoved" => false, + "allowtrailingslash" => "no", + "generatepreview" => true + ], + "objects" => [ + "versions" => [ + "days" => null, + "steps" => 10 + ] + ], + "assets" => [ + "versions" => [ + "days" => null, + "steps" => 10 + ], + "icc_rgb_profile" => "", + "icc_cmyk_profile" => "", + "hide_edit_image" => false, + "disable_tree_preview" => false + ], + "services" => [ + "google" => [ + "client_id" => "", + "email" => "", + "simpleapikey" => "", + "browserapikey" => "" + ] + ], + "cache" => [ + "enabled" => false, + "lifetime" => null, + "excludePatterns" => "", + "excludeCookie" => "" + ], + "outputfilters" => [ + "less" => false, + "lesscpath" => "" + ], + "webservice" => [ + "enabled" => true + ], + "httpclient" => [ + "adapter" => "Zend_Http_Client_Adapter_Socket", + "proxy_host" => "", + "proxy_port" => "", + "proxy_user" => "", + "proxy_pass" => "" + ], + "email" => [ + "sender" => [ + "name" => "pimcore", + "email" => "pimcore@example.com" + ], + "return" => [ + "name" => "pimcore", + "email" => "pimcore@example.com" + ], + "method" => "mail", + "smtp" => [ + "host" => "", + "port" => "", + "ssl" => null, + "name" => "", + "auth" => [ + "method" => "login", + "username" => "", + "password" => "" + ] + ], + "debug" => [ + "emailaddresses" => "" + ], + "bounce" => [ + "type" => "", + "maildir" => "", + "mbox" => "", + "imap" => [ + "host" => "", + "port" => "", + "username" => "", + "password" => "", + "ssl" => false + ] + ] + ], + "newsletter" => [ + "sender" => [ + "name" => "", + "email" => "" + ], + "return" => [ + "name" => "", + "email" => "" + ], + "method" => null, + "smtp" => [ + "host" => "", + "port" => "", + "ssl" => "ssl", + "name" => "", + "auth" => [ + "method" => null, + "username" => "", + "password" => null + ] + ], + "debug" => null, + "usespecific" => true + ], + "applicationlog" => [ + "mail_notification" => [ + "send_log_summary" => false, + "filter_priority" => null, + "mail_receiver" => "" + ], + "archive_treshold" => "30", + "archive_alternative_database" => "" + ] +]; diff --git a/tests/_etc/config/bundle/template/controller/DefaultController b/tests/_etc/config/bundle/template/controller/DefaultController new file mode 100644 index 0000000..fea9a8b --- /dev/null +++ b/tests/_etc/config/bundle/template/controller/DefaultController @@ -0,0 +1,19 @@ +setViewAutoRender($event->getRequest(), true, 'twig'); + } + + public function defaultAction(Request $request) + { + } +} diff --git a/tests/_etc/config/bundle/template/views/default b/tests/_etc/config/bundle/template/views/default new file mode 100644 index 0000000..a9bd9eb --- /dev/null +++ b/tests/_etc/config/bundle/template/views/default @@ -0,0 +1,21 @@ + + + + + Test Page for Search Bundle + {{ pimcore_head_meta() }} + {{ pimcore_head_link() }} + + +
+
+ {% if document is defined %} + {{ document.getId() }} + {% endif %} +
+ {% block content %} + {{ pimcore_areablock('dachcomBundleTest') }} + {% endblock %} +
+ + diff --git a/tests/_etc/config/system/config.yml b/tests/_etc/config/system/config.yml new file mode 100755 index 0000000..73736d7 --- /dev/null +++ b/tests/_etc/config/system/config.yml @@ -0,0 +1,18 @@ +imports: + - { resource: parameters.yml } + - { resource: security.yml } + - { resource: services.yml } + - { resource: 'local/' } + +# don't send real emails in functional tests +swiftmailer: + disable_delivery: true + +pimcore: + error_handling: + render_error_document: true + +framework: + profiler: + enabled: true + collect: false \ No newline at end of file diff --git a/tests/_etc/config/system/php.ini b/tests/_etc/config/system/php.ini new file mode 100755 index 0000000..3635758 --- /dev/null +++ b/tests/_etc/config/system/php.ini @@ -0,0 +1,8 @@ + +; extensions +;extension="memcache.so" +;extension="memcached.so" + +; custom php settings +memory_limit = 1G +date.timezone = Europe/Berlin \ No newline at end of file diff --git a/tests/_etc/scripts/codeception b/tests/_etc/scripts/codeception new file mode 100755 index 0000000..41b6c4f --- /dev/null +++ b/tests/_etc/scripts/codeception @@ -0,0 +1,12 @@ +#!/bin/bash +set -e + +echo "START CODECEPTION TESTS FOR $DACHCOM_BUNDLE_NAME" + +CMD="vendor/bin/codecept run -c lib/$DACHCOM_BUNDLE_NAME --env travis" + +# generate json result file +CMD="$CMD --json" + +echo $CMD +eval $CMD diff --git a/tests/_etc/scripts/ecs b/tests/_etc/scripts/ecs new file mode 100755 index 0000000..e0af73f --- /dev/null +++ b/tests/_etc/scripts/ecs @@ -0,0 +1,6 @@ +#!/bin/bash +set -e + +echo "START ECS FOR $DACHCOM_BUNDLE_NAME" + +vendor/bin/ecs check lib/$DACHCOM_BUNDLE_NAME/src --config lib/$DACHCOM_BUNDLE_NAME/easy-coding-standard.yml diff --git a/tests/_etc/scripts/phpstan b/tests/_etc/scripts/phpstan new file mode 100755 index 0000000..d4356da --- /dev/null +++ b/tests/_etc/scripts/phpstan @@ -0,0 +1,7 @@ +#!/bin/bash +set -e + +echo "START PHPSTAN FOR $DACHCOM_BUNDLE_NAME" + +bin/console cache:warmup --env=dev +vendor/bin/phpstan analyse -c lib/$DACHCOM_BUNDLE_NAME/phpstan.neon -a lib/$DACHCOM_BUNDLE_NAME/tests/_phpstan-bootstrap.php lib/$DACHCOM_BUNDLE_NAME/src -l 2 diff --git a/tests/_etc/travis/install b/tests/_etc/travis/install new file mode 100755 index 0000000..9c83978 --- /dev/null +++ b/tests/_etc/travis/install @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +set -e + + +## include global bundle test configuration + +source $TRAVIS_BUILD_DIR/tests/_etc/bundle_configuration + + +## setup php + +phpenv config-add $DACHCOM_BUNDLE_HOME/tests/_etc/config/system/php.ini + + +## setup mysql + +mysql --version +mysql -e "SET GLOBAL innodb_file_format=Barracuda;" +mysql -e "SET GLOBAL innodb_large_prefix=1;" +mysql -e "CREATE DATABASE dachcom_bundle_test CHARSET=utf8mb4;" + + +## move bundle temporarily and clean dir in order to install pimcore + +mkdir -p $DACHCOM_BUNDLE_HOME/../lib/$DACHCOM_BUNDLE_NAME +mv $DACHCOM_BUNDLE_HOME/{.[!.],}* $DACHCOM_BUNDLE_HOME/../lib/$DACHCOM_BUNDLE_NAME +rm -rf $DACHCOM_BUNDLE_HOME/{.[!.],}* + + +## clone pimcore + +git clone https://github.com/pimcore/skeleton.git $DACHCOM_BUNDLE_HOME +git checkout ${PIMCORE_SKELETON_BRANCH} $DACHCOM_BUNDLE_HOME + + +## move bundle back into lib/$DACHCOM_BUNDLE_NAME + +mv $DACHCOM_BUNDLE_HOME/../lib $DACHCOM_BUNDLE_HOME + + +## copy _etc dir to root dir + +cp -r $DACHCOM_BUNDLE_HOME/lib/$DACHCOM_BUNDLE_NAME/tests/_etc/bundle_configuration $DACHCOM_BUNDLE_HOME/bundle_configuration +cp -r $DACHCOM_BUNDLE_HOME/lib/$DACHCOM_BUNDLE_NAME/tests/_etc $DACHCOM_BUNDLE_HOME/_etc +chmod -R +x $DACHCOM_BUNDLE_HOME/_etc + + +## create download dir + +mkdir $DACHCOM_BUNDLE_HOME/lib/$DACHCOM_BUNDLE_NAME/tests/_data/downloads + + +## add config templates + +mkdir -p $DACHCOM_BUNDLE_HOME/var/config +cp $DACHCOM_BUNDLE_HOME/_etc/config/system/config.yml app/config/config.yml +cp app/config/parameters.example.yml app/config/parameters.yml + +for K in "${!DACHCOM_INSTALL_CONFIG_FILES[@]}" +do + cp $K ${DACHCOM_INSTALL_CONFIG_FILES[$K]}; +done + + +## load GeoLite2 + +wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz +gzip -d GeoLite2-City.mmdb.gz +mv -nv GeoLite2-City.mmdb var/config/ + + +## install composer dependencies + +COMPOSER_MEMORY_LIMIT=-1 composer install --no-scripts + +COMPOSER_MEMORY_LIMIT=-1 composer require phpstan/phpstan:^0.11.1 phpstan/phpstan-symfony:^0.11.0 symplify/easy-coding-standard:^5.4 --no-scripts + +## install $DACHCOM_BUNDLE_NAME dependencies +BRANCH_REGEX="^(([[:digit:]]+\.)+[[:digit:]]+)$" + +if [[ ${TRAVIS_BRANCH} =~ $BRANCH_REGEX ]]; then + echo "composer require dachcom-digital/${DACHCOM_BUNDLE_REPO_NAME}:${TRAVIS_BRANCH}" + COMPOSER_MEMORY_LIMIT=-1 composer require dachcom-digital/${DACHCOM_BUNDLE_REPO_NAME}:${TRAVIS_BRANCH} +else + echo "composer require dachcom-digital/${DACHCOM_BUNDLE_REPO_NAME}:dev-${TRAVIS_BRANCH}" + COMPOSER_MEMORY_LIMIT=-1 composer require "dachcom-digital/${DACHCOM_BUNDLE_REPO_NAME}:dev-${TRAVIS_BRANCH}#${TRAVIS_COMMIT}" +fi + +## clear cache + +rm -rf var/cache diff --git a/tests/_etc/travis/script b/tests/_etc/travis/script new file mode 100755 index 0000000..c65286a --- /dev/null +++ b/tests/_etc/travis/script @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -e + +source $TRAVIS_BUILD_DIR/_etc/bundle_configuration + +$DACHCOM_BUNDLE_HOME/_etc/scripts/$DACHCOM_TEST_SECTION \ No newline at end of file diff --git a/tests/_phpstan-bootstrap.php b/tests/_phpstan-bootstrap.php new file mode 100644 index 0000000..0c3c527 --- /dev/null +++ b/tests/_phpstan-bootstrap.php @@ -0,0 +1,6 @@ +load($bundleClass . '/_etc/config/bundle/symfony/' . $configName); + } + } + + /** + * {@inheritdoc} + */ + public function registerBundlesToCollection(\Pimcore\HttpKernel\BundleCollection\BundleCollection $collection) + { + if (class_exists('\\AppBundle\\AppBundle')) { + $collection->addBundle(new \AppBundle\AppBundle()); + } + + $collection->addBundle(new \Symfony\Bundle\WebProfilerBundle\WebProfilerBundle()); + + $bundleClass = getenv('DACHCOM_BUNDLE_CLASS'); + $collection->addBundle(new $bundleClass()); + } + + /** + * @param ContainerBuilder $container + */ + protected function build(ContainerBuilder $container) + { + $container->addCompilerPass(new \DachcomBundle\Test\DependencyInjection\MakeServicesPublicPass(), + \Symfony\Component\DependencyInjection\Compiler\PassConfig::TYPE_BEFORE_OPTIMIZATION, -100000); + $container->addCompilerPass(new \DachcomBundle\Test\DependencyInjection\MonologChannelLoggerPass(), + \Symfony\Component\DependencyInjection\Compiler\PassConfig::TYPE_BEFORE_OPTIMIZATION, 1); + } + + /** + * {@inheritdoc} + */ + public function boot() + { + parent::boot(); + \Pimcore::setKernel($this); + } +} diff --git a/tests/_support/DependencyInjection/MakeServicesPublicPass.php b/tests/_support/DependencyInjection/MakeServicesPublicPass.php new file mode 100644 index 0000000..13736db --- /dev/null +++ b/tests/_support/DependencyInjection/MakeServicesPublicPass.php @@ -0,0 +1,30 @@ +getServiceIds(), function (string $id) use ($prefix) { + return strpos($id, $prefix) === 0; + }); + + foreach ($serviceIds as $serviceId) { + if ($container->hasAlias($serviceId)) { + $container->getAlias($serviceId)->setPublic(true); + } + + $container + ->findDefinition($serviceId) + ->setPublic(true); + } + } +} diff --git a/tests/_support/DependencyInjection/MonologChannelLoggerPass.php b/tests/_support/DependencyInjection/MonologChannelLoggerPass.php new file mode 100644 index 0000000..91f8875 --- /dev/null +++ b/tests/_support/DependencyInjection/MonologChannelLoggerPass.php @@ -0,0 +1,27 @@ +getParameter('monolog.handlers_to_channels'); + foreach ($channelsToHide as $channelToHide) { + $monologHandlers['monolog.handler.console']['elements'][] = $channelToHide; + } + + $container->setParameter('monolog.handlers_to_channels', $monologHandlers); + } +} diff --git a/tests/_support/FunctionalTester.php b/tests/_support/FunctionalTester.php new file mode 100644 index 0000000..862e9c1 --- /dev/null +++ b/tests/_support/FunctionalTester.php @@ -0,0 +1,13 @@ + 'PhpBrowser needs the pimcore core framework to work.' + ]; + } + + /** + * @param PimcoreCore $pimcoreCore + */ + public function _inject($pimcoreCore) + { + $this->pimcoreCore = $pimcoreCore; + } + + /** + * @inheritDoc + */ + public function _initialize() + { + $this->sessionSnapShot = []; + + parent::_initialize(); + } + + /** + * Actor Function to see current uri matches given host + * + * @param $host + */ + public function seeCurrentHostEquals($host) + { + $server = $this->pimcoreCore->client->getHistory()->current()->getServer(); + $this->assertEquals($host, $server['HTTP_HOST']); + } + + /** + * Actor Function to see a page generated by a static route definition. + * + * @param string $routeName + * @param array $args + */ + public function amOnStaticRoute(string $routeName, array $args) + { + $path = $this->pimcoreCore->getContainer()->get('router')->generate($routeName, $args, false); + $this->pimcoreCore->amOnPage($path); + } + + /** + * Actor Function to see a page with enabled edit-mode + * + * @param string $page + */ + public function amOnPageInEditMode(string $page) + { + $this->pimcoreCore->amOnPage(sprintf('%s?pimcore_editmode=true', $page)); + } + + /** + * Actor Function to see a page with given locale + * + * @param string $url + * @param string $locale + */ + public function amOnPageWithLocale($url, $locale) + { + $this->pimcoreCore->_loadPage('GET', $url, [], [], ['HTTP_ACCEPT_LANGUAGE' => $locale]); + } + + /** + * Actor Function to login into Pimcore Backend + * + * @param $username + */ + public function amLoggedInAs($username) + { + $firewallName = 'admin'; + + try { + /** @var PimcoreUser $userModule */ + $userModule = $this->getModule('\\' . PimcoreUser::class); + } catch (ModuleException $pimcoreModule) { + $this->debug('[PIMCORE BUNDLE MODULE] could not load pimcore user module'); + return; + } + + $pimcoreUser = $userModule->getUser($username); + + if (!$pimcoreUser instanceof User) { + $this->debug(sprintf('[PIMCORE BUNDLE MODULE] could not fetch user %s.', $username)); + return; + } + + /** @var Session $session */ + $session = $this->pimcoreCore->getContainer()->get('session'); + + $user = new \Pimcore\Bundle\AdminBundle\Security\User\User($pimcoreUser); + $token = new UsernamePasswordToken($user, null, $firewallName, $pimcoreUser->getRoles()); + $this->pimcoreCore->getContainer()->get('security.token_storage')->setToken($token); + + \Pimcore\Tool\Session::useSession(function (AttributeBagInterface $adminSession) use ($pimcoreUser, $session) { + $session->setId(\Pimcore\Tool\Session::getSessionId()); + $adminSession->set('user', $pimcoreUser); + $adminSession->set('csrfToken', self::PIMCORE_ADMIN_CSRF_TOKEN_NAME); + }); + + // allow re-usage of session in same cest. + if (!empty($this->sessionSnapShot)) { + $cookie = $this->sessionSnapShot; + } else { + $cookie = new Cookie($session->getName(), $session->getId()); + $this->sessionSnapShot = $cookie; + } + + $this->pimcoreCore->client->getCookieJar()->clear(); + $this->pimcoreCore->client->getCookieJar()->set($cookie); + + } + + /** + * Actor Function to see canonical rel in link header + */ + public function seeCanonicalLinkInResponse() + { + $link = $this->pimcoreCore->client->getInternalResponse()->getHeader('Link'); + + $this->assertInternalType('string', $link); + $this->assertContains('rel="canonical"', $link); + } + + /** + * Actor Function to not see canonical rel in link header + */ + public function dontSeeCanonicalLinkInResponse() + { + $link = $this->pimcoreCore->client->getInternalResponse()->getHeader('Link'); + + $this->assertNull($link); + } + + /** + * Actor Function to check if last _fragment request has given properties in request attributes. + * + * @param array $properties + */ + public function seePropertiesInLastFragmentRequest(array $properties = []) + { + /** @var Profiler $profiler */ + $profiler = $this->pimcoreCore->_getContainer()->get('profiler'); + + $tokens = $profiler->find('', '_fragment', 1, 'GET', '', ''); + if (count($tokens) === 0) { + throw new \RuntimeException('No profile found. Is the profiler data collector enabled?'); + } + + $token = $tokens[0]['token']; + /** @var \Symfony\Component\HttpKernel\Profiler\Profile $profile */ + $profile = $profiler->loadProfile($token); + + if (!$profile instanceof Profile) { + throw new \RuntimeException(sprintf('Profile with token "%s" not found.', $token)); + } + + /** @var RequestDataCollector $requestCollector */ + $requestCollector = $profile->getCollector('request'); + + foreach ($properties as $property) { + $this->assertTrue($requestCollector->getRequestAttributes()->has($property), sprintf('"%s" not found in request collector.', $property)); + } + } +} diff --git a/tests/_support/Helper/PimcoreBackend.php b/tests/_support/Helper/PimcoreBackend.php new file mode 100644 index 0000000..8388337 --- /dev/null +++ b/tests/_support/Helper/PimcoreBackend.php @@ -0,0 +1,436 @@ +generatePageDocument($documentKey, $locale); + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving document page. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Page::class, Page::getById($document->getId())); + + return $document; + } + + /** + * Actor Function to create a Child Page Document + * + * @param Document $parent + * @param string $documentKey + * @param string $locale + * + * @return Page + */ + public function haveASubPageDocument( + Document $parent, + $documentKey = 'test-sub-document', + $locale = null + ) { + $document = $this->generatePageDocument($documentKey, $locale); + $document->setParentId($parent->getId()); + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving child document page. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Page::class, Page::getById($document->getId())); + + return $document; + } + + /** + * Actor Function to create a link + * + * @param Page $source + * @param string $linkKey + * @param string $locale + * + * @return Document\Link + */ + public function haveALink( + Page $source, + $linkKey = 'test-link', + $locale = null + ) { + $link = $this->generateLink($source, $linkKey, $locale); + + try { + $link->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving link. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Document\Link::class, Document\Link::getById($link->getId())); + + return $link; + } + + /** + * Actor Function to create a link + * + * @param Document $parent + * @param Page $source + * @param string $linkKey + * @param string $locale + * + * @return Document\Link + */ + public function haveASubLink( + Document $parent, + Page $source, + $linkKey = 'test-link', + $locale = null + ) { + $link = $this->generateLink($source, $linkKey, $locale); + $link->setParent($parent); + + try { + $link->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving sub link. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Document\Link::class, Document\Link::getById($link->getId())); + + return $link; + } + + /** + * Actor Function to create a Hardlink + * + * @param Page $source + * @param string $hardlinkKey + * @param string $locale + * + * @return Hardlink + */ + public function haveAHardLink( + Page $source, + $hardlinkKey = 'test-document', + $locale = null + ) { + $hardlink = $this->generateHardlink($source, $hardlinkKey, $locale); + + try { + $hardlink->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving hardlink. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Hardlink::class, Hardlink::getById($hardlink->getId())); + + return $hardlink; + } + + /** + * Actor Function to create a Site Document + * + * @param string $siteKey + * @param null $locale + * + * @return Site + */ + public function haveASite($siteKey, $locale = null) + { + $site = $this->generateSiteDocument($siteKey, $locale); + + try { + $site->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving site. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Site::class, Site::getById($site->getId())); + + return $site; + } + + /** + * Actor Function to create a Document for a Site + * + * @param Site $site + * @param string $key + * @param string $locale + * + * @return Page + */ + public function haveAPageDocumentForSite(Site $site, $key = 'document-test', $locale = null) + { + $document = $this->generatePageDocument($key, $locale); + $document->setParentId($site->getRootDocument()->getId()); + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while document page for site. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Page::class, Page::getById($document->getId())); + + return $document; + } + + /** + * Actor Function to create a Hard Link for a Site + * + * @param Site $site + * @param Page $document + * @param string $key + * @param string $locale + * + * @return Page + */ + public function haveAHardlinkForSite(Site $site, Page $document, $key = 'hardlink-test', $locale = null) + { + $hardLink = $this->generateHardlink($document, $key, $locale); + $hardLink->setParentId($site->getRootDocument()->getId()); + + try { + $hardLink->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while document page for site. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Hardlink::class, Hardlink::getById($hardLink->getId())); + + return $hardLink; + } + + /** + * Actor Function to create a FrontPage mapped Document + * + * @param Hardlink $hardlinkDocument + * + * @return Page + */ + public function haveAFrontPageMappedDocument(Hardlink $hardlinkDocument) + { + $document = $this->generatePageDocument('frontpage-mapped-' . $hardlinkDocument->getKey()); + $document->setParentId($hardlinkDocument->getId()); + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while document page for frontpage mapping. message was: ' . $e->getMessage())); + } + + $this->assertInstanceOf(Page::class, Page::getById($document->getId())); + + $hardlinkDocument->setProperty('front_page_map', 'document', $document->getId(), false, false); + + try { + $hardlinkDocument->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while document hardlink for frontpage mapping. message was: ' . $e->getMessage())); + } + + return $document; + } + + /** + * Actor Function to create a language connection + * + * @param Page $sourceDocument + * @param Page $targetDocument + * + */ + public function haveTwoConnectedDocuments(Page $sourceDocument, Page $targetDocument) + { + $service = new Service(); + $service->addTranslation($sourceDocument, $targetDocument); + } + + /** + * Actor Function to disable a document + * + * @param Document $document + * + * @return Document + */ + public function haveAUnPublishedDocument(Document $document) + { + $document->setPublished(false); + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while un-publishing document. message was: ' . $e->getMessage())); + } + + return $document; + } + + /** + * API Function to create a page document + * + * @param string $key + * @param string $locale + * + * @return Page + */ + protected function generatePageDocument($key = 'document-test', $locale = null) + { + $document = TestHelper::createEmptyDocumentPage('', false); + $document->setController('@AppBundle\Controller\DefaultController'); + $document->setAction('default'); + $document->setKey($key); + $document->setProperty('navigation_title', 'text', $key); + $document->setProperty('navigation_name', 'text', $key); + + if ($locale !== null) { + $document->setProperty('language', 'text', $locale, false, true); + } + + return $document; + } + + /** + * API Function to create a hardlink document + * + * @param Page $source + * @param string $key + * @param string $locale + * + * @return Hardlink + */ + protected function generateHardlink(Page $source, $key = 'hardlink-test', $locale = null) + { + $hardlink = new Hardlink(); + $hardlink->setKey($key); + $hardlink->setParentId(1); + $hardlink->setSourceId($source->getId()); + $hardlink->setPropertiesFromSource(true); + $hardlink->setChildrenFromSource(true); + $hardlink->setProperty('navigation_title', 'text', $key); + $hardlink->setProperty('navigation_name', 'text', $key); + + if ($locale !== null) { + $hardlink->setProperty('language', 'text', $locale, false, true); + } + + return $hardlink; + } + + + /** + * API Function to create a link document + * + * @param Page $source + * @param string $key + * @param string $locale + * + * @return Document\Link + */ + protected function generateLink(Page $source, $key = 'link-test', $locale = null) + { + $link = new Document\Link(); + $link->setKey($key); + $link->setParentId(1); + $link->setLinktype('internal'); + $link->setInternalType('document'); + $link->setInternal($source->getId()); + $link->setProperty('navigation_title', 'text', $key); + $link->setProperty('navigation_name', 'text', $key); + + if ($locale !== null) { + $link->setProperty('language', 'text', $locale, false, true); + } + + return $link; + } + + + + /** + * API Function to create a site document + * + * @param string $domain + * @param string $locale + * + * @return Site + */ + protected function generateSiteDocument($domain, $locale = null) + { + $document = TestHelper::createEmptyDocumentPage($domain, false); + $document->setProperty('navigation_title', 'text', $domain); + $document->setProperty('navigation_name', 'text', $domain); + + $document->setKey(str_replace('.', '-', $domain)); + + if ($locale !== null) { + $document->setProperty('language', 'text', $locale, false, true); + } + + try { + $document->save(); + } catch (\Exception $e) { + \Codeception\Util\Debug::debug(sprintf('[SEARCH ERROR] error while saving document for site. message was: ' . $e->getMessage())); + } + + $site = new Site(); + $site->setRootId((int) $document->getId()); + $site->setMainDomain($domain); + + return $site; + } + + /** + * @return Container + * @throws \Codeception\Exception\ModuleException + */ + protected function getContainer() + { + return $this->getModule('\\' . PimcoreCore::class)->getContainer(); + } +} diff --git a/tests/_support/Helper/PimcoreBundleCore.php b/tests/_support/Helper/PimcoreBundleCore.php new file mode 100644 index 0000000..dbf93ad --- /dev/null +++ b/tests/_support/Helper/PimcoreBundleCore.php @@ -0,0 +1,68 @@ +config = array_merge($this->config, [ + 'run_installer' => false + ]); + + parent::__construct($moduleContainer, $config); + } + + /** + * @param array $settings + * + * @throws \Codeception\Exception\ModuleException + */ + public function _beforeSuite($settings = []) + { + parent::_beforeSuite($settings); + + if ($this->config['run_installer'] === true) { + $this->installBundle($settings); + } + } + + /** + * @param $settings + * + * @return string|void + * @throws \Codeception\Exception\ModuleException + * @throws \Exception + */ + private function installBundle($settings) + { + /** @var PimcoreCore $pimcoreModule */ + $pimcoreModule = $this->getModule('\\' . PimcoreCore::class); + + $bundleName = getenv('DACHCOM_BUNDLE_NAME'); + $installerClass = getenv('DACHCOM_BUNDLE_INSTALLER_CLASS'); + + if ($installerClass === false) { + return; + } + + $this->debug(sprintf('[%s] Running installer...', strtoupper($bundleName))); + + if ($pimcoreModule->_getContainer()) { + $pimcoreModule->getKernel()->reboot($pimcoreModule->getKernel()->getCacheDir()); + } + + // install dachcom bundle + $installer = $pimcoreModule->getContainer()->get($installerClass); + $installer->install(); + + \Pimcore::collectGarbage(); + } +} diff --git a/tests/_support/Helper/PimcoreCore.php b/tests/_support/Helper/PimcoreCore.php new file mode 100644 index 0000000..a14d2b8 --- /dev/null +++ b/tests/_support/Helper/PimcoreCore.php @@ -0,0 +1,166 @@ +config = array_merge($this->config, [ + // set specific configuration file for suite + 'configuration_file' => null + ]); + + parent::__construct($moduleContainer, $config); + } + + /** + * @inheritDoc + */ + public function _after(\Codeception\TestInterface $test) + { + parent::_after($test); + + // config has changed, we need to restore default config before starting a new test! + if ($this->kernelHasCustomConfig === true) { + $this->clearCache(); + $this->bootKernelWithConfiguration(null); + $this->kernelHasCustomConfig = false; + } + } + + /** + * @inheritdoc + */ + public function _afterSuite() + { + \Pimcore::collectGarbage(); + $this->clearCache(); + parent::_afterSuite(); + } + + /** + * @inheritdoc + */ + public function _initialize() + { + $this->setPimcoreEnvironment($this->config['environment']); + $this->initializeKernel(); + $this->setupDbConnection(); + $this->setPimcoreCacheAvailability('disabled'); + } + + /** + * @inheritdoc + */ + protected function initializeKernel() + { + $maxNestingLevel = 200; // Symfony may have very long nesting level + $xdebugMaxLevelKey = 'xdebug.max_nesting_level'; + if (ini_get($xdebugMaxLevelKey) < $maxNestingLevel) { + ini_set($xdebugMaxLevelKey, $maxNestingLevel); + } + + $configFile = null; + if ($this->config['configuration_file'] !== null) { + $configFile = $this->config['configuration_file']; + } + + $this->bootKernelWithConfiguration($configFile); + $this->setupPimcoreDirectories(); + } + + /** + * @param $configuration + */ + protected function bootKernelWithConfiguration($configuration) + { + if ($configuration === null) { + $configuration = 'config_default.yml'; + } + + putenv('DACHCOM_BUNDLE_CONFIG_FILE=' . $configuration); + + $this->kernel = require __DIR__ . '/../_boot/kernelBuilder.php'; + $this->getKernel()->boot(); + + $this->client = new SymfonyConnector($this->kernel, $this->persistentServices, $this->config['rebootable_client']); + + if ($this->config['cache_router'] === true) { + $this->persistService('router', true); + } + + // dispatch kernel booted event - will be used from services which need to reset state between tests + $this->kernel->getContainer()->get('event_dispatcher')->dispatch(TestEvents::KERNEL_BOOTED); + } + + /** + * @param bool $force + */ + protected function clearCache($force = true) + { + \Codeception\Util\Debug::debug('[PIMCORE] Clear Cache!'); + + $fileSystem = new Filesystem(); + + try { + $fileSystem->remove(PIMCORE_PROJECT_ROOT . '/var/cache'); + $fileSystem->mkdir(PIMCORE_PROJECT_ROOT . '/var/cache'); + } catch (\Exception $e) { + //try again later if "directory not empty" error occurs. + if ($force === true) { + sleep(1); + $this->clearCache(false); + } + } + } + + /** + * @param $env + */ + protected function setPimcoreEnvironment($env) + { + Config::setEnvironment($env); + } + + /** + * @param string $state + */ + protected function setPimcoreCacheAvailability($state = 'disabled') + { + if ($state === 'disabled') { + Cache::disable(); + } else { + Cache::enable(); + } + } + + /** + * Actor Function to boot symfony with a specific bundle configuration + * + * @param string $configuration + */ + public function haveABootedSymfonyConfiguration(string $configuration) + { + $this->kernelHasCustomConfig = true; + $this->clearCache(); + $this->bootKernelWithConfiguration($configuration); + } +} + diff --git a/tests/_support/Helper/PimcoreUser.php b/tests/_support/Helper/PimcoreUser.php new file mode 100644 index 0000000..888942d --- /dev/null +++ b/tests/_support/Helper/PimcoreUser.php @@ -0,0 +1,125 @@ +createUser($username, false); + $this->assertInstanceOf(User::class, $user); + + return $user; + } + + /** + * Actor Function to create a Admin User + * + * @param $username + * + * @return User + */ + public function haveAUserWithAdminRights($username) + { + $user = $this->createUser($username, true); + $this->assertInstanceOf(User::class, $user); + + return $user; + } + + /** + * API Function to get a User + * + * @param string $username + * + * @return User + */ + public function getUser($username) + { + if (isset($this->users[$username])) { + return $this->users[$username]; + } + + throw new \InvalidArgumentException(sprintf('User %s does not exist', $username)); + } + + /** + * API Function to create a User + * + * @param string $username + * @param bool $admin + * + * @return null|User|User\AbstractUser + */ + protected function createUser($username, $admin = true) + { + if (!TestHelper::supportsDbTests()) { + $this->debug(sprintf('[PIMCORE USER MODULE] Not initializing user %s as DB is not connected', $username)); + return null; + } else { + $this->debug(sprintf('[PIMCORE USER MODULE] Initializing user %s', $username)); + } + + $password = $username; + + $user = null; + + try { + $user = User::getByName($username); + } catch (\Exception $e) { + // fail silently + } + + if ($user instanceof User) { + return $user; + } + + $this->debug(sprintf('[PIMCORE USER MODULE] Creating user %s', $username)); + + $pass = null; + + try { + $pass = Authentication::getPasswordHash($username, $password); + } catch (\Exception $e) { + // fail silently. + } + + $user = User::create([ + 'parentId' => 0, + 'username' => $username, + 'password' => $pass, + 'active' => true, + 'admin' => $admin + ]); + + $this->users[$user->getName()] = $user; + + return $user; + } +} diff --git a/tests/_support/Helper/Unit.php b/tests/_support/Helper/Unit.php new file mode 100644 index 0000000..c698ec2 --- /dev/null +++ b/tests/_support/Helper/Unit.php @@ -0,0 +1,16 @@ +getPimcoreBundle()->getContainer(); + } + + /** + * @return PimcoreCore + * @throws \Codeception\Exception\ModuleException + */ + protected function getPimcoreBundle() + { + return $this->getModule('\\' . PimcoreCore::class); + } +} diff --git a/tests/_support/UnitTester.php b/tests/_support/UnitTester.php new file mode 100644 index 0000000..def75bd --- /dev/null +++ b/tests/_support/UnitTester.php @@ -0,0 +1,13 @@ +exists($dataDir . 'generated')) { + $fs->mkdir($dataDir . 'generated'); + } + + if (!$fs->exists($dataDir . 'downloads')) { + $fs->mkdir($dataDir . 'downloads'); + } + } + + /** + * @return string + */ + public static function getStoragePath() + { + $dataDir = codecept_data_dir() . 'generated' . DIRECTORY_SEPARATOR; + return $dataDir; + } + + /** + * @return string + */ + public static function getDownloadPath() + { + $dataDir = codecept_data_dir() . 'downloads' . DIRECTORY_SEPARATOR; + return $dataDir; + } + + public static function cleanUp() + { + $finder = new Finder(); + $fs = new Filesystem(); + + $dataDir = self::getStoragePath(); + if ($fs->exists($dataDir)) { + $fs->remove($finder->ignoreDotFiles(true)->in($dataDir)); + } + + $downloadDir = self::getDownloadPath(); + if ($fs->exists($downloadDir)) { + $fs->remove($finder->ignoreDotFiles(true)->in($downloadDir)); + } + } +} diff --git a/tests/_support/Util/SearchHelper.php b/tests/_support/Util/SearchHelper.php new file mode 100644 index 0000000..a2a5dba --- /dev/null +++ b/tests/_support/Util/SearchHelper.php @@ -0,0 +1,33 @@ +setCondition('id != 1'); + $docList->setUnpublished(true); + + foreach ($docList->getDocuments() as $document) { + \Codeception\Util\Debug::debug('[SEARCH] Deleting document: ' . $document->getKey()); + $document->delete(); + } + + // remove all sites (pimcore < 5.6) + $db = \Pimcore\Db::get(); + $availableSites = $db->fetchAll('SELECT * FROM sites'); + if (is_array($availableSites)) { + foreach ($availableSites as $availableSite) { + $db->delete('sites', ['id' => $availableSite['id']]); + } + } + } +} diff --git a/tests/_support/Util/VersionHelper.php b/tests/_support/Util/VersionHelper.php new file mode 100644 index 0000000..0af2eba --- /dev/null +++ b/tests/_support/Util/VersionHelper.php @@ -0,0 +1,64 @@ +'); + } + + /** + * @param string $version + * + * @return mixed + */ + public static function pimcoreVersionIsGreaterOrEqualThan(string $version) + { + return version_compare(self::getPimcoreVersion(), $version, '>='); + } + + /** + * @param string $version + * + * @return mixed + */ + public static function pimcoreVersionIsLowerThan(string $version) + { + return version_compare(self::getPimcoreVersion(), $version, '<'); + } + + /** + * @param string $version + * + * @return mixed + */ + public static function pimcoreVersionIsLowerOrEqualThan(string $version) + { + return version_compare(self::getPimcoreVersion(), $version, '<='); + } + + /** + * @return string + */ + private static function getPimcoreVersion() + { + return preg_replace('/[^0-9.]/', '', \Pimcore\Version::getVersion()); + } +} diff --git a/tests/_support/_boot/kernelBuilder.php b/tests/_support/_boot/kernelBuilder.php new file mode 100644 index 0000000..728d856 --- /dev/null +++ b/tests/_support/_boot/kernelBuilder.php @@ -0,0 +1,19 @@ +activatesKernelDebugMode($environment); + +if ($debug) { + Debug::enable(); + @ini_set('display_errors', 'On'); +} + +$kernel = new \DachcomBundle\Test\App\TestAppKernel($environment, $debug); + +return $kernel; diff --git a/tests/functional.suite.dist.yml b/tests/functional.suite.dist.yml new file mode 100644 index 0000000..4736c47 --- /dev/null +++ b/tests/functional.suite.dist.yml @@ -0,0 +1,12 @@ +actor: FunctionalTester +modules: + enabled: + - \DachcomBundle\Test\Helper\PimcoreCore: + connect_db: true + rebootable_client: true + - \DachcomBundle\Test\Helper\PimcoreBundleCore: + run_installer: true + - \DachcomBundle\Test\Helper\Browser\PhpBrowser: + depends: \DachcomBundle\Test\Helper\PimcoreCore + - \DachcomBundle\Test\Helper\PimcoreBackend + - \DachcomBundle\Test\Helper\PimcoreUser diff --git a/tests/functional/_bootstrap.php b/tests/functional/_bootstrap.php new file mode 100644 index 0000000..94bf66c --- /dev/null +++ b/tests/functional/_bootstrap.php @@ -0,0 +1,2 @@ +