diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000..bbf17a4 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,33 @@ +name: Tests + +on: + push: + branches: + - 'master' + - '[0-9].[0-9]+' + pull_request: ~ + +jobs: + tests: + name: ${{ matrix.php }} / ${{ matrix.phpunit }} + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php: ['8.1'] + phpunit: ['phpunit.xml', 'phpunit-integration-legacy.xml'] + + steps: + - uses: actions/checkout@v2 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + + - run: composer --version + - run: composer validate --strict + + - run: composer update --prefer-dist + + - run: vendor/bin/phpunit -c ${{ matrix.phpunit }} --colors=always diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a7419cc --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/vendor/ +composer.lock +.phpunit.result.cache +.php-cs-fixer.cache +var diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..67a1ab7 --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,56 @@ +in(__DIR__) + ->exclude(['var', 'vendor']) + ->files()->name('*.php') +; + +$config = new PhpCsFixer\Config(); +return $config + ->setRules([ + '@PSR12' => true, + '@PSR12:risky' => true, + '@PhpCsFixer' => true, + '@PhpCsFixer:risky' => true, + + // Overrides for rules included in PhpCsFixer rule sets + 'concat_space' => ['spacing' => 'one'], + 'method_chaining_indentation' => false, + 'multiline_whitespace_before_semicolons' => false, + 'native_function_invocation' => ['include' => ['@all']], + 'no_superfluous_phpdoc_tags' => false, + 'no_unset_on_property' => false, + 'ordered_imports' => ['imports_order' => ['class', 'function', 'const'], 'sort_algorithm' => 'alpha'], + 'php_unit_internal_class' => false, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'php_unit_test_class_requires_covers' => false, + 'phpdoc_align' => false, + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + 'single_line_comment_style' => false, + 'trailing_comma_in_multiline' => ['elements' => ['arrays', 'arguments']], + 'yoda_style' => false, + 'php_unit_strict' => false, + 'php_unit_test_annotation' => false, + + // Additional rules + 'return_assignment' => false, + 'date_time_immutable' => true, + 'declare_strict_types' => true, + 'global_namespace_import' => [ + 'import_classes' => null, + 'import_constants' => true, + 'import_functions' => true, + ], + 'list_syntax' => ['syntax' => 'short'], + 'heredoc_indentation' => ['indentation' => 'same_as_start'], + 'mb_str_functions' => true, + 'native_constant_invocation' => true, + 'nullable_type_declaration_for_default_null_value' => true, + 'static_lambda' => true, + 'ternary_to_null_coalescing' => true, + 'use_arrow_functions' => true, + ]) + ->setRiskyAllowed(true) + ->setFinder($finder) +; diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md index e95cc8b..cda0359 100644 --- a/README.md +++ b/README.md @@ -1 +1,24 @@ -# ibexa-scheduled-visibility +# Netgen's Ibexa Scheduled Visibility + +**Netgen's Ibexa Scheduled Visibility** enables scheduled publishing of content +based on ``publish_from`` and ``publish_to`` fields and further configuration. + +## Installation + +To install Ibexa CMS Scheduled Visibility first add it as a dependency to your project: + +```sh +composer require netgen/ibexa-scheduled-visibility:^1.0 +``` + +Once the added dependency is installed, activate the bundle in `config/bundles.php` file by adding it to the returned array, together with other required bundles: + +```php + ['all' => true], +} +``` diff --git a/bundle/Command/ScheduledVisibilityUpdateCommand.php b/bundle/Command/ScheduledVisibilityUpdateCommand.php new file mode 100644 index 0000000..d6dd702 --- /dev/null +++ b/bundle/Command/ScheduledVisibilityUpdateCommand.php @@ -0,0 +1,251 @@ +setDescription( + 'Updates content visibility based on publish_from and publish_to attributes and configuration.', + ); + $this->addOption( + 'limit', + 'l', + InputOption::VALUE_OPTIONAL, + 'Number of content objects to process in a single iteration', + 1024, + ); + } + + protected function initialize(InputInterface $input, OutputInterface $output): void + { + $this->style = new SymfonyStyle($input, $output); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->style->info( + 'This command fetches content and updates visibility based on its schedule from publish_from and publish_to fields.', + ); + + $question = new ConfirmationQuestion( + 'Continue with this action?', + true, + '/^(y)/i', + ); + + if (!$this->style->askQuestion($question)) { + $this->style->success('Aborted'); + + return Command::SUCCESS; + } + + if (!$this->configurationService->isEnabled()) { + $this->style->warning('Scheduled visibility mechanism is disabled.'); + + return Command::FAILURE; + } + + $allContentTypes = $this->configurationService->isAllContentTypes(); + $allowedContentTypes = $this->configurationService->getAllowedContentTypes(); + + if (!$allContentTypes && count($allowedContentTypes) === 0) { + $this->style->warning('No content types configured for scheduled visibility mechanism.'); + + return Command::FAILURE; + } + + $pager = $this->getPager($allContentTypes, $allowedContentTypes); + + if ($pager->getNbResults() === 0) { + $this->style->info('No content found'); + + return Command::FAILURE; + } + + $limit = $input->getOption('limit'); + $offset = 0; + + $progressBar = $this->style->createProgressBar($pager->getNbResults()); + $progressBar->setFormat('debug'); + $progressBar->start(); + + $results = $pager->getAdapter()->getSlice($offset, $limit); + while (count($results) > 0) { + $this->processResults($results, $progressBar); + $offset += $limit; + $results = $pager->getAdapter()->getSlice($offset, $limit); + } + + $progressBar->finish(); + + $this->style->info('Done.'); + + return Command::SUCCESS; + } + + private function processResults(array $results, ProgressBar $progressBar): void + { + foreach ($results as $result) { + try { + $languageId = $result['initial_language_id']; + $language = $this->loadLanguage($languageId); + } catch (NotFoundException $exception) { + $this->logger->error( + sprintf( + 'Language with id #%d does not exist: %s', + $languageId, + $exception->getMessage(), + ), + ); + + $progressBar->advance(); + + continue; + } + + try { + $contentId = $result['id']; + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Content $content */ + $content = $this->repository->sudo( + fn () => $this->repository->getContentService()->loadContent( + $contentId, + [$language->getLanguageCode()], + ), + ); + } catch (NotFoundException $exception) { + $this->logger->error( + sprintf( + 'Content with id #%d does not exist: %s', + $contentId, + $exception->getMessage(), + ), + ); + + $progressBar->advance(); + + continue; + } + + try { + $this->scheduledVisibilityService->updateVisibilityIfNeeded($content); + } catch (InvalidStateException $exception) { + $this->logger->error($exception->getMessage()); + } + + $progressBar->advance(); + } + } + + private function getQueryBuilder(): QueryBuilder + { + $query = $this->connection->createQueryBuilder(); + $query + ->select('id', 'initial_language_id') + ->from('ezcontentobject') + ->where('published != :unpublished') + ->orderBy('id', 'ASC') + ->setParameter('unpublished', 0); + + return $query; + } + + private function applyContentTypeLimit(QueryBuilder $query, array $contentTypeIds): void + { + $query->where( + $query->expr()->in('contentclass_id', ':content_type_ids'), + )->setParameter('content_type_ids', $contentTypeIds, Connection::PARAM_INT_ARRAY); + } + + private function getPager(bool $allContentTypes, array $allowedContentTypes): Pagerfanta + { + $query = $this->getQueryBuilder(); + + $contentTypeIds = []; + if (!$allContentTypes && count($allowedContentTypes) > 0) { + foreach ($allowedContentTypes as $allowedContentType) { + try { + $contentTypeIds[] = $this->repository->getContentTypeService()->loadContentTypeByIdentifier($allowedContentType)->id; + } catch (NotFoundException $exception) { + $this->logger->error( + sprintf( + "Content type with identifier '%s' does not exist: %s", + $allowedContentType, + $exception->getMessage(), + ), + ); + + continue; + } + } + } + + if (count($contentTypeIds) > 0) { + $this->applyContentTypeLimit($query, $contentTypeIds); + } + + $countQueryBuilderModifier = function (QueryBuilder $queryBuilder) use ($contentTypeIds): void { + $queryBuilder->select('COUNT(id) AS total_results') + ->from('ezcontentobject') + ->where('published != :unpublished') + ->setParameter('unpublished', 0) + ->setMaxResults(1); + + if (count($contentTypeIds) > 0) { + $this->applyContentTypeLimit($queryBuilder, $contentTypeIds); + } + }; + + return new Pagerfanta(new QueryAdapter($query, $countQueryBuilderModifier)); + } + + private function loadLanguage(int $id): Language + { + if (!isset($this->languageCache[$id])) { + $language = $this->repository->getContentLanguageService()->loadLanguageById($id); + $this->languageCache[$id] = $language; + } + + return $this->languageCache[$id]; + } +} diff --git a/bundle/Core/Configuration.php b/bundle/Core/Configuration.php new file mode 100644 index 0000000..b81f8a1 --- /dev/null +++ b/bundle/Core/Configuration.php @@ -0,0 +1,42 @@ +enabled; + } + + public function isAllContentTypes(): bool + { + return $this->allContentTypes; + } + + public function getAllowedContentTypes(): array + { + return $this->allowedContentTypes; + } + + public function getHandlerIdentifier(): string + { + return $this->handler; + } + + public function isContentTypeAllowed(string $contentType): bool + { + return $this->allContentTypes || in_array($contentType, $this->allowedContentTypes, true); + } +} diff --git a/bundle/Core/Enum/VisibilityUpdateResult.php b/bundle/Core/Enum/VisibilityUpdateResult.php new file mode 100644 index 0000000..774d30d --- /dev/null +++ b/bundle/Core/Enum/VisibilityUpdateResult.php @@ -0,0 +1,14 @@ +getName(), $content->id); + + parent::__construct($message, 0, $previous); + } +} diff --git a/bundle/Core/Registry.php b/bundle/Core/Registry.php new file mode 100644 index 0000000..774866d --- /dev/null +++ b/bundle/Core/Registry.php @@ -0,0 +1,45 @@ + $handler) { + $this->register($identifier, $handler); + } + } + + public function register(string $identifier, VisibilityHandler $handler): void + { + $this->handlerMap[$identifier] = $handler; + } + + /** + * @throws OutOfBoundsException + */ + public function get(?string $identifier): VisibilityHandler + { + return $this->handlerMap[$identifier] ?? throw new OutOfBoundsException( + sprintf( + "No handler is registered for identifier '%s'", + $identifier, + ), + ); + } +} diff --git a/bundle/Core/ScheduledVisibilityService.php b/bundle/Core/ScheduledVisibilityService.php new file mode 100644 index 0000000..de30c2a --- /dev/null +++ b/bundle/Core/ScheduledVisibilityService.php @@ -0,0 +1,173 @@ +registry->get($handlerIdentifier ?? $this->configurationService->getHandlerIdentifier()); + + if ($this->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + + $this->logUpdate($content, VisibilityUpdateResult::Hidden); + + return VisibilityUpdateResult::Hidden; + } + + if ($this->shouldBeVisible($content) && !$handler->isVisible($content)) { + $handler->reveal($content); + + $this->logUpdate($content, VisibilityUpdateResult::Revealed); + + return VisibilityUpdateResult::Revealed; + } + + return VisibilityUpdateResult::NoChange; + } + + /** + * @throws InvalidStateException + */ + public function shouldBeHidden(Content $content): bool + { + if (!$this->isValid($content)) { + throw new InvalidStateException($content); + } + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Field $publishFromField */ + $publishFromField = $content->getField('publish_from'); + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Field $publishToField */ + $publishToField = $content->getField('publish_to'); + + $publishFromDateTime = $this->getDateTime($publishFromField); + $publishToDateTime = $this->getDateTime($publishToField); + + if ($publishToDateTime === null && $publishFromDateTime === null) { + return false; + } + + $currentDateTime = new DateTime(); + + if ($publishFromDateTime !== null && $publishFromDateTime > $currentDateTime) { + return true; + } + + if ($publishToDateTime !== null && $publishToDateTime <= $currentDateTime) { + return true; + } + + return false; + } + + /** + * @throws InvalidStateException + */ + public function shouldBeVisible(Content $content): bool + { + if (!$this->isValid($content)) { + throw new InvalidStateException($content); + } + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Field $publishFromField */ + $publishFromField = $content->getField('publish_from'); + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Field $publishToField */ + $publishToField = $content->getField('publish_to'); + + $publishFromDateTime = $this->getDateTime($publishFromField); + $publishToDateTime = $this->getDateTime($publishToField); + + if ($publishToDateTime === null && $publishFromDateTime === null) { + return false; + } + + $currentDateTime = new DateTime(); + + if ($publishFromDateTime === null && $publishToDateTime > $currentDateTime) { + return true; + } + + if ($publishToDateTime === null && $publishFromDateTime <= $currentDateTime) { + return true; + } + + if ($publishFromDateTime !== null && $publishFromDateTime <= $currentDateTime + && $publishToDateTime !== null && $publishToDateTime > $currentDateTime) { + return true; + } + + return false; + } + + private function isValid(Content $content): bool + { + $publishFromField = $content->getField('publish_from'); + $publishToField = $content->getField('publish_to'); + + if ($publishFromField === null || $publishToField === null) { + return false; + } + + if ( + ($publishFromField->fieldTypeIdentifier !== 'ezdatetime' && $publishFromField->fieldTypeIdentifier !== 'ezdate') + || ($publishToField->fieldTypeIdentifier !== 'ezdatetime' && $publishToField->fieldTypeIdentifier !== 'ezdate') + ) { + return false; + } + + $publishFromDateTime = $this->getDateTime($publishFromField); + $publishToDateTime = $this->getDateTime($publishToField); + if ($publishFromDateTime !== null && $publishToDateTime !== null && $publishToDateTime <= $publishFromDateTime) { + return false; + } + + return true; + } + + private function getDateTime(Field $field): null|DateTime + { + if ($field->value instanceof DateValue) { + return $field->value->date; + } + if ($field->value instanceof DateAndTimeValue) { + return $field->value->value; + } + + return null; + } + + private function logUpdate(Content $content, VisibilityUpdateResult $updateResult): void + { + $this->logger->info( + sprintf( + "Content '%s' with id #%d has been %s.", + $content->getName(), + $content->id, + $updateResult->value, + ), + ); + } +} diff --git a/bundle/Core/VisibilityHandler.php b/bundle/Core/VisibilityHandler.php new file mode 100644 index 0000000..59f75c9 --- /dev/null +++ b/bundle/Core/VisibilityHandler.php @@ -0,0 +1,18 @@ +repository->sudo( + fn () => $this->contentService->hideContent($content->contentInfo), + ); + } + + public function reveal(ContentValue $content): void + { + $this->repository->sudo( + fn () => $this->contentService->revealContent($content->contentInfo), + ); + } + + public function isHidden(ContentValue $content): bool + { + return $content->contentInfo->isHidden; + } + + public function isVisible(ContentValue $content): bool + { + return !$content->contentInfo->isHidden; + } +} diff --git a/bundle/Core/VisibilityHandler/ContentAndLocation.php b/bundle/Core/VisibilityHandler/ContentAndLocation.php new file mode 100644 index 0000000..d0e4665 --- /dev/null +++ b/bundle/Core/VisibilityHandler/ContentAndLocation.php @@ -0,0 +1,40 @@ +contentHandler->hide($content); + $this->locationHandler->hide($content); + } + + public function reveal(Content $content): void + { + $this->contentHandler->reveal($content); + $this->locationHandler->reveal($content); + } + + public function isHidden(Content $content): bool + { + return $this->contentHandler->isHidden($content) && $this->locationHandler->isHidden($content); + } + + public function isVisible(Content $content): bool + { + return $this->contentHandler->isVisible($content) && $this->locationHandler->isVisible($content); + } +} diff --git a/bundle/Core/VisibilityHandler/Location.php b/bundle/Core/VisibilityHandler/Location.php new file mode 100644 index 0000000..76911d5 --- /dev/null +++ b/bundle/Core/VisibilityHandler/Location.php @@ -0,0 +1,65 @@ +repository->sudo( + function () use ($content): void { + $locations = $this->locationService->loadLocations($content->contentInfo); + + foreach ($locations as $location) { + $this->locationService->hideLocation($location); + } + }, + ); + } + + public function reveal(Content $content): void + { + $this->repository->sudo( + function () use ($content): void { + $locations = $this->locationService->loadLocations($content->contentInfo); + + foreach ($locations as $location) { + $this->locationService->unhideLocation($location); + } + }, + ); + } + + public function isHidden(Content $content): bool + { + return !$this->isVisible($content); + } + + public function isVisible(Content $content): bool + { + $locations = $this->repository->sudo( + fn () => $this->locationService->loadLocations($content->contentInfo), + ); + + /** @var \Ibexa\Contracts\Core\Repository\Values\Content\Location $location */ + foreach ($locations as $location) { + if ($location->hidden) { + return false; + } + } + + return true; + } +} diff --git a/bundle/Core/VisibilityHandler/ObjectState.php b/bundle/Core/VisibilityHandler/ObjectState.php new file mode 100644 index 0000000..ec08c8e --- /dev/null +++ b/bundle/Core/VisibilityHandler/ObjectState.php @@ -0,0 +1,80 @@ +hiddenObjectStateId; + + $this->setObjectState($content, $hiddenObjectStateId); + } + + public function reveal(Content $content): void + { + $visibleObjectStateId = $this->visibleObjectStateId; + + $this->setObjectState($content, $visibleObjectStateId); + } + + public function isHidden(Content $content): bool + { + $objectState = $this->getObjectState($content); + + return $this->hiddenObjectStateId === $objectState->id; + } + + public function isVisible(Content $content): bool + { + $objectState = $this->getObjectState($content); + + return $this->visibleObjectStateId === $objectState->id; + } + + private function setObjectState(Content $content, int $objectStateId): void + { + $this->repository->sudo( + function () use ($content, $objectStateId): void { + $objectState = $this->objectStateService->loadObjectState($objectStateId); + + $objectStateGroup = $objectState->getObjectStateGroup(); + + $this->objectStateService->setContentState( + $content->contentInfo, + $objectStateGroup, + $objectState, + ); + }, + ); + } + + private function getObjectState(Content $content): ObjectStateValue + { + $objectStateGroupId = $this->objectStateGroupId; + + return $this->repository->sudo( + function () use ($content, $objectStateGroupId): ObjectStateValue { + $objectStateGroup = $this->objectStateService->loadObjectStateGroup($objectStateGroupId); + + return $this->objectStateService->getContentState($content->contentInfo, $objectStateGroup); + }, + ); + } +} diff --git a/bundle/Core/VisibilityHandler/Section.php b/bundle/Core/VisibilityHandler/Section.php new file mode 100644 index 0000000..e77a09b --- /dev/null +++ b/bundle/Core/VisibilityHandler/Section.php @@ -0,0 +1,55 @@ +hiddenSectionId; + + $this->assignSection($content, $hiddenSectionId); + } + + public function reveal(Content $content): void + { + $visibleSectionId = $this->visibleSectionId; + + $this->assignSection($content, $visibleSectionId); + } + + public function isHidden(Content $content): bool + { + return $content->contentInfo->sectionId === $this->hiddenSectionId; + } + + public function isVisible(Content $content): bool + { + return $content->contentInfo->sectionId === $this->visibleSectionId; + } + + private function assignSection(Content $content, int $sectionId): void + { + $this->repository->sudo( + function () use ($content, $sectionId): void { + $section = $this->sectionService->loadSection($sectionId); + + $this->sectionService->assignSection($content->contentInfo, $section); + }, + ); + } +} diff --git a/bundle/DependencyInjection/Compiler/ScheduledVisibilityHandlerRegistrationPass.php b/bundle/DependencyInjection/Compiler/ScheduledVisibilityHandlerRegistrationPass.php new file mode 100644 index 0000000..84e0929 --- /dev/null +++ b/bundle/DependencyInjection/Compiler/ScheduledVisibilityHandlerRegistrationPass.php @@ -0,0 +1,59 @@ +has($this->handlerRegistryId)) { + return; + } + + $handlerRegistryDefinition = $container->getDefinition($this->handlerRegistryId); + + $handlers = $container->findTaggedServiceIds($this->handlerTag); + + foreach ($handlers as $id => $attributes) { + $this->registerHandler($handlerRegistryDefinition, $id, $attributes); + } + } + + /** + * @throws LogicException + */ + private function registerHandler(Definition $handlerRegistryDefinition, string $id, array $attributes): void + { + foreach ($attributes as $attribute) { + if (!isset($attribute['identifier'])) { + throw new LogicException( + sprintf( + "'%s' service tag needs an 'identifier' attribute to identify the handler", + $this->handlerTag, + ), + ); + } + + $handlerRegistryDefinition->addMethodCall( + 'register', + [ + $attribute['identifier'], + new Reference($id), + ], + ); + } + } +} diff --git a/bundle/DependencyInjection/Configuration.php b/bundle/DependencyInjection/Configuration.php new file mode 100644 index 0000000..62305de --- /dev/null +++ b/bundle/DependencyInjection/Configuration.php @@ -0,0 +1,144 @@ +rootNodeName = $rootNodeName; + } + + public function getConfigTreeBuilder(): TreeBuilder + { + $treeBuilder = new TreeBuilder($this->rootNodeName); + $rootNode = $treeBuilder->getRootNode(); + + $this->addEnabled($rootNode); + $this->addHandlerSection($rootNode); + $this->addContentTypesSection($rootNode); + $this->addSectionsSection($rootNode); + $this->addObjectStatesSection($rootNode); + + return $treeBuilder; + } + + private function addEnabled(ArrayNodeDefinition $nodeDefinition): void + { + $nodeDefinition + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => false]) + ->children() + ->booleanNode('enabled') + ->defaultFalse() + ->end() + ->end(); + } + + private function addHandlerSection(ArrayNodeDefinition $nodeDefinition): void + { + $nodeDefinition + ->children() + ->scalarNode('handler') + ->info('Configure handler for scheduled visibility mechanism') + ->defaultValue('content') + ->end() + ->end(); + } + + private function addContentTypesSection(ArrayNodeDefinition $nodeDefinition): void + { + $nodeDefinition + ->children() + ->arrayNode('content_types') + ->info('Configure content_types used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => false]) + ->children() + ->booleanNode('all') + ->defaultFalse() + ->end() + ->arrayNode('allowed') + ->scalarPrototype() + ->end() + ->end() + ->end() + ->end(); + } + + private function addSectionsSection(ArrayNodeDefinition $nodeDefinition): void + { + $nodeDefinition + ->children() + ->arrayNode('sections') + ->info('Configure sections used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->arrayNode('visible') + ->info('Configure visible section id used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('section_id') + ->defaultValue(0) + ->end() + ->end() + ->end() + ->arrayNode('hidden') + ->info('Configure hidden section id used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('section_id') + ->defaultValue(0) + ->end() + ->end() + ->end() + ->end() + ->end() + ->end(); + } + + private function addObjectStatesSection(ArrayNodeDefinition $nodeDefinition): void + { + $nodeDefinition + ->children() + ->arrayNode('object_states') + ->info('Configure object_states used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('object_state_group_id') + ->defaultValue(0) + ->end() + ->arrayNode('visible') + ->info('Configure visible object states and groups used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('object_state_id') + ->defaultValue(0) + ->end() + ->end() + ->end() + ->arrayNode('hidden') + ->info('Configure hidden bject states and groups used for scheduled visibility mechanism') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('object_state_id') + ->defaultValue(0) + ->end() + ->end() + ->end() + ->end() + ->end() + ->end(); + } +} diff --git a/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityExtension.php b/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityExtension.php new file mode 100644 index 0000000..f074ca9 --- /dev/null +++ b/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityExtension.php @@ -0,0 +1,105 @@ +getAlias()); + } + + public function load(array $configs, ContainerBuilder $container): void + { + $loader = new Loader\YamlFileLoader( + $container, + new FileLocator(__DIR__ . '/../../bundle/Resources/config/'), + ); + + $loader->load('services.yaml'); + $loader->load('default_settings.yaml'); + + $this->processExtensionConfiguration($configs, $container); + } + + private function processExtensionConfiguration(array $configs, ContainerBuilder $container): void + { + $configuration = $this->getConfiguration($configs, $container); + + $configuration = $this->processConfiguration($configuration, $configs); + + $this->processEnabledConfiguration($configuration, $container); + $this->processHandlerConfiguration($configuration, $container); + $this->processContentTypesConfiguration($configuration, $container); + $this->processSectionsConfiguration($configuration, $container); + $this->processObjectStatesConfiguration($configuration, $container); + } + + private function processEnabledConfiguration(array $configuration, ContainerBuilder $container): void + { + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.enabled', + $configuration['enabled'], + ); + } + + private function processHandlerConfiguration(array $configuration, ContainerBuilder $container): void + { + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.handler', + $configuration['handler'], + ); + } + + private function processContentTypesConfiguration(array $configuration, ContainerBuilder $container): void + { + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.content_types.all', + $configuration['content_types']['all'], + ); + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.content_types.allowed', + $configuration['content_types']['allowed'], + ); + } + + private function processSectionsConfiguration(array $configuration, ContainerBuilder $container): void + { + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.sections.visible.section_id', + $configuration['sections']['visible']['section_id'], + ); + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.sections.hidden.section_id', + $configuration['sections']['hidden']['section_id'], + ); + } + + private function processObjectStatesConfiguration(array $configuration, ContainerBuilder $container): void + { + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.object_states.object_state_group_id', + $configuration['object_states']['object_state_group_id'], + ); + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.object_states.visible.object_state_id', + $configuration['object_states']['visible']['object_state_id'], + ); + $container->setParameter( + 'netgen_ibexa_scheduled_visibility.object_states.hidden.object_state_id', + $configuration['object_states']['hidden']['object_state_id'], + ); + } +} diff --git a/bundle/EventListener/ScheduledVisibilityListener.php b/bundle/EventListener/ScheduledVisibilityListener.php new file mode 100644 index 0000000..5a4426f --- /dev/null +++ b/bundle/EventListener/ScheduledVisibilityListener.php @@ -0,0 +1,47 @@ + ['onPublishVersion'], + ]; + } + + public function onPublishVersion(PublishVersionEvent $event): void + { + if (!$this->configurationService->isEnabled()) { + return; + } + + $content = $event->getContent(); + if (!$this->configurationService->isContentTypeAllowed($content->getContentType()->identifier)) { + return; + } + + try { + $this->scheduledVisibilityService->updateVisibilityIfNeeded($content); + } catch (InvalidStateException $exception) { + $this->logger->error($exception->getMessage()); + } + } +} diff --git a/bundle/NetgenIbexaScheduledVisibilityBundle.php b/bundle/NetgenIbexaScheduledVisibilityBundle.php new file mode 100644 index 0000000..16caecd --- /dev/null +++ b/bundle/NetgenIbexaScheduledVisibilityBundle.php @@ -0,0 +1,19 @@ +addCompilerPass(new ScheduledVisibilityHandlerRegistrationPass()); + } +} diff --git a/bundle/Resources/config/default_settings.yaml b/bundle/Resources/config/default_settings.yaml new file mode 100644 index 0000000..34092a7 --- /dev/null +++ b/bundle/Resources/config/default_settings.yaml @@ -0,0 +1,10 @@ +parameters: + netgen_ibexa_scheduled_visibility.enabled: false + netgen_ibexa_scheduled_visibility.handler: 'content' + netgen_ibexa_scheduled_visibility.content_types.all: false + netgen_ibexa_scheduled_visibility.content_types.allowed: [] + netgen_ibexa_scheduled_visibility.sections.hidden.section_id: 0 + netgen_ibexa_scheduled_visibility.sections.visible.section_id: 0 + netgen_ibexa_scheduled_visibility.object_states.object_state_group_id: 0 + netgen_ibexa_scheduled_visibility.object_states.hidden.object_state_id: 0 + netgen_ibexa_scheduled_visibility.object_states.visible.object_state_id: 0 diff --git a/bundle/Resources/config/services.yaml b/bundle/Resources/config/services.yaml new file mode 100644 index 0000000..fbd3d99 --- /dev/null +++ b/bundle/Resources/config/services.yaml @@ -0,0 +1,77 @@ +services: + Netgen\Bundle\IbexaScheduledVisibilityBundle\EventListener\ScheduledVisibilityListener: + arguments: + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\ScheduledVisibilityService' + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Configuration' + - '@?logger' + tags: + - { name: kernel.event_subscriber } + - { name: monolog.logger, channel: ngscheduledvisibility } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Configuration: + arguments: + - '%netgen_ibexa_scheduled_visibility.handler%' + - '%netgen_ibexa_scheduled_visibility.enabled%' + - '%netgen_ibexa_scheduled_visibility.content_types.all%' + - '%netgen_ibexa_scheduled_visibility.content_types.allowed%' + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\ScheduledVisibilityService: + arguments: + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Configuration' + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Registry' + - '@?logger' + tags: + - { name: monolog.logger, channel: ngscheduledvisibility } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Registry: + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Content: + arguments: + - '@ibexa.api.repository' + - '@ibexa.api.service.content' + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: content } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Location: + arguments: + - '@ibexa.api.repository' + - '@ibexa.api.service.location' + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: location } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\ContentAndLocation: + arguments: + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Content' + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Location' + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: content_location } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Section: + arguments: + - '@ibexa.api.repository' + - '@ibexa.api.service.section' + - '%netgen_ibexa_scheduled_visibility.sections.hidden.section_id%' + - '%netgen_ibexa_scheduled_visibility.sections.visible.section_id%' + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: section } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\ObjectState: + arguments: + - '@ibexa.api.repository' + - '@ibexa.api.service.object_state' + - '%netgen_ibexa_scheduled_visibility.object_states.object_state_group_id%' + - '%netgen_ibexa_scheduled_visibility.object_states.hidden.object_state_id%' + - '%netgen_ibexa_scheduled_visibility.object_states.visible.object_state_id%' + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: object_state } + + Netgen\Bundle\IbexaScheduledVisibilityBundle\Command\ScheduledVisibilityUpdateCommand: + arguments: + - '@ibexa.api.repository' + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\ScheduledVisibilityService' + - '@Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\Configuration' + - '@ibexa.persistence.connection' + - '@?logger' + tags: + - { name: console.command, command: 'ngscheduledvisibility:update' } + - { name: monolog.logger, channel: ngscheduledvisibility } diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b98f8ad --- /dev/null +++ b/composer.json @@ -0,0 +1,40 @@ +{ + "name": "netgen/ibexa-scheduled-visibility", + "description": "Netgen's scheduled visibility mechanism for Ibexa CMS", + "type": "ibexa-bundle", + "license": "GPL-2.0-only", + "authors": [ + { + "name": "Netgen", + "homepage": "https://netgen.io" + } + ], + "require": { + "php": ">=8.1", + "ibexa/core": "^4.5" + }, + "require-dev": { + "phpunit/phpunit": "^10", + "matthiasnoback/symfony-dependency-injection-test": "^4.1" + }, + "minimum-stability": "dev", + "prefer-stable": true, + "autoload": { + "psr-4": { + "Netgen\\Bundle\\IbexaScheduledVisibilityBundle\\": "bundle" + } + }, + "autoload-dev": { + "psr-4": { + "Netgen\\IbexaScheduledVisibility\\Tests\\": "tests/bundle" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "scripts": { + "test": "@php vendor/bin/phpunit --colors=always" + } +} diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..90f2358 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = NetgenContentBrowser +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..2f182ec --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +import sys, os +import sphinx_rtd_theme + +from sphinx.highlighting import lexers +from pygments.lexers.web import PhpLexer +from pygments.lexers.web import HtmlLexer +from pygments.lexers.web import JsonLexer + +from datetime import datetime + +lexers['php'] = PhpLexer(startinline=True) +lexers['php-annotations'] = PhpLexer(startinline=True) +lexers['html'] = HtmlLexer(startinline=True) +lexers['json'] = JsonLexer(startinline=True) + +extensions = ['sphinx.ext.autodoc', + 'sphinx_copybutton', + 'sphinx.ext.doctest', + 'sphinx.ext.todo', + 'sphinx.ext.coverage', + 'sphinx.ext.imgmath', + 'sphinx.ext.ifconfig', + 'sensio.sphinx.configurationblock'] + +source_suffix = '.rst' +master_doc = 'index' + +project = 'Netgen\'s Scheduled Visibility for Ibexa CMS' +copyright = 'Netgen' +author = 'Netgen' + +version = '' +release = '' + +exclude_patterns = ['_build', '.virtualenvs'] + +html_theme = "sphinx_rtd_theme" +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +html_static_path = ['_static'] +templates_path = ['_templates'] + +html_theme_options = { + 'collapse_navigation': True, + 'display_version': True, +} + +html_context = { + 'copyright_url': 'https://netgen.io', + 'current_year': datetime.utcnow().year +} + +def setup(app): + app.add_stylesheet("css/style.css") diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..9314775 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,15 @@ +Netgen's Scheduled Visibility for Ibexa CMS +=========================================== + +Ibexa Scheduled Visibility enables scheduled publishing of content +based on ``publish_from`` and ``publish_to`` fields and further configuration. + +Reference +--------- + +.. toctree:: + :hidden: + + reference/index + +.. include:: /reference/map.rst.inc diff --git a/docs/reference/configuration.rst b/docs/reference/configuration.rst new file mode 100644 index 0000000..fcd99c1 --- /dev/null +++ b/docs/reference/configuration.rst @@ -0,0 +1,115 @@ +Configuration +============= + +.. contents:: + :depth: 1 + :local: + +Default configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + enabled: false + handler: 'content' + content_types: + all: false + allowed: [] + sections: + visible: + section_id: 0 + hidden: + section_id: 0 + object_states: + object_state_group_id: 0 + visible: + object_state_id: 0 + hidden: + object_state_id: 0 + +Enabling scheduled visibility +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In order to use Ibexa scheduled visibility, you have to enable it: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + enabled: true + +Changing visibility handlers: +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In order to change :doc:`visibility handler `, +you need to set it to one of supported ones: +**'content'**, **'location'**, **'content_location'**, **'section'**, **'object_state'** +or create your own :ref:`custom handler`: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + handler: 'section' + +Content type limitations +~~~~~~~~~~~~~~~~~~~~~~~~ + +In order to include all content types in scheduled visibility mechanism you need to enable it: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + content_types: + all: true + +In order to limit content types you need to disable previously mentioned setting for all content types +and enter content types to be included in scheduled visibility mechanism: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + content_types: + all: false + allowed: ['content_type_1', 'content_type_2'] + +.. _section_configuration: + +Section handler configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If :ref:`'section'` has been chosen as preferred visibility handler, +ids of sections used for visible and hidden content need to be configured: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + handler: 'section' + sections: + visible: + section_id: 1 + hidden: + section_id: 2 + +.. _object_state_configuration: + +Object state handler configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If :ref:`'object_state'` has been chosen as preferred visibility handler, +ids of object states used for visible and hidden content need to be configured, +as well as object state group id in which both of these states are: + +.. code-block:: yaml + + netgen_ibexa_scheduled_visibility: + handler: 'object_state' + object_states: + object_state_group_id: 1 + visible: + object_state_id: 1 + hidden: + object_state_id: 2 + +.. note:: + + Both object states must be in the configured object state group. diff --git a/docs/reference/index.rst b/docs/reference/index.rst new file mode 100644 index 0000000..317532f --- /dev/null +++ b/docs/reference/index.rst @@ -0,0 +1,12 @@ +Reference +========= + +.. toctree:: + :hidden: + + installation + configuration + visibility_handling + usage + +.. include:: /reference/map.rst.inc diff --git a/docs/reference/installation.rst b/docs/reference/installation.rst new file mode 100644 index 0000000..35c670e --- /dev/null +++ b/docs/reference/installation.rst @@ -0,0 +1,20 @@ +Installation +============ + +To install Ibexa CMS Scheduled Visibility first add it as a dependency to your project: + +.. code-block:: shell + + $ composer require netgen/ibexa-scheduled-visibility:^1.0 + +Once the added dependency is installed, activate the bundle in ``config/bundles.php`` file by adding it to the returned array, together with other required bundles: + +.. code-block:: php + + ['all' => true], + } diff --git a/docs/reference/map.rst.inc b/docs/reference/map.rst.inc new file mode 100644 index 0000000..6d0d813 --- /dev/null +++ b/docs/reference/map.rst.inc @@ -0,0 +1,4 @@ +* :doc:`/reference/installation` +* :doc:`/reference/configuration` +* :doc:`/reference/visibility_handling` +* :doc:`/reference/usage` diff --git a/docs/reference/usage.rst b/docs/reference/usage.rst new file mode 100644 index 0000000..a76f864 --- /dev/null +++ b/docs/reference/usage.rst @@ -0,0 +1,40 @@ +Usage +===== + +.. contents:: + :depth: 1 + :local: + +Content types +------------- + +For content to be accepted by scheduled visibility mechanism, +its content type must contain two fields that are either ``ezdate`` or ``ezdatetime``. +Identifiers of these fields must be ``publish_from`` and ``published_to``. + +.. warning:: + ``publish_from`` and ``published_to`` fields must not be translatable. + +``publish_from`` +~~~~~~~~~~~~~~~~~~~~ +It represents time from which content becomes visible. +When set to null, content does not have that limit. + +``publish_to`` +~~~~~~~~~~~~~~~~~~~~ +It represents time until content is visible. +When set to null, content does not have that limit. + +When both fields are set to null, no action will be taken. +Naturally, if value of ``publish_from`` field is greater that value of ``publish_to``, +content will not be accepted by the mechanism and no action will be taken. + +Command +------- + +Bundle contains ``ScheduledVisibilityUpdateCommand`` +that searches through configured content and, if necessary, updates its visibility. +Command has a ``limit`` option that represents number of content objects to process in a single iteration. +By default it is set to 1024. +Command can be executed with: ``bin/console ngscheduledvisibility:update``. +For this mechanism to work how it was intended, this command should be set as cron job. diff --git a/docs/reference/visibility_handling.rst b/docs/reference/visibility_handling.rst new file mode 100644 index 0000000..1b09f31 --- /dev/null +++ b/docs/reference/visibility_handling.rst @@ -0,0 +1,73 @@ +Visibility handling +=========================== + +Scheduled visibility comes with several handlers you can use for updating content visibility using +different services from `Ibexa PHP API `_: + +.. contents:: + :depth: 1 + :local: + +Content +------- + +This handler uses +`hideContent() `_ and +`revealContent() `_ methods from +`ContentService `_. +It hides Content by making all the Locations appear hidden but does not persist hidden state on Location object/s. + +Location +-------- + +This handler uses +`hideLocation() `_ and +`unhideLocation() `_ methods from +`LocationService `_. +It hides the Location and marks invisible all descendants of Location. + +Content and Location +-------------------- + +This handler uses +`hideContent() `_ and +`revealContent() `_ methods from +`ContentService `_ and +`hideLocation() `_ and +`unhideLocation() `_ methods from +`LocationService `_. +It does combined actions of Content and Location handlers mentioned above. + +.. _section_handler: + +Section +------- + +This handler uses `SectionService `_ +and its method `assignSection() `_. +Content that is supposed to become hidden or visible will be assigned to :ref:`configured` sections. + +.. _object_state_handler: + +Object state +------------ + +This handler uses `ObjectStateService `_ +and its method `setContentState() `_. +Content that is supposed to be hidden or visible will be assigned to :ref:`configured` object states in object state group. + +.. note:: + + Both object states must be in the configured object state group. + +.. _custom_handler: + +Custom handler +------------ + +Custom handler can be created. It needs to be registered and tagged with: + +.. code-block:: yaml + + tags: + - { name: netgen.ibexa_scheduled_visibility.handler, identifier: custom_identifier } diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..5896d27 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,7 @@ +sphinx>=1.7.4,<2.0 +sphinx_rtd_theme>=0.3.1,<1.0 +sphinx-copybutton==0.2.11 +pathlib +git+https://github.com/fabpot/sphinx-php.git +jinja2<3.1.0 +alabaster<0.7.14 diff --git a/phpunit-integration-legacy.xml b/phpunit-integration-legacy.xml new file mode 100644 index 0000000..5632ef6 --- /dev/null +++ b/phpunit-integration-legacy.xml @@ -0,0 +1,13 @@ + + + + + + + + + ./tests/bundle/Integration/ + ./tests/bundle/Integration/BaseTest.php + + + diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..4925c13 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,8 @@ + + + + + ./tests/bundle/DependencyInjection + + + diff --git a/tests/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityTest.php b/tests/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityTest.php new file mode 100644 index 0000000..c7478cb --- /dev/null +++ b/tests/bundle/DependencyInjection/NetgenIbexaScheduledVisibilityTest.php @@ -0,0 +1,412 @@ +setParameter('kernel.bundles', []); + } + + public static function provideDefaultConfigurationCases(): iterable + { + return [ + [ + [], + ], + [ + [ + 'enabled' => false, + ], + ], + [ + [ + 'enabled' => false, + 'handler' => 'content', + ], + ], + [ + [ + 'enabled' => false, + 'handler' => 'content', + 'sections' => [ + 'visible' => [ + 'section_id' => 0, + ], + 'hidden' => [ + 'section_id' => 0, + ], + ], + ], + ], + [ + [ + 'enabled' => false, + 'handler' => 'content', + 'sections' => [ + 'visible' => [ + 'section_id' => 0, + ], + 'hidden' => [ + 'section_id' => 0, + ], + ], + 'object_states' => [ + 'object_state_group_id' => 0, + 'visible' => [ + 'object_state_id' => 0, + ], + 'hidden' => [ + 'object_state_id' => 0, + ], + ], + ], + ], + [ + [ + 'enabled' => false, + 'handler' => 'content', + 'sections' => [ + 'visible' => [ + 'section_id' => 0, + ], + 'hidden' => [ + 'section_id' => 0, + ], + ], + 'object_states' => [ + 'object_state_group_id' => 0, + 'visible' => [ + 'object_state_id' => 0, + ], + 'hidden' => [ + 'object_state_id' => 0, + ], + ], + 'content_types' => [ + 'all' => false, + 'allowed' => [], + ], + ], + ], + ]; + } + + public static function provideEnabledConfigurationCases(): iterable + { + return [ + [ + [], + false, + ], + [ + [ + 'enabled' => false, + ], + false, + ], + [ + [ + 'enabled' => true, + ], + true, + ], + ]; + } + + public static function provideHandlerConfigurationCases(): iterable + { + return [ + [ + [ + 'handler' => 'content', + ], + 'content', + ], + [ + [ + 'handler' => 'location', + ], + 'location', + ], + [ + [ + 'handler' => 'content_location', + ], + 'content_location', + ], + [ + [ + 'handler' => 'section', + ], + 'section', + ], + [ + [ + 'handler' => 'object_state', + ], + 'object_state', + ], + ]; + } + + public static function provideSectionConfigurationCases(): iterable + { + return [ + [ + [ + 'sections' => [ + 'visible' => [ + 'section_id' => 1, + ], + 'hidden' => [ + 'section_id' => 2, + ], + ], + ], + [ + 'visible' => 1, + 'hidden' => 2, + ], + ], + [ + [ + 'sections' => [ + 'visible' => [ + 'section_id' => 2, + ], + 'hidden' => [ + 'section_id' => 1, + ], + ], + ], + [ + 'visible' => 2, + 'hidden' => 1, + ], + ], + ]; + } + + public static function provideObjectStateConfigurationCases(): iterable + { + return [ + [ + [ + 'object_states' => [ + 'object_state_group_id' => 1, + 'visible' => [ + 'object_state_id' => 2, + ], + 'hidden' => [ + 'object_state_id' => 3, + ], + ], + ], + [ + 'group' => 1, + 'visible' => 2, + 'hidden' => 3, + ], + ], + [ + [ + 'object_states' => [ + 'object_state_group_id' => 3, + 'visible' => [ + 'object_state_id' => 2, + ], + 'hidden' => [ + 'object_state_id' => 1, + ], + ], + ], + [ + 'group' => 3, + 'visible' => 2, + 'hidden' => 1, + ], + ], + ]; + } + + public static function provideContentTypesConfigurationCases(): iterable + { + return [ + [ + [ + 'content_types' => [], + ], + [ + 'all' => false, + 'allowed' => [], + ], + ], + [ + [ + 'content_types' => [ + 'all' => true, + 'allowed' => [], + ], + ], + [ + 'all' => true, + 'allowed' => [], + ], + ], + [ + [ + 'content_types' => [ + 'all' => false, + 'allowed' => ['content_1', 'content_2'], + ], + ], + [ + 'all' => false, + 'allowed' => ['content_1', 'content_2'], + ], + ], + ]; + } + + /** + * @dataProvider provideDefaultConfigurationCases + */ + public function testDefaultConfiguration(array $configuration): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.enabled', + false, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.handler', + 'content', + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.sections.visible.section_id', + 0, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.sections.hidden.section_id', + 0, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.object_state_group_id', + 0, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.visible.object_state_id', + 0, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.hidden.object_state_id', + 0, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.content_types.all', + false, + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.content_types.allowed', + [], + ); + } + + /** + * @dataProvider provideEnabledConfigurationCases + */ + public function testEnabledConfiguration(array $configuration, bool $expectedParameterValue): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.enabled', + $expectedParameterValue, + ); + } + + /** + * @dataProvider provideHandlerConfigurationCases + */ + public function testHandlerConfiguration(array $configuration, string $expectedParameterValue): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.handler', + $expectedParameterValue, + ); + } + + /** + * @dataProvider provideSectionConfigurationCases + */ + public function testSectionConfiguration(array $configuration, array $expectedParameterValues): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.sections.visible.section_id', + $expectedParameterValues['visible'], + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.sections.hidden.section_id', + $expectedParameterValues['hidden'], + ); + } + + /** + * @dataProvider provideObjectStateConfigurationCases + */ + public function testObjectStateConfiguration(array $configuration, array $expectedParameterValues): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.object_state_group_id', + $expectedParameterValues['group'], + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.visible.object_state_id', + $expectedParameterValues['visible'], + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.object_states.hidden.object_state_id', + $expectedParameterValues['hidden'], + ); + } + + /** + * @dataProvider provideContentTypesConfigurationCases + */ + public function testContentTypesConfiguration(array $configuration, array $expectedParameterValues): void + { + $this->load($configuration); + + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.content_types.all', + $expectedParameterValues['all'], + ); + $this->assertContainerBuilderHasParameter( + 'netgen_ibexa_scheduled_visibility.content_types.allowed', + $expectedParameterValues['allowed'], + ); + } + + protected function getContainerExtensions(): array + { + return [ + new NetgenIbexaScheduledVisibilityExtension(), + ]; + } +} diff --git a/tests/bundle/Integration/BaseTest.php b/tests/bundle/Integration/BaseTest.php new file mode 100644 index 0000000..5c9b742 --- /dev/null +++ b/tests/bundle/Integration/BaseTest.php @@ -0,0 +1,152 @@ + null, + 'publish_to' => null, + ], + false, + ], + [ + [ + 'publish_from' => null, + 'publish_to' => new DateTime('tomorrow'), + ], + false, + ], + [ + [ + 'publish_from' => null, + 'publish_to' => new DateTime('yesterday'), + ], + true, + ], + [ + [ + 'publish_from' => new DateTime('2 days ago'), + 'publish_to' => new DateTime('yesterday'), + ], + true, + ], + [ + [ + 'publish_from' => new DateTime('yesterday'), + 'publish_to' => new DateTime('tomorrow'), + ], + false, + ], + [ + [ + 'publish_from' => new DateTime('tomorrow'), + 'publish_to' => null, + ], + true, + ], + [ + [ + 'publish_from' => new DateTime('tomorrow'), + 'publish_to' => new DateTime('2 day'), + ], + true, + ], + ]; + } + + protected function getScheduledVisibilityService(): ScheduledVisibilityService + { + /** @var \Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\ScheduledVisibilityService $service */ + $service = $this->getSetupFactory()->getServiceContainer()->get(ScheduledVisibilityService::class); + + return $service; + } + + protected function createContentType(): ContentType + { + $repository = $this->getRepository(); + + $contentTypeService = $repository->getContentTypeService(); + $permissionResolver = $repository->getPermissionResolver(); + + $typeCreate = $contentTypeService->newContentTypeCreateStruct('test-scheduled-visibility'); + $typeCreate->mainLanguageCode = 'eng-GB'; + $typeCreate->remoteId = '384b94a1bd6bc06826410e284dd9684887bf56fc'; + $typeCreate->urlAliasSchema = 'url|scheme'; + $typeCreate->nameSchema = 'name|scheme'; + $typeCreate->names = [ + 'eng-GB' => 'Test Scheduled Visibility', + ]; + $typeCreate->creatorId = $this->generateId('user', $permissionResolver->getCurrentUserReference()->getUserId()); + $typeCreate->creationDate = $this->createDateTime(); + + $publishFromFieldCreate = $contentTypeService->newFieldDefinitionCreateStruct('publish_from', 'ezdate'); + $publishFromFieldCreate->names = [ + 'eng-GB' => 'Publish from', + ]; + $publishFromFieldCreate->position = 1; + $typeCreate->addFieldDefinition($publishFromFieldCreate); + + $publishToFieldCreate = $contentTypeService->newFieldDefinitionCreateStruct('publish_to', 'ezdatetime'); + $publishToFieldCreate->names = [ + 'eng-GB' => 'Publish to', + ]; + $publishToFieldCreate->position = 2; + $typeCreate->addFieldDefinition($publishToFieldCreate); + + $groups = [ + $contentTypeService->loadContentTypeGroupByIdentifier('Media'), + ]; + + $contentTypeDraft = $contentTypeService->createContentType( + $typeCreate, + $groups, + ); + + $contentTypeService->publishContentTypeDraft($contentTypeDraft); + $contentType = $contentTypeService->loadContentType($contentTypeDraft->id); + + self::assertInstanceOf( + ContentType::class, + $contentType, + ); + + return $contentType; + } + + protected function createContent(?DateTime $publishFrom, ?DateTime $publishTo): Content + { + $contentService = $this->getRepository()->getContentService(); + $contentType = $this->createContentType(); + $contentCreate = $contentService->newContentCreateStruct($contentType, 'eng-GB'); + $contentCreate->setField('publish_from', $publishFrom); + $contentCreate->setField('publish_to', $publishTo); + + $contentCreate->remoteId = 'abcdef0123456789abcdef0123456789'; + $contentCreate->alwaysAvailable = true; + + $locationService = $this->getRepository()->getLocationService(); + $content = $contentService->createContent( + $contentCreate, + [$locationService->newLocationCreateStruct(2)], + ); + $publishedContent = $contentService->publishVersion($content->getVersionInfo()); + + self::assertInstanceOf(Content::class, $publishedContent); + + return $publishedContent; + } +} diff --git a/tests/bundle/Integration/ContentAndLocationTest.php b/tests/bundle/Integration/ContentAndLocationTest.php new file mode 100644 index 0000000..b47ee34 --- /dev/null +++ b/tests/bundle/Integration/ContentAndLocationTest.php @@ -0,0 +1,41 @@ +getScheduledVisibilityService(); + $content = $this->createContent($configuration['publish_from'], $configuration['publish_to']); + $handler = $this->getContentAndLocationHandler(); + if ($scheduledVisibilityService->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + } + if ($scheduledVisibilityService->shouldBeVisible($content) && $handler->isHidden($content)) { + $handler->reveal($content); + } + $content = $this->getRepository()->getContentService()->loadContent($content->contentInfo->id); + self::assertEquals($handler->isHidden($content), $expectedHidden); + } + + private function getContentAndLocationHandler(): ContentAndLocation + { + /** @var \Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Content $contentHandler */ + $contentHandler = $this->getSetupFactory()->getServiceContainer()->get(Content::class); + + /** @var \Netgen\Bundle\IbexaScheduledVisibilityBundle\Core\VisibilityHandler\Location $locationHandler */ + $locationHandler = $this->getSetupFactory()->getServiceContainer()->get(Location::class); + + return new ContentAndLocation($contentHandler, $locationHandler); + } +} diff --git a/tests/bundle/Integration/ContentTest.php b/tests/bundle/Integration/ContentTest.php new file mode 100644 index 0000000..81fe460 --- /dev/null +++ b/tests/bundle/Integration/ContentTest.php @@ -0,0 +1,35 @@ +getScheduledVisibilityService(); + $content = $this->createContent($configuration['publish_from'], $configuration['publish_to']); + $handler = $this->getContentHandler(); + if ($scheduledVisibilityService->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + } + if ($scheduledVisibilityService->shouldBeVisible($content) && $handler->isHidden($content)) { + $handler->reveal($content); + } + $content = $this->getRepository()->getContentService()->loadContent($content->contentInfo->id); + self::assertEquals($handler->isHidden($content), $expectedHidden); + } + + private function getContentHandler(): Content + { + $repository = $this->getRepository(); + + return new Content($repository, $repository->getContentService()); + } +} diff --git a/tests/bundle/Integration/LocationTest.php b/tests/bundle/Integration/LocationTest.php new file mode 100644 index 0000000..37a86fe --- /dev/null +++ b/tests/bundle/Integration/LocationTest.php @@ -0,0 +1,35 @@ +getScheduledVisibilityService(); + $content = $this->createContent($configuration['publish_from'], $configuration['publish_to']); + $handler = $this->getLocationHandler(); + if ($scheduledVisibilityService->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + } + if ($scheduledVisibilityService->shouldBeVisible($content) && $handler->isHidden($content)) { + $handler->reveal($content); + } + $content = $this->getRepository()->getContentService()->loadContent($content->contentInfo->id); + self::assertEquals($handler->isHidden($content), $expectedHidden); + } + + private function getLocationHandler(): Location + { + $repository = $this->getRepository(); + + return new Location($repository, $repository->getLocationService()); + } +} diff --git a/tests/bundle/Integration/ObjectStateTest.php b/tests/bundle/Integration/ObjectStateTest.php new file mode 100644 index 0000000..de3b298 --- /dev/null +++ b/tests/bundle/Integration/ObjectStateTest.php @@ -0,0 +1,67 @@ +getScheduledVisibilityService(); + $content = $this->createContent($configuration['publish_from'], $configuration['publish_to']); + $hiddenObjectState = $this->createObjectState(); + $visibleObjectStateId = 1; + $objectStateGroupId = 2; + $handler = $this->getObjectStateHandler($objectStateGroupId, $hiddenObjectState->id, $visibleObjectStateId); + if ($scheduledVisibilityService->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + } + if ($scheduledVisibilityService->shouldBeVisible($content) && $handler->isHidden($content)) { + $handler->reveal($content); + } + $content = $this->getRepository()->getContentService()->loadContent($content->contentInfo->id); + + $objectStateService = $this->getRepository()->getObjectStateService(); + $objectStateGroup = $objectStateService->loadObjectStateGroup(2); + $objectState = $this->getRepository()->sudo( + static fn (): ObjectStateValue => $objectStateService->getContentState($content->contentInfo, $objectStateGroup), + ); + self::assertEquals($objectState->id, $expectedHidden ? $hiddenObjectState->id : $visibleObjectStateId); + } + + private function getObjectStateHandler(int $objectStateGroupId, int $hiddenObjectStateId, int $visibleObjectStateId): ObjectState + { + $repository = $this->getRepository(); + + return new ObjectState($repository, $repository->getObjectStateService(), $objectStateGroupId, $hiddenObjectStateId, $visibleObjectStateId); + } + + private function createObjectState(): ObjectStateValue + { + $repository = $this->getRepository(); + + $objectStateService = $repository->getObjectStateService(); + $objectStateGroup = $objectStateService->loadObjectStateGroup(2); + + $objectStateCreateStruct = $objectStateService->newObjectStateCreateStruct( + 'scheduled_visibility_object_state', + ); + $objectStateCreateStruct->priority = 23; + $objectStateCreateStruct->defaultLanguageCode = 'eng-GB'; + $objectStateCreateStruct->names = [ + 'eng-GB' => 'Scheduled visibility object state', + ]; + + return $objectStateService->createObjectState( + $objectStateGroup, + $objectStateCreateStruct, + ); + } +} diff --git a/tests/bundle/Integration/SectionTest.php b/tests/bundle/Integration/SectionTest.php new file mode 100644 index 0000000..a325c58 --- /dev/null +++ b/tests/bundle/Integration/SectionTest.php @@ -0,0 +1,51 @@ +getScheduledVisibilityService(); + $content = $this->createContent($configuration['publish_from'], $configuration['publish_to']); + $hiddenSection = $this->createSection(); + $visibleSectionId = 1; + $handler = $this->getSectionHandler($hiddenSection->id, $visibleSectionId); + if ($scheduledVisibilityService->shouldBeHidden($content) && !$handler->isHidden($content)) { + $handler->hide($content); + } + if ($scheduledVisibilityService->shouldBeVisible($content) && $handler->isHidden($content)) { + $handler->reveal($content); + } + $content = $this->getRepository()->getContentService()->loadContent($content->contentInfo->id); + self::assertEquals($content->contentInfo->sectionId, $expectedHidden ? $hiddenSection->id : $visibleSectionId); + } + + private function getSectionHandler(int $hiddenSectionId, int $visibleSectionId): Section + { + $repository = $this->getRepository(); + + return new Section($repository, $repository->getSectionService(), $hiddenSectionId, $visibleSectionId); + } + + private function createSection(): SectionValue + { + $repository = $this->getRepository(); + + $sectionService = $repository->getSectionService(); + + $sectionCreate = $sectionService->newSectionCreateStruct(); + $sectionCreate->name = 'Test Scheduled Visibility section'; + $sectionCreate->identifier = 'scheduled_visibility_section_'; + + return $sectionService->createSection($sectionCreate); + } +} diff --git a/tests/bundle/Integration/SetupFactory/Legacy.php b/tests/bundle/Integration/SetupFactory/Legacy.php new file mode 100644 index 0000000..e64036e --- /dev/null +++ b/tests/bundle/Integration/SetupFactory/Legacy.php @@ -0,0 +1,27 @@ +load('services.yaml'); + $loader->load('default_settings.yaml'); + + $containerBuilder->addCompilerPass(new ScheduledVisibilityHandlerRegistrationPass()); + } +}