diff --git a/CHANGELOG.txt b/CHANGELOG.txt old mode 100644 new mode 100755 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100755 index 0000000..d159169 --- /dev/null +++ b/LICENSE.txt @@ -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 old mode 100644 new mode 100755 diff --git a/composer.json b/composer.json old mode 100644 new mode 100755 index c65c68c..f260790 --- a/composer.json +++ b/composer.json @@ -1,7 +1,16 @@ { - "name": "drupal/domain_path", - "type": "drupal-module", - "description": "Allow the same path to be used across different domains", - "homepage": "https://github.com/dennisinteractive/domain_path", - "license": "GPL-2.0+" + "name": "drupal/domain_path", + "description": "Allow the same path to be used across different domains.", + "type": "drupal-module", + "homepage": "https://github.com/dennisinteractive/domain_path", + "license": "GPL-2.0-or-later", + "require": { + "drupal/domain": "^1.0-beta" + }, + "require-dev": { + "drupal/pathauto": "1.x-dev" + }, + "suggest": { + "drupal/pathauto": "Automatic path aliases with Domain Path Pathauto submodule." + } } diff --git a/config/install/domain_path.settings.yml b/config/install/domain_path.settings.yml old mode 100644 new mode 100755 index e53485f..1ce5f33 --- a/config/install/domain_path.settings.yml +++ b/config/install/domain_path.settings.yml @@ -1,2 +1,4 @@ entity_types: node: '1' +hide_path_alias_ui: TRUE +language_method: 'language_content' diff --git a/config/schema/domain_path.schema.yml b/config/schema/domain_path.schema.yml index 669e14e..5404fe3 100755 --- a/config/schema/domain_path.schema.yml +++ b/config/schema/domain_path.schema.yml @@ -6,3 +6,9 @@ domain_path.settings: type: sequence sequence: type: string + hide_path_alias_ui: + label: Hide the default URL alias UI + type: boolean + language_method: + label: The method of language detection + type: string diff --git a/domain_path.info.yml b/domain_path.info.yml index 6a48e74..5d3dd1f 100755 --- a/domain_path.info.yml +++ b/domain_path.info.yml @@ -2,7 +2,8 @@ name: 'Domain Path' description: 'Allows separate path aliases per domain.' type: module package: Domain -core_version_requirement: ^8.8 || ^9 +core_version_requirement: ^8.8 || ^9 || ^10 +configure: entity.domain_path_settings dependencies: - - path - - domain + - drupal:path + - domain:domain diff --git a/domain_path.links.action.yml b/domain_path.links.action.yml old mode 100644 new mode 100755 diff --git a/domain_path.services.yml b/domain_path.services.yml index 2cc1626..b48833b 100755 --- a/domain_path.services.yml +++ b/domain_path.services.yml @@ -1,13 +1,4 @@ services: - domain_path.path_processor: - class: Drupal\domain_path\PathProcessor\DomainPathProcessor - arguments: ['@language_manager', '@entity_type.manager', '@path_alias.manager', '@domain.negotiator'] - tags: - # Priority is very important here. The inbound processor needs to happen - # BEFORE the path module alias processor, and the outbound needs to happen - # AFTER the alias processor. - - { name: path_processor_inbound, priority: 110 } - - { name: path_processor_outbound, priority: 200 } domain_path.helper: class: Drupal\domain_path\DomainPathHelper arguments: ['@current_user', '@entity_type.manager', '@path_alias.manager', '@config.factory', '@module_handler'] diff --git a/drupalci.yml b/drupalci.yml new file mode 100755 index 0000000..83fc544 --- /dev/null +++ b/drupalci.yml @@ -0,0 +1,21 @@ +build: + assessment: + validate_codebase: + phplint: + csslint: + halt-on-fail: false + eslint: + halt-on-fail: false + phpcs: + sniff-all-files: false + halt-on-fail: false + testing: + container_command: + commands: + - '/bin/bash -c "cd ${SOURCE_DIR}/modules/contrib/domain && chmod +x ./define_subdomains.sh && ./define_subdomains.sh"' + run_tests.standard: + types: 'PHPUnit-Unit,PHPUnit-Build,PHPUnit-Kernel,PHPUnit-Functional' + run_tests.js: + concurrency: 1 + types: 'PHPUnit-FunctionalJavascript' + nightwatchjs: diff --git a/modules/domain_path_pathauto/domain_path_pathauto.info.yml b/modules/domain_path_pathauto/domain_path_pathauto.info.yml old mode 100644 new mode 100755 index 9e97de2..c59f82f --- a/modules/domain_path_pathauto/domain_path_pathauto.info.yml +++ b/modules/domain_path_pathauto/domain_path_pathauto.info.yml @@ -4,5 +4,5 @@ description: Domain Path Pathauto support core_version_requirement: ^8.8 || ^9 package: Domain dependencies: - - domain_path - - pathauto(>= 1.8) + - domain_path:domain_path + - pathauto:pathauto(>= 1.8) diff --git a/modules/domain_path_pathauto/domain_path_pathauto.module b/modules/domain_path_pathauto/domain_path_pathauto.module new file mode 100755 index 0000000..a0a340d --- /dev/null +++ b/modules/domain_path_pathauto/domain_path_pathauto.module @@ -0,0 +1,42 @@ +get('hide_path_alias_ui'); + if ($default_ui_hidden) { + $keys = ['domain_path']; + } + if (!empty(NestedArray::getValue($form, $keys)) && ($object = $form_state->getFormObject()) && is_callable([ + $object, + 'getEntity', + ]) + && ($entity = $object->getEntity())) { + $domain_path_helper = \Drupal::service('domain_path.helper'); + $domain_path_pathauto_helper = \Drupal::service('domain_path_pathauto.helper'); + /** @var \Drupal\domain_path_pathauto\DomainPathautoHelper $domain_path_pathauto_helper */ + if ($domain_path_helper->domainPathsIsEnabled($entity)) { + try { + $domain_path_pathauto_helper->alterEntityForm($form, $form_state, $entity, $keys); + } + catch (InvalidPluginDefinitionException | PluginNotFoundException $e) { + } + + } + } +} diff --git a/modules/domain_path_pathauto/domain_path_pathauto.services.yml b/modules/domain_path_pathauto/domain_path_pathauto.services.yml old mode 100644 new mode 100755 index 348c70f..f2e6cdb --- a/modules/domain_path_pathauto/domain_path_pathauto.services.yml +++ b/modules/domain_path_pathauto/domain_path_pathauto.services.yml @@ -5,3 +5,6 @@ services: domain_path_pathauto.alias_uniquifier: class: Drupal\domain_path_pathauto\DomainAliasUniquifier arguments: ['@config.factory', '@pathauto.alias_storage_helper','@module_handler', '@router.route_provider', '@path_alias.manager'] + domain_path_pathauto.helper: + class: Drupal\domain_path_pathauto\DomainPathautoHelper + arguments: ['@entity_type.manager', '@domain_path_pathauto.generator', '@config.factory', '@domain_path.helper'] diff --git a/modules/domain_path_pathauto/src/DomainAliasUniquifier.php b/modules/domain_path_pathauto/src/DomainAliasUniquifier.php old mode 100644 new mode 100755 diff --git a/modules/domain_path_pathauto/src/DomainPathautoGenerator.php b/modules/domain_path_pathauto/src/DomainPathautoGenerator.php old mode 100644 new mode 100755 index c1673e4..59f226a --- a/modules/domain_path_pathauto/src/DomainPathautoGenerator.php +++ b/modules/domain_path_pathauto/src/DomainPathautoGenerator.php @@ -8,6 +8,7 @@ use Drupal\Core\Language\LanguageInterface; use Drupal\Core\Render\BubbleableMetadata; use Drupal\pathauto\PathautoGenerator; +use Drupal\pathauto\PathautoGeneratorInterface; /** * Provides methods for generating domain path aliases. @@ -65,6 +66,7 @@ public function createEntityAlias(EntityInterface $entity, $op, $domain_id = '') 'data' => $data, 'bundle' => $entity->bundle(), 'language' => &$langcode, + 'domain_id' => $domain_id, ]; $pattern_original = $pattern->getPattern(); $this->moduleHandler->alter('pathauto_pattern', $pattern, $context); diff --git a/modules/domain_path_pathauto/src/DomainPathautoHelper.php b/modules/domain_path_pathauto/src/DomainPathautoHelper.php new file mode 100755 index 0000000..ede255d --- /dev/null +++ b/modules/domain_path_pathauto/src/DomainPathautoHelper.php @@ -0,0 +1,283 @@ +entityTypeManager = $entity_type_manager; + $this->domainPathautoGenerator = $domain_pathauto_generator; + $this->configFactory = $config_factory; + $this->domainPathHelper = $domain_path_helper; + } + + /** + * The domain path_auto form element for the entity form. + * + * @param array $form + * The form. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The form state. + * @param \Drupal\Core\Entity\ContentEntityInterface $entity + * Related entity. + * + * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException + * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException + */ + public function alterEntityForm(array &$form, FormStateInterface $form_state, ContentEntityInterface $entity, array $keys) { + // We need to use it in validation callback. + $form_state->addBuildInfo('element_keys', $keys); + $domains = $this->entityTypeManager->getStorage('domain') + ->loadMultipleSorted(); + // When setting states of checkboxes it's matter whether we have enabled or + // disabled default pathauto UI. Depending on it, we have different paths. + $input_selector_prefix = 'input[name="domain_path'; + if (!$this->configFactory->get('domain_path.settings')->get('hide_path_alias_ui')) { + $input_selector_prefix = 'input[name="path[0][domain_path]'; + } + $build_info = $form_state->getBuildInfo(); + foreach ($domains as $domain_id => $domain) { + // See https://git.drupalcode.org/project/pathauto/-/blob/8.x-1.x/src/PathautoWidget.php#L42 + // Generate checkboxes per each domain. + if ($build_info['pathauto_checkbox'] && NestedArray::getValue($form, $keys)) { + NestedArray::setValue($form, array_merge($keys, [$domain_id, 'pathauto']), [ + '#type' => 'checkbox', + '#title' => $this->t('Generate automatic URL alias for @domain', ['@domain' => Html::escape(rtrim($domain->getPath(), '/'))]), + '#default_value' => $this->domainPathautoGenerator->domainPathPathautoGenerationIsEnabled($entity, $domain->id()), + '#weight' => -1, + ]); + } + // Disable form element if the "delete-checkbox" is active or automatic + // creation of alias is checked. + NestedArray::setValue($form, array_merge($keys, [$domain_id, 'path', '#states']), [ + 'disabled' => [ + [$input_selector_prefix . '[domain_path_delete]"]' => ['checked' => TRUE]], + 'OR', + [$input_selector_prefix . '[' . $domain_id . '][pathauto]"]' => ['checked' => TRUE]], + ], + ]); + } + $form['#validate'][] = [$this, 'validateAlteredForm']; + if (!empty($form['actions'])) { + if (array_key_exists('submit', $form['actions'])) { + $form['actions']['submit']['#submit'][] = [ + $this, + 'submitAlteredEntityForm', + ]; + } + } + else { + // If no actions we just tack it on to the form submit handlers. + $form['#submit'][] = [$this, 'submitAlteredEntityForm']; + } + } + + /** + * Validation handler. + * + * @param array $form + * The form array. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The form state object. + * + * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException + * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException + */ + public function validateAlteredForm(array &$form, FormStateInterface $form_state) { + // Set up variables. + $entity = $form_state->getFormObject()->getEntity(); + $path_values = $form_state->getValue('path'); + $domain_path_values = ($this->configFactory->get('domain_path.settings')->get('hide_path_alias_ui')) ? $form_state->getValue('domain_path') : $path_values[0]['domain_path']; + $alias = $path_values[0]['alias'] ?? NULL; + // Check domain access settings if they are on the form. + $domain_access = []; + if (!empty($form['field_domain_access']) && !empty($form_state->getValue('field_domain_access'))) { + $domain_access = $this->domainPathHelper->processDomainAccessField($form_state->getValue('field_domain_access')); + } + $build_info = $form_state->getBuildInfo(); + $domain_access_all = empty($form['field_domain_all_affiliates']) || $form_state->getValue('field_domain_all_affiliates')['value']; + // Validate each path value. + + if (array_key_exists('domain_path_delete', $domain_path_values)) { + unset($domain_path_values['domain_path_delete']); + } + + foreach ($domain_path_values as $domain_id => $domain_path_data) { + + // Don't validate if the domain doesn't have access (we remove aliases + // for domains that don't have access to this entity). + $domain_has_access = $domain_access_all || ($domain_access && !empty($domain_access[$domain_id])); + if (!$domain_has_access) { + continue; + } + + // If domain pathauto is not enabled, validate user entered path. + if (array_key_exists('pathauto', $domain_path_data) && !$domain_path_data['pathauto']) { + $path = $domain_path_data['path']; + if (!empty($path) && $path === $alias) { + $form_state->setError(NestedArray::getValue($form, array_merge($build_info['element_keys'], [$domain_id])), $this->t('Domain path "%path" matches the default path alias. You may leave the element blank.', ['%path' => $path])); + } + elseif (!empty($path)) { + // Trim slashes and whitespace from end of path value. + $path_value = rtrim(trim($path), " \\/"); + + // Check that the paths start with a slash. + if ($path_value && $path_value[0] !== '/') { + $form_state->setError(NestedArray::getValue($form, array_merge($build_info['element_keys'], [$domain_id, 'path'])), $this->t('Domain path "%path" needs to start with a slash.', ['%path' => $path])); + } + + // Check for duplicates. + $entity_query = $this->entityTypeManager->getStorage('domain_path') + ->getQuery(); + $entity_query->condition('domain_id', $domain_id) + ->condition('alias', $path_value); + if (!$entity->isNew()) { + $entity_query->condition('source', '/' . $entity->toUrl()->getInternalPath(), '<>'); + } + $result = $entity_query->execute(); + if ($result) { + $form_state->setError(NestedArray::getValue($form, array_merge($build_info['element_keys'], [$domain_id, 'path'])), $this->t('Domain path %path matches an existing domain path alias', ['%path' => $path_value])); + } + } + if (isset($path_value)) { + $domain_path_values[$domain_id] = $path_value; + } + } + $form_state->setValue('domain_path', $domain_path_values); + } + } + + /** + * Submit handler. + * + * @param array $form + * The form array. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The form state object. + * + * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException + * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException|\Drupal\Core\Entity\EntityStorageException + */ + public function submitAlteredEntityForm(array $form, FormStateInterface $form_state) { + $path_values = $form_state->getValue('path'); + $domain_path_values = ($this->configFactory->get('domain_path.settings')->get('hide_path_alias_ui')) ? $form_state->getValue('domain_path') : $path_values[0]['domain_path']; + $entity = $form_state->getFormObject()->getEntity(); + $entity_system_path = '/' . $entity->toUrl()->getInternalPath(); + $properties = [ + 'source' => $entity_system_path, + 'language' => $entity->language()->getId(), + ]; + $domain_access_all = empty($form['field_domain_all_affiliates']) || $form_state->getValue('field_domain_all_affiliates')['value']; + // Check domain access settings if they are on the form. + $domain_access = []; + if (!empty($form['field_domain_access']) && !empty($form_state->getValue('field_domain_access'))) { + $domain_access = $this->domainPathHelper->processDomainAccessField($form_state->getValue('field_domain_access')); + } + // If not set to delete, then save changes. + if (empty($domain_path_values['domain_path_delete'])) { + unset($domain_path_values['domain_path_delete']); + foreach ($domain_path_values as $domain_id => $domain_path_data) { + + $alias = trim($domain_path_data['path']); + if ($domain_path_data['pathauto']) { + // Generate alias using pathauto. + $alias = $this->domainPathautoGenerator->createEntityAlias($entity, 'return', $domain_id); + // Remember pathauto default enabled setting. + $this->domainPathautoGenerator->setDomainPathPathautoState($entity, $domain_id, TRUE); + } + else { + // Delete pathauto default enabled setting. + $this->domainPathautoGenerator->deleteDomainPathPathautoState($entity, $domain_id); + } + // Get the existing domain path for this domain if it exists. + $properties['domain_id'] = $domain_id; + $domain_paths = $this->entityTypeManager->getStorage('domain_path') + ->loadByProperties($properties); + $domain_has_access = $domain_access_all || ($domain_access && !empty($domain_access[$domain_id])); + $domain_path = $domain_paths ? reset($domain_paths) : NULL; + // We don't want to save the alias if the domain path field is empty, + // or if the domain doesn't have + // access to this entity. + if (!$alias || !$domain_has_access) { + // Delete the existing domain path. + if ($domain_path) { + $domain_path->delete(); + } + continue; + } + + // Create or update the domain path. + $properties_map = [ + 'alias' => $alias, + 'domain_id' => $domain_id, + ] + $properties; + if (!$domain_path) { + $domain_path = $this->entityTypeManager->getStorage('domain_path') + ->create(['type' => 'domain_path']); + foreach ($properties_map as $field => $value) { + $domain_path->set($field, $value); + } + $domain_path->save(); + } + elseif ($domain_path->get('alias')->value !== $alias) { + $domain_path->set('alias', $alias); + $domain_path->save(); + } + } + } + } + +} diff --git a/src/Controller/DomainPathListBuilder.php b/src/Controller/DomainPathListBuilder.php index 36f5476..1c5437a 100755 --- a/src/Controller/DomainPathListBuilder.php +++ b/src/Controller/DomainPathListBuilder.php @@ -6,8 +6,11 @@ use Drupal\Core\Entity\EntityTypeInterface; use Drupal\Core\Entity\EntityListBuilder; use Drupal\Core\Entity\EntityStorageInterface; +use Drupal\Core\Form\FormBuilderInterface; use Drupal\Core\Routing\UrlGeneratorInterface; +use Drupal\domain_path\Form\DomainPathFilterForm; use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\Request; /** * Provides a list controller for domain_path entity. @@ -16,6 +19,20 @@ */ class DomainPathListBuilder extends EntityListBuilder { + /** + * The current request. + * + * @var \Symfony\Component\HttpFoundation\Request + */ + protected $currentRequest; + + /** + * The form builder. + * + * @var \Drupal\Core\Form\FormBuilderInterface + */ + protected $formBuilder; + /** * The url generator. * @@ -31,7 +48,9 @@ public static function createInstance(ContainerInterface $container, EntityTypeI return new static( $entity_type, $container->get('entity_type.manager')->getStorage($entity_type->id()), - $container->get('url_generator') + $container->get('url_generator'), + $container->get('request_stack')->getCurrentRequest(), + $container->get('form_builder') ); } @@ -45,11 +64,37 @@ public static function createInstance(ContainerInterface $container, EntityTypeI * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator * The url generator. */ - public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, UrlGeneratorInterface $url_generator) { + public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, UrlGeneratorInterface $url_generator, Request $current_request, FormBuilderInterface $form_builder) { parent::__construct($entity_type, $storage); $this->urlGenerator = $url_generator; + $this->currentRequest = $current_request; + $this->formBuilder = $form_builder; + } + + /** + * {@inheritdoc} + */ + protected function getEntityIds() { + $query = $this->getStorage()->getQuery(); + + $search = $this->currentRequest->query->get('search'); + if ($search) { + $query->condition('alias', $search, 'CONTAINS'); + } + + // Only add the pager if a limit is specified. + if ($this->limit) { + $query->pager($this->limit); + } + + // Allow the entity query to sort using the table header. + $header = $this->buildHeader(); + $query->tableSort($header); + + return $query->execute(); } + /** * {@inheritdoc} * @@ -82,4 +127,15 @@ public function buildRow(EntityInterface $entity) { return $row + parent::buildRow($entity); } + /** + * {@inheritdoc} + */ + public function render() { + $keys = $this->currentRequest->query->get('search'); + $build['path_admin_filter_form'] = $this->formBuilder->getForm(DomainPathFilterForm::class, $keys); + $build += parent::render(); + + return $build; + } + } diff --git a/src/DomainPathAliasManager.php b/src/DomainPathAliasManager.php new file mode 100755 index 0000000..4026ac1 --- /dev/null +++ b/src/DomainPathAliasManager.php @@ -0,0 +1,89 @@ +getActiveDomain(); + if ($active) { + $properties = [ + 'alias' => $alias, + 'domain_id' => \Drupal::service('domain.negotiator')->getActiveDomain()->id(), + ]; + $domain_paths = \Drupal::entityTypeManager()->getStorage('domain_path')->loadByProperties($properties); + + //https://git.drupalcode.org/project/drupal/-/blob/9.2.x/core/modules/path_alias/src/PathProcessor/AliasPathProcessor.php#L36 didn't pass the $langcode. + $langcode = $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(); + if ($langcode == NULL) { + //TODO: keep a "zxx -> Not applicable" in record for langage negotiation failed? + $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;// LANGCODE_NOT_SPECIFIED = 'und' + //return the first record when langage negotiation failed at this moment + $this->domainPath = reset($domain_paths); + if ($this->domainPath) { + return $this->domainPath->getSource(); + } + } + else { + foreach ($domain_paths as $domain_path) { + if ($domain_path->getLanguageCode() == $langcode) { + $this->domainPath = $domain_path; + return $this->domainPath->getSource(); + } + } + } + } + return parent::getPathByAlias($alias, $langcode); + } + + public function getAliasByPath($path, $langcode = NULL) { + $config = \Drupal::config('domain_path.settings'); + $this->method = $config->get('language_method') ? $config->get('language_method') : LanguageInterface::TYPE_CONTENT; + + $active = \Drupal::service('domain.negotiator')->getActiveDomain(); + if ($active) { + $properties = [ + 'source' => $path, + 'domain_id' => \Drupal::service('domain.negotiator')->getActiveDomain()->id(), + ]; + $domain_paths = \Drupal::entityTypeManager()->getStorage('domain_path')->loadByProperties($properties); + $langcode = $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(); + if ($langcode == NULL) { + $langcode = LanguageInterface::LANGCODE_NOT_APPLICABLE;// TODO: 'zxx' = active for any language or not? + } + foreach ($domain_paths as $domain_path) { + if ($domain_path->getLanguageCode() == $langcode) { + $this->domainPath = $domain_path; + return $this->domainPath->getAlias(); + } + } + } + return parent::getAliasByPath($path, $langcode); + } +} diff --git a/src/DomainPathHelper.php b/src/DomainPathHelper.php index f84b29d..919a207 100755 --- a/src/DomainPathHelper.php +++ b/src/DomainPathHelper.php @@ -146,15 +146,7 @@ public function alterEntityForm(&$form, FormStateInterface $form_state, $entity) $label = $domain->getPath(); } - if ($this->moduleHandler->moduleExists('domain_path_pathauto')) { - $form['path']['widget'][0]['domain_path'][$domain_id]['pathauto'] = [ - '#type' => 'checkbox', - '#title' => $this->t('Generate automatic URL alias for @domain', ['@domain' => Html::escape(rtrim($domain->getPath(), '/'))]), - '#default_value' => \Drupal::service('domain_path_pathauto.generator')->domainPathPathautoGenerationIsEnabled($entity, $domain->id()), - '#weight' => -1, - ]; - } - + $form_state->addBuildInfo('pathauto_checkbox', $form['path']['widget'][0]['pathauto']['#type'] === 'checkbox'); $form['path']['widget'][0]['domain_path'][$domain_id]['path'] = [ '#type' => 'textfield', '#title' => Html::escape(rtrim($label, '/')), @@ -167,22 +159,21 @@ public function alterEntityForm(&$form, FormStateInterface $form_state, $entity) ], ]; - if($this->moduleHandler->moduleExists('domain_path_pathauto')) { - $form['path']['widget'][0]['domain_path'][$domain_id]['path']['#states'] = [ - 'disabled' => [ - ['input[name="path[0][domain_path][domain_path_delete]"]' => ['checked' => TRUE]], - 'OR', - ['input[name="path[0][domain_path][' . $domain_id . '][pathauto]"]' => ['checked' => TRUE]], - ] - ]; - } - // If domain settings are on the page for this domain we only show if // it's checked. e.g. on the node form, we only show the domain path // field for domains we're publishing to if (!empty($form['field_domain_access']['widget']['#options'][$domain_id])) { - $form['path']['widget'][0]['domain_path'][$domain_id]['#states']['invisible']['input[name="field_domain_access[' . $domain_id . ']"]'] = ['unchecked' => TRUE]; + if ($form['field_domain_access']['widget']['#type'] == 'select') { + $form['path']['widget'][0]['domain_path'][$domain_id]['#states']['invisible']['select[name="field_domain_access"]'] = ['!value' => $domain_id]; + } + elseif ($form['field_domain_access']['widget']['#type'] == 'radios') { + $form['path']['widget'][0]['domain_path'][$domain_id]['#states']['invisible']['input[name="field_domain_access"]'] = ['!value' => $domain_id]; + } + else { + $form['path']['widget'][0]['domain_path'][$domain_id]['#states']['invisible']['input[name="field_domain_access[' . $domain_id . ']"]'] = ['unchecked' => TRUE]; + } $form['path']['widget'][0]['domain_path'][$domain_id]['#states']['invisible']['input[name="field_domain_all_affiliates[value]"]'] = ['unchecked' => TRUE]; + } else if (!empty($form['field_domain_access']['widget']['#options'])) { $form['path']['widget'][0]['domain_path'][$domain_id]['#access'] = FALSE; @@ -202,6 +193,15 @@ public function alterEntityForm(&$form, FormStateInterface $form_state, $entity) // If no actions we just tack it on to the form submit handlers. $form['#submit'][] = [$this, 'submitEntityForm']; } + + // Hide the default URL alias for better UI + if ($config->get('hide_path_alias_ui')) { + $form['domain_path'] = $form['path']['widget'][0]['domain_path']; + if (isset($form['advanced'])) { + $form['domain_path']['#group'] = 'advanced'; + } + unset($form['path']); + } } /** @@ -214,10 +214,11 @@ public function alterEntityForm(&$form, FormStateInterface $form_state, $entity) */ public static function validateEntityForm(array &$form, FormStateInterface $form_state) { // Set up variables. + $config = \Drupal::config('domain_path.settings'); $entity = $form_state->getFormObject()->getEntity(); $domain_path_storage = \Drupal::service('entity_type.manager')->getStorage('domain_path'); $path_values = $form_state->getValue('path'); - $domain_path_values = $path_values[0]['domain_path']; + $domain_path_values = ($config->get('hide_path_alias_ui')) ? $form_state->getValue('domain_path') : $path_values[0]['domain_path']; // If we're just deleting the domain paths we don't have to validate // anything. @@ -225,12 +226,14 @@ public static function validateEntityForm(array &$form, FormStateInterface $form return; } unset($domain_path_values['domain_path_delete']); - $alias = isset($path_values[0]['alias']) ? $path_values[0]['alias'] : NULL; // Check domain access settings if they are on the form. $domain_access = []; - if (!empty($form['field_domain_access'])) { + if (!empty($form['field_domain_access']) && !empty($form_state->getValue('field_domain_access'))) { foreach ($form_state->getValue('field_domain_access') as $item) { + if (!is_array($item)) { + continue; + } $domain_access[$item['target_id']] = $item['target_id']; } } @@ -241,41 +244,13 @@ public static function validateEntityForm(array &$form, FormStateInterface $form // Validate each path value. foreach ($domain_path_values as $domain_id => $domain_path_data) { - // Don't validate if the domain doesn't have access (we remove aliases // for domains that don't have access to this entity). $domain_has_access = $domain_access_all || ($domain_access && !empty($domain_access[$domain_id])); if (!$domain_has_access) { continue; } - // If domain pathauto is not enabled, validate user entered path. - if(!(\Drupal::service('module_handler')->moduleExists('domain_path_pathauto') && $domain_path_data['pathauto'])) { - $path = $domain_path_data['path']; - if (!empty($path) && $path == $alias) { - $form_state->setError($form['path']['widget'][0]['domain_path'][$domain_id], t('Domain path "%path" matches the default path alias. You may leave the element blank.', ['%path' => $path])); - } - elseif (!empty($path)) { - // Trim slashes and whitespace from end of path value. - $path_value = rtrim(trim($path), " \\/"); - - // Check that the paths start with a slash. - if ($path_value && $path_value[0] !== '/') { - $form_state->setError($form['path']['widget'][0]['domain_path'][$domain_id]['path'], t('Domain path "%path" needs to start with a slash.', ['%path' => $path])); - } - - // Check for duplicates. - $entity_query = $domain_path_storage->getQuery(); - $entity_query->condition('domain_id', $domain_id) - ->condition('alias', $path); - if (!$entity->isNew()) { - $entity_query->condition('source', '/' . $entity->toUrl()->getInternalPath(), '<>'); - } - $result = $entity_query->execute(); - if ($result) { - $form_state->setError($form['path']['widget'][0]['domain_path'][$domain_id]['path'], t('Domain path %path matches an existing domain path alias', ['%path' => $path])); - } - } - } + $form_state->setValue('domain_path', $domain_path_values); } } @@ -289,6 +264,7 @@ public static function validateEntityForm(array &$form, FormStateInterface $form */ public function submitEntityForm($form, FormStateInterface $form_state) { // Setup Variables + $config = \Drupal::config('domain_path.settings'); $entity = $form_state->getFormObject()->getEntity(); $entity_system_path = '/' . $entity->toUrl()->getInternalPath(); // Get the saved alias @@ -298,15 +274,13 @@ public function submitEntityForm($form, FormStateInterface $form_state) { 'language' => $entity->language()->getId(), ]; $path_values = $form_state->getValue('path'); - $domain_path_values = $path_values[0]['domain_path']; + $domain_path_values = ($config->get('hide_path_alias_ui')) ? $form_state->getValue('domain_path') : $path_values[0]['domain_path']; $domain_path_storage = $this->entityTypeManager->getStorage('domain_path'); // Check domain access settings if they are on the form. $domain_access = []; - if (!empty($form['field_domain_access'])) { - foreach ($form_state->getValue('field_domain_access') as $item) { - $domain_access[$item['target_id']] = $item['target_id']; - } + if (!empty($form['field_domain_access']) && !empty($form_state->getValue('field_domain_access'))) { + $domain_access = $this->processDomainAccessField($form_state->getValue('field_domain_access')); } // If domain access is on for this form, we check the "all affiliates" // checkbox, otherwise we just assume it's available on all domains. @@ -317,19 +291,7 @@ public function submitEntityForm($form, FormStateInterface $form_state) { unset($domain_path_values['domain_path_delete']); foreach ($domain_path_values as $domain_id => $domain_path_data) { - $alias = $domain_path_data['path']; - if ($this->moduleHandler->moduleExists('domain_path_pathauto')) { - $domain_path_pathauto_service = \Drupal::service('domain_path_pathauto.generator'); - if ($domain_path_data['pathauto']) { - // Generate alias using pathauto. - $alias = $domain_path_pathauto_service->createEntityAlias($entity, 'return', $domain_id); - // Remember pathauto default enabled setting. - $domain_path_pathauto_service->setDomainPathPathautoState($entity, $domain_id, TRUE); - } else { - // Delete pathauto default enabled setting. - $domain_path_pathauto_service->deleteDomainPathPathautoState($entity, $domain_id); - } - } + $alias = trim($domain_path_data['path']); // Get the existing domain path for this domain if it exists. $properties['domain_id'] = $domain_id; $domain_paths = $domain_path_storage->loadByProperties($properties); @@ -337,9 +299,9 @@ public function submitEntityForm($form, FormStateInterface $form_state) { $domain_has_access = $domain_access_all || ($domain_access && !empty($domain_access[$domain_id])); // We don't want to save the alias if the domain path field is empty, - // or if it matches the default alias, or if the domain doesn't have + // or if the domain doesn't have // access to this entity. - if (!$alias || $alias == $default_alias || !$domain_has_access) { + if (!$alias || !$domain_has_access) { // Delete the existing domain path. if ($domain_path) { $domain_path->delete(); @@ -420,11 +382,10 @@ public function deleteEntityDomainPaths(EntityInterface $entity, $delete_all_tra * Returns array of configured entity types. */ public function getConfiguredEntityTypes() { - if ($enabled_entity_types = $this->config->get('entity_types')) { - $enabled_entity_types = array_filter($enabled_entity_types); + $enabled_entity_types = $this->config->get('entity_types'); + $enabled_entity_types = array_filter($enabled_entity_types); - return array_keys($enabled_entity_types); - } + return array_keys($enabled_entity_types); } /** @@ -440,4 +401,19 @@ public function domainPathsIsEnabled(EntityInterface $entity) { return in_array($entity->getEntityTypeId(), $this->getConfiguredEntityTypes()); } + /** + * Returns an array of processed domain access field values. + */ + public function processDomainAccessField($field_values): array { + $domain_access = []; + foreach ($field_values as $field_value) { + if (!is_array($field_value)) { + continue; + } + $domain_access[$field_value['target_id']] = $field_value['target_id']; + } + + return $domain_access; + } + } diff --git a/src/DomainPathServiceProvider.php b/src/DomainPathServiceProvider.php new file mode 100755 index 0000000..b249266 --- /dev/null +++ b/src/DomainPathServiceProvider.php @@ -0,0 +1,22 @@ +getDefinition('path_alias.manager'); + $definition->setClass('Drupal\domain_path\DomainPathAliasManager'); + } + +} diff --git a/src/Form/DomainPathFilterForm.php b/src/Form/DomainPathFilterForm.php new file mode 100755 index 0000000..6510505 --- /dev/null +++ b/src/Form/DomainPathFilterForm.php @@ -0,0 +1,26 @@ +setRedirect('entity.domain_path.collection', [], [ + 'query' => ['search' => trim($form_state->getValue('filter'))], + ]); + } + + /** + * {@inheritdoc} + */ + public function resetForm(array &$form, FormStateInterface $form_state) { + $form_state->setRedirect('entity.domain_path.collection'); + } + +} diff --git a/src/Form/DomainPathForm.php b/src/Form/DomainPathForm.php index 0e0d5a8..5f29f9b 100755 --- a/src/Form/DomainPathForm.php +++ b/src/Form/DomainPathForm.php @@ -131,17 +131,19 @@ public function validateForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\domain_path\Entity\DomainPath $current_domain_path */ $current_domain_path = $form_state->getformObject()->getEntity(); - if ($domain_path_entity_data = $this->entityTypeManager->getStorage('domain_path')->loadByProperties(['alias' => $alias])) { + if ($domain_path_entity_data = $this->entityTypeManager->getStorage('domain_path')->loadByProperties(['alias' => $alias_check])) { foreach ($domain_path_entity_data as $domain_path_entity) { $check_domain_id = $domain_path_entity->get('domain_id')->target_id; $is_same = $current_domain_path && $domain_path_entity->id() == $current_domain_path->id(); if ($check_domain_id == $domain_id && !$is_same) { $domain_path = $domains[$domain_id]->getPath(); - $form_state->setErrorByName('alias', $this->t('Domain path %path matches an existing domain path alias for %domain_path.', ['%path' => $alias, '%domain_path' => $domain_path])); + $form_state->setErrorByName('alias', $this->t('Domain path %path matches an existing domain path alias for %domain_path.', ['%path' => $alias_check, '%domain_path' => $domain_path])); } } } + $alias_value[0]['value'] = $alias_check; + $form_state->setValue('alias', $alias_value); } /** diff --git a/src/Form/DomainPathSettingsForm.php b/src/Form/DomainPathSettingsForm.php index 26df82c..9453393 100755 --- a/src/Form/DomainPathSettingsForm.php +++ b/src/Form/DomainPathSettingsForm.php @@ -8,6 +8,7 @@ use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; use Symfony\Component\DependencyInjection\ContainerInterface; +use Drupal\Core\Language\LanguageInterface; /** * Class DomainPathSettingsForm. @@ -75,6 +76,9 @@ public function buildForm(array $form, FormStateInterface $form_state) { foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) { if (is_subclass_of($entity_type->getClass(), FieldableEntityInterface::class) && $entity_type->hasLinkTemplate('canonical')) { $default_value = !empty($enabled_entity_types[$entity_type_id]) ? $enabled_entity_types[$entity_type_id] : NULL; + if ($entity_type_id == 'domain_path' || $entity_type_id == 'domain_path_redirect') { + continue; + } $form['entity_types'][$entity_type_id] = [ '#type' => 'checkbox', '#title' => $entity_type->getLabel(), @@ -82,27 +86,46 @@ public function buildForm(array $form, FormStateInterface $form_state) { ]; } } - - $form['display_domain'] = [ +/* + $form['ui'] = [ '#type' => 'details', '#open' => TRUE, - '#title' => $this->t('Domain path alias title'), + '#title' => $this->t('UI Settings'), ]; +*/ + $form['language_method'] = [ + '#type' => 'radios', + '#title' => $this->t('The method of language detection'), + '#default_value' => !empty($config->get('alias_title')) ? $config->get('alias_title') : 'name', + '#options' => [ + LanguageInterface::TYPE_CONTENT => $this->t('Content language'), + LanguageInterface::TYPE_INTERFACE => $this->t('Interface text language'), + LanguageInterface::TYPE_URL => $this->t('Language from URLs') + ], + '#default_value' => !empty($config->get('language_method')) ? $config->get('language_method') : LanguageInterface::TYPE_CONTENT, + '#description' => $this->t('If you enabled multilingual content for certain domains, you need to set it according to your language settings.'), + ]; $options = [ 'name' => $this->t('The domain display name'), 'hostname' => $this->t('The raw hostname'), 'url' => $this->t('The domain base URL'), ]; - $form['display_domain']['alias_title'] = [ + $form['alias_title'] = [ '#type' => 'radios', - '#title' => $this->t('Title'), + '#title' => $this->t('Domain path alias title'), '#default_value' => !empty($config->get('alias_title')) ? $config->get('alias_title') : 'name', '#options' => $options, '#description' => $this->t('Select the text to display for each field in entity edition.'), ]; + $form['hide_path_alias_ui'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Hide the default URL alias UI'), + '#default_value' => !empty($config->get('hide_path_alias_ui')) ? $config->get('hide_path_alias_ui') : FALSE, + '#description' => $this->t('Hide the default URL alias options from the UI to avoid the confusion. Domain path will replace the default URL alias with each individual domains alias'), + ]; return parent::buildForm($form, $form_state); } @@ -112,7 +135,9 @@ public function buildForm(array $form, FormStateInterface $form_state) { public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('domain_path.settings') ->set('entity_types', $form_state->getValue('entity_types')) + ->set('language_method', $form_state->getValue('language_method')) ->set('alias_title', $form_state->getValue('alias_title')) + ->set('hide_path_alias_ui', $form_state->getValue('hide_path_alias_ui')) ->save(); parent::submitForm($form, $form_state); diff --git a/src/PathProcessor/DomainPathProcessor.php b/src/PathProcessor/DomainPathProcessor.php deleted file mode 100755 index 2348a60..0000000 --- a/src/PathProcessor/DomainPathProcessor.php +++ /dev/null @@ -1,151 +0,0 @@ -languageManager = $language_manager; - $this->entityTypeManager = $entity_type_manager; - $this->aliasManager = $alias_manager; - $this->domainNegotiator = $domain_negotiator; - } - - /** - * {@inheritdoc} - */ - public function processInbound($path, Request $request) { - if ($active = $this->domainNegotiator->getActiveDomain()) { - $properties = [ - 'alias' => $path, - 'domain_id' => $this->domainNegotiator->getActiveDomain()->id(), - 'language' => $this->languageManager->getCurrentLanguage()->getId(), - ]; - $domain_paths = $this->entityTypeManager->getStorage('domain_path')->loadByProperties($properties); - } - if (empty($domain_paths)) { - return $path; - } - $domain_path = reset($domain_paths); - - return $domain_path->getSource(); - } - - /** - * {@inheritdoc} - */ - public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) { - if (empty($options['alias']) && ($active_domain = $this->domainNegotiator->getActiveDomain())) { - // It's possible the path module has aliased this path already so we're - // going to revert that. - $unaliased_path = $this->aliasManager->getPathByAlias($path); - if (isset($options["language"])) { - $language = $options["language"]; - } - else { - $language = $this->languageManager->getCurrentLanguage(); - } - - // If an entity is not available in current active domain we should change the active domain. - if (!empty($options['entity'])) { - $entity = $options['entity']; - $langcode = $language->getId(); - - if ($entity instanceof TranslatableInterface && $entity->hasTranslation($langcode)) { - $entity = $entity->getTranslation($langcode); - } - - if ($entity instanceof ContentEntityBase && $entity->hasField('field_domain_access')) { - $entityDomainsList = \Drupal::service('domain.element_manager')->getFieldValues($entity, 'field_domain_access'); - if (!empty($entityDomainsList)) { - $entityDomainsIdList = array_keys($entityDomainsList); - if (!in_array($active_domain->id(), $entityDomainsIdList)) { - $active_domain = Domain::load($entityDomainsIdList[0]); - } - } - } - } - - $properties = [ - 'source' => $unaliased_path, - 'domain_id' => $active_domain->id(), - 'language' => $language->getId(), - ]; - $domain_paths = $this->entityTypeManager->getStorage('domain_path')->loadByProperties($properties); - if (empty($domain_paths)) { - return $path; - } - $domain_path = reset($domain_paths); - // If the unaliased path matches our domain path source (internal url) - // then we have a match and we output the alias, otherwise we just pass - // the original $path along. - return $domain_path->getAlias(); - } - - return $path; - } - -} diff --git a/tests/src/Functional/DomainPathCreateTest.php b/tests/src/Functional/DomainPathCreateTest.php old mode 100644 new mode 100755 index e962eea..cf0b238 --- a/tests/src/Functional/DomainPathCreateTest.php +++ b/tests/src/Functional/DomainPathCreateTest.php @@ -12,7 +12,7 @@ class DomainPathCreateTest extends DomainPathTestBase { /** * {@inheritdoc} */ - protected function setUp() { + protected function setUp(): void { parent::setUp(); } @@ -23,7 +23,6 @@ public function testDomainPathCreate() { // No domain paths should exist. $this->domainPathTableIsEmpty(); $node = $this->drupalCreateNode(); - $this->assertTrue($node, 'Node found in database.'); $domain_path_storage = \Drupal::service('entity_type.manager')->getStorage('domain_path'); $default_domain_id = NULL; foreach ($this->domains as $domain) { diff --git a/tests/src/Functional/DomainPathDomainTest.php b/tests/src/Functional/DomainPathDomainTest.php new file mode 100755 index 0000000..d05acfe --- /dev/null +++ b/tests/src/Functional/DomainPathDomainTest.php @@ -0,0 +1,51 @@ +domainPathTableIsEmpty(); + $node = $this->drupalCreateNode(); + $domain_path_storage = \Drupal::service('entity_type.manager')->getStorage('domain_path'); + + foreach ($this->domains as $domain) { + $alias = '/' . $this->randomMachineName(8); + $domain_path_storage->create([ + 'type' => 'domain_path', + 'alias' => $alias, + 'domain_id' => $domain->id(), + 'language' => $node->language()->getId(), + 'source' => '/node/' . $node->id(), + ])->save(); + $domain_paths[] = [ + 'alias' => $domain->getPath() . $alias, + 'path' => $node->id(), + 'text' => $node->getTitle(), + ]; + } + + foreach ($domain_paths as $domain_path) { + $this->drupalGet($domain_path['alias']); + $this->assertSession()->statusCodeEquals(200); + $this->assertSession()->pageTextContains($domain_path['text']); + } + } + +} diff --git a/tests/src/Functional/DomainPathNodeAliasTest.php b/tests/src/Functional/DomainPathNodeAliasTest.php old mode 100644 new mode 100755 index a9ce6f7..dac4b6a --- a/tests/src/Functional/DomainPathNodeAliasTest.php +++ b/tests/src/Functional/DomainPathNodeAliasTest.php @@ -12,7 +12,7 @@ class DomainPathNodeAliasTest extends DomainPathTestBase { /** * {@inheritdoc} */ - protected function setUp() { + protected function setUp(): void { parent::setUp(); } @@ -20,36 +20,41 @@ protected function setUp() { * Test domain path node aliases. */ public function testDomainPathNodeAliasesFill() { + // Set path from Node form. $edit = []; $edit['title[0][value]'] = $this->randomMachineName(8); $edit['body[0][value]'] = $this->randomMachineName(16); foreach ($this->domains as $domain) { - $domain_specific_alias_value = $this->randomMachineName(8); - $domain_specific_alias_path = "/$domain_specific_alias_value"; - $edit['domain_path[' . $domain->id() . ']'] = $domain_specific_alias_path; - if ($domain->isDefault()) { - $domain_paths_check['default'] = $domain_specific_alias_value; - } - else { - $domain_paths_check['specific'] = $domain_specific_alias_value; - } + $domain_alias_value = '/' . $this->randomMachineName(8); + $edit['domain_path[' . $domain->id() . '][path]'] = $domain_alias_value; + $domain_paths_check[$domain->id()] = $domain_alias_value; } - $edit['path[0][alias]'] = '/' . $this->randomMachineName(8); $this->drupalPostForm('node/add/page', $edit, t('Save')); - // Check that the node exists in the database. + + $storage = \Drupal::service('entity_type.manager')->getStorage('domain_path'); + foreach ($domain_paths_check as $domain_id => $domain_alias_value) { + $this->assertCount(1, $storage->loadByProperties([ + 'domain_id' => $domain_id, + 'alias' => $domain_alias_value, + ])); + } + + // Check values on node form. $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); - $this->assertTrue($node, 'Node found in database.'); $this->drupalGet('node/' . $node->id() . '/edit'); - $this->assertSession()->statusCodeEquals(200); - if (!empty($domain_paths_check['default'])) { - $this->drupalGet($domain_paths_check['default']); - $this->assertSession()->statusCodeEquals(200); + $session = $this->assertSession(); + foreach ($domain_paths_check as $domain_id => $domain_alias_value) { + $session->fieldValueEquals('domain_path[' . $domain_id . '][path]', $domain_alias_value); } - if (!empty($domain_paths_check['specific'])) { - $this->drupalGet($domain_paths_check['specific']); - $this->assertSession()->statusCodeNotEquals(200); + // Ensure aren't removed on second save. + $page = $this->getSession()->getPage(); + $page->pressButton('Save'); + $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); + $this->drupalGet('node/' . $node->id() . '/edit'); + $session = $this->assertSession(); + foreach ($domain_paths_check as $domain_id => $domain_alias_value) { + $session->fieldValueEquals('domain_path[' . $domain_id . '][path]', $domain_alias_value); } - } } diff --git a/tests/src/Functional/DomainPathTestBase.php b/tests/src/Functional/DomainPathTestBase.php old mode 100644 new mode 100755 index 1e1ce78..37b9928 --- a/tests/src/Functional/DomainPathTestBase.php +++ b/tests/src/Functional/DomainPathTestBase.php @@ -13,39 +13,31 @@ abstract class DomainPathTestBase extends DomainTestBase { */ protected $domains; - /** - * Sets a base hostname for running tests. - * - * When creating test domains, try to use $this->base_hostname or the - * domainCreateTestDomains() method. - * - * @var string - */ - public $base_hostname; - /** * Modules to enable. * * @var array */ - public static $modules = ['domain_path', 'field', 'node', 'user', 'path', 'system']; + public static $modules = [ + 'domain_path', + 'field', + 'node', + 'user', + 'path', + 'system', + ]; /** - * We use the standard profile for testing. - * - * @var string + * {@inheritdoc} */ - protected $profile = 'standard'; + protected $defaultTheme = 'stark'; /** * {@inheritdoc} */ - protected function setUp() { + protected function setUp(): void { parent::setUp(); - // Create Basic page and Article node types. - if ($this->profile != 'standard') { - $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); - } + // Create domains. $this->domainCreateTestDomains(2); $this->domains = $this->getDomains();