Download project

This commit is contained in:
Roman Pyrih
2024-11-20 09:09:44 +01:00
parent 547a138d6a
commit 5ff041757f
40737 changed files with 7766183 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
name-template: v$NEXT_PATCH_VERSION
tag-template: v$NEXT_PATCH_VERSION
categories:
- title: 🔨 Improvements
label: enhancement
- title: 🐛 Bug Fixes
label: bug
- title: 🚀 New Features
label: Feature
change-template: '- #$NUMBER: $TITLE by @$AUTHOR'
template: |
# Changes
$CHANGES

View File

@@ -0,0 +1,118 @@
name: PHP tests
on: [push, pull_request]
jobs:
php-linter:
name: PHP Syntax check 5.6|7.2|7.3|8.0|8.1
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: PHP syntax checker 5.6
uses: prestashop/github-action-php-lint/5.6@master
with:
folder-to-exclude: "! -path \"./tests/*\""
- name: PHP syntax checker 7.2
uses: prestashop/github-action-php-lint/7.2@master
- name: PHP syntax checker 8.0
uses: prestashop/github-action-php-lint/8.0@master
- name: PHP syntax checker 8.1
uses: prestashop/github-action-php-lint/8.1@master
php-cs-fixer:
name: PHP-CS-Fixer
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache vendor folder
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }}
- name: Cache composer folder
uses: actions/cache@v2
with:
path: ~/.composer/cache
key: php-composer-cache
- run: composer install
- name: Run PHP-CS-Fixer
run: vendor/bin/php-cs-fixer fix --diff --dry-run
phpstan:
name: PHPStan
runs-on: ubuntu-latest
strategy:
matrix:
prestashop_version: [
"https://github.com/PrestaShop/PrestaShop/releases/download/8.0.0/prestashop_8.0.0.zip",
"https://github.com/PrestaShop/PrestaShop/releases/download/1.7.4.4/prestashop_1.7.4.4.zip",
]
steps:
- name: Download PrestaShop code source
run: |
wget -O /tmp/prestashop.zip ${{ matrix.prestashop_version }}
unzip -o /tmp/prestashop.zip -d /tmp
unzip -o /tmp/prestashop.zip -d /tmp/prestashop
- name: Setup PHP with tools
uses: shivammathur/setup-php@v2
with:
php-version: 7.4
- name: Checkout
uses: actions/checkout@v2
- name: Cache vendor folder
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }}
- name: Cache composer folder
uses: actions/cache@v2
with:
path: ~/.composer/cache
key: php-composer-cache
- run: composer install
- name: Run PHPStan
env:
_PS_ROOT_DIR_: /tmp/prestashop
run: vendor/bin/phpstan
phpunit:
name: PHPUnit
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Cache vendor folder
uses: actions/cache@v3
with:
path: vendor
key: php-${{ hashFiles('composer.lock') }}
- name: Cache composer folder
uses: actions/cache@v3
with:
path: ~/.composer/cache
key: php-composer-cache
- name: Install dependencies
run: composer install
- name: PHPUnit tests 1.7
run: DOCKER_INTERNAL="1.7" make phpunit
- name: PHPUnit tests with PS 8
run: DOCKER_INTERNAL=8 make phpunit

View File

@@ -0,0 +1,3 @@
/vendor/
.php-cs-fixer.cache
.phpunit.result.cache

View File

@@ -0,0 +1,12 @@
<?php
$config = new PrestaShop\CodingStandards\CsFixer\Config();
$config
->setUsingCache(true)
->getFinder()
->in(__DIR__)
->exclude('translations')
->exclude('vendor');
return $config;

View File

@@ -0,0 +1,172 @@
Open Software License ("OSL") v. 3.0
This Open Software License (the "License") applies to any original work of
authorship (the "Original Work") whose owner (the "Licensor") has placed the
following licensing notice adjacent to the copyright notice for the Original
Work:
Licensed under the Open Software License version 3.0
1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free,
non-exclusive, sublicensable license, for the duration of the copyright, to do
the following:
a) to reproduce the Original Work in copies, either alone or as part of a
collective work;
b) to translate, adapt, alter, transform, modify, or arrange the Original
Work, thereby creating derivative works ("Derivative Works") based upon the
Original Work;
c) to distribute or communicate copies of the Original Work and Derivative
Works to the public, with the proviso that copies of Original Work or
Derivative Works that You distribute or communicate shall be licensed under
this Open Software License;
d) to perform the Original Work publicly; and
e) to display the Original Work publicly.
2. Grant of Patent License. Licensor grants You a worldwide, royalty-free,
non-exclusive, sublicensable license, under patent claims owned or controlled
by the Licensor that are embodied in the Original Work as furnished by the
Licensor, for the duration of the patents, to make, use, sell, offer for sale,
have made, and import the Original Work and Derivative Works.
3. Grant of Source Code License. The term "Source Code" means the preferred
form of the Original Work for making modifications to it and all available
documentation describing how to modify the Original Work. Licensor agrees to
provide a machine-readable copy of the Source Code of the Original Work along
with each copy of the Original Work that Licensor distributes. Licensor
reserves the right to satisfy this obligation by placing a machine-readable
copy of the Source Code in an information repository reasonably calculated to
permit inexpensive and convenient access by You for as long as Licensor
continues to distribute the Original Work.
4. Exclusions From License Grant. Neither the names of Licensor, nor the names
of any contributors to the Original Work, nor any of their trademarks or
service marks, may be used to endorse or promote products derived from this
Original Work without express prior permission of the Licensor. Except as
expressly stated herein, nothing in this License grants any license to
Licensor's trademarks, copyrights, patents, trade secrets or any other
intellectual property. No patent license is granted to make, use, sell, offer
for sale, have made, or import embodiments of any patent claims other than the
licensed claims defined in Section 2. No license is granted to the trademarks
of Licensor even if such marks are included in the Original Work. Nothing in
this License shall be interpreted to prohibit Licensor from licensing under
terms different from this License any Original Work that Licensor otherwise
would have a right to license.
5. External Deployment. The term "External Deployment" means the use,
distribution, or communication of the Original Work or Derivative Works in any
way such that the Original Work or Derivative Works may be used by anyone
other than You, whether those works are distributed or communicated to those
persons or made available as an application intended for use over a network.
As an express condition for the grants of license hereunder, You must treat
any External Deployment by You of the Original Work or a Derivative Work as a
distribution under section 1(c).
6. Attribution Rights. You must retain, in the Source Code of any Derivative
Works that You create, all copyright, patent, or trademark notices from the
Source Code of the Original Work, as well as any notices of licensing and any
descriptive text identified therein as an "Attribution Notice." You must cause
the Source Code for any Derivative Works that You create to carry a prominent
Attribution Notice reasonably calculated to inform recipients that You have
modified the Original Work.
7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that
the copyright in and to the Original Work and the patent rights granted herein
by Licensor are owned by the Licensor or are sublicensed to You under the
terms of this License with the permission of the contributor(s) of those
copyrights and patent rights. Except as expressly stated in the immediately
preceding sentence, the Original Work is provided under this License on an "AS
IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without
limitation, the warranties of non-infringement, merchantability or fitness for
a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK
IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this
License. No license to the Original Work is granted by this License except
under this disclaimer.
8. Limitation of Liability. Under no circumstances and under no legal theory,
whether in tort (including negligence), contract, or otherwise, shall the
Licensor be liable to anyone for any indirect, special, incidental, or
consequential damages of any character arising as a result of this License or
the use of the Original Work including, without limitation, damages for loss
of goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses. This limitation of liability shall not
apply to the extent applicable law prohibits such limitation.
9. Acceptance and Termination. If, at any time, You expressly assented to this
License, that assent indicates your clear and irrevocable acceptance of this
License and all of its terms and conditions. If You distribute or communicate
copies of the Original Work or a Derivative Work, You must make a reasonable
effort under the circumstances to obtain the express assent of recipients to
the terms of this License. This License conditions your rights to undertake
the activities listed in Section 1, including your right to create Derivative
Works based upon the Original Work, and doing so without honoring these terms
and conditions is prohibited by copyright law and international treaty.
Nothing in this License is intended to affect copyright exceptions and
limitations (including "fair use" or "fair dealing"). This License shall
terminate immediately and You may no longer exercise any of the rights granted
to You by this License upon your failure to honor the conditions in Section
1(c).
10. Termination for Patent Action. This License shall terminate automatically
and You may no longer exercise any of the rights granted to You by this
License as of the date You commence an action, including a cross-claim or
counterclaim, against Licensor or any licensee alleging that the Original Work
infringes a patent. This termination provision shall not apply for an action
alleging patent infringement by combinations of the Original Work with other
software or hardware.
11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this
License may be brought only in the courts of a jurisdiction wherein the
Licensor resides or in which Licensor conducts its primary business, and under
the laws of that jurisdiction excluding its conflict-of-law provisions. The
application of the United Nations Convention on Contracts for the
International Sale of Goods is expressly excluded. Any use of the Original
Work outside the scope of this License or after its termination shall be
subject to the requirements and penalties of copyright or patent law in the
appropriate jurisdiction. This section shall survive the termination of this
License.
12. Attorneys' Fees. In any action to enforce the terms of this License or
seeking damages relating thereto, the prevailing party shall be entitled to
recover its costs and expenses, including, without limitation, reasonable
attorneys' fees and costs incurred in connection with such action, including
any appeal of such action. This section shall survive the termination of this
License.
13. Miscellaneous. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent necessary
to make it enforceable.
14. Definition of "You" in This License. "You" throughout this License,
whether in upper or lower case, means an individual or a legal entity
exercising rights under, and complying with all of the terms of, this License.
For legal entities, "You" includes any entity that controls, is controlled by,
or is under common control with you. For purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the direction or
management of such entity, whether by contract or otherwise, or (ii) ownership
of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
15. Right to Use. You may use the Original Work in all ways not otherwise
restricted or conditioned by this License or by law, and Licensor promises not
to interfere with or be responsible for such uses by You.
16. Modification of This License. This License is Copyright © 2005 Lawrence
Rosen. Permission is granted to copy, distribute, or communicate this License
without modification. Nothing in this License permits You to modify this
License as applied to the Original Work or to Derivative Works. However, You
may modify the text of this License and copy, distribute or communicate your
modified version (the "Modified License") and apply it to other original works
of authorship subject to the following conditions: (i) You may not indicate in
any way that your Modified License is the "Open Software License" or "OSL" and
you may not use those names in the name of your Modified License; (ii) You
must replace the notice specified in the first paragraph above with the notice
"Licensed under <insert your license name here>" or with a notice of your own
that is not confusingly similar to the notice in this License; and (iii) You
may not claim that your original works are open source software unless your
Modified License has been approved by Open Source Initiative (OSI) and You
comply with its license review and certification process.

View File

@@ -0,0 +1,26 @@
DOCKER_INTERNAL ?= 8
DOCKER = $(shell docker ps 2> /dev/null)
check-docker:
ifndef DOCKER
$(error "DOCKER is unavailable on your system")
endif
phpunit: check-docker
docker pull prestashop/docker-internal-images:${DOCKER_INTERNAL}
@docker run --rm \
--name phpunit \
-e PS_DOMAIN=localhost \
-e PS_ENABLE_SSL=0 \
-e PS_DEV_MODE=1 \
-e XDEBUG_MODE=coverage \
-e XDEBUG_ENABLED=1 \
-v ${PWD}:/var/www/html/test-lib \
-w /var/www/html/test-lib \
prestashop/docker-internal-images:${DOCKER_INTERNAL} \
sh -c " \
service mariadb start && \
service apache2 start && \
_PS_ROOT_DIR_=/var/www/html/ vendor/bin/phpunit \
"
@echo phpunit passed

View File

@@ -0,0 +1,187 @@
# PrestaShop module dependencies library
The goal of this package is to help managing module dependencies.
Let's explain it with an actual case
Supposing our module needs modules A and B to work properly.
We will have to install this `module-lib-mbo-installer` and have a file named `module_dependencies.json` in the root folder of our module containing
```
{
"dependencies": [
{
"name" : "A"
},
{
"name" : "B"
}
]
}
```
The lib will start by checking if [PS MBO (Marketplace in the Back Office)](https://github.com/PrestaShopCorp/ps_mbo) is installed and enabled.
MBO needs to be installed first because we download other modules from the marketplace.
Then it will check for the modules A and B
## Installation
```
composer require prestashop/module-lib-mbo-installer
```
## Version Guidance
| Version | Status | Packagist -| Namespace | Repo | Docs | PHP Version |
|---------|----------------|----------------------|--------------|---------------------|---------------------|--------------|
| 1.x | Latest | `prestashop/module-lib-mbo-installer` | `Prestashop\ModuleLibMboInstaller` | [v1.x][lib-1-repo] | N/A | >=5.6 |
[lib-1-repo]: https://github.com/PrestaShopCorp/module-lib-mbo-installer/tree/main
## Usage
You have 2 methods available
- DependenciesBuilder::handleDependencies() : this method will return you the status of all the dependencies, including MBO, in an array
```php
[
'module_display_name' => string // your displayed module name
'module_name' => string // your module tech name
'module_version' => string
'ps_version' => string
'php_version' => string
'locale' => string // the shop locale
'dependencies' => [ // an array of all the dependencies defined + MBO
[
'name' => 'ps_mbo'
'installed' => bool
'enabled' => bool
'current_version' => string
'install' => string // route to install the module, if relevant
'enable' => string // route to enable the module, if relevant
'upgrade' => string // route to upgrade the module, if relevant
],
[
'name' => string // a dependent module
'installed' => bool
'enabled' => bool
'current_version' => string
'install' => string // route to install the module, if relevant
'enable' => string // route to enable the module, if relevant
'upgrade' => string // route to upgrade the module, if relevant
],
...
]
];
```
- DependenciesBuilder::areDependenciesMet() : this method will return you whether all the dependencies, including MBO, are installed and enabled
These 2 methods will help you gather informations about your dependencies and allow you to perform actions to resolve them.
### Examples of implementation
In most of the cases you'll want to show the dependencies of your module in the configuration page, to allow the "user" to fix them
You can use one of the examples above in the `getContent` method of your module's main file
#### Use the given public CDC
In your module
```php
$mboInstaller = new Prestashop\ModuleLibMboInstaller\DependencyBuilder($this);
$dependencies = $mboInstaller->handleDependencies();
$this->smarty->assign('dependencies', $dependencies);
return $this->display(__FILE__, 'views/templates/admin/dependency_builder.tpl');
```
In the template
```html
<!-- Load cdc library -->
<script src="https://assets.prestashop3.com/dst/mbo/v1/mbo-cdc-dependencies-resolver.umd.js"></script>
<!-- cdc container -->
<div id="cdc-container"></div>
<script defer>
const renderMboCdcDependencyResolver = window.mboCdcDependencyResolver.render
const context = {
...{$dependencies|json_encode},
onDependenciesResolved: () => console.log('Everything works!'),
onDependencyResolved: (dependencyData) => console.log('Dependency installed', dependencyData), // name, displayName, version
onDependencyFailed: (dependencyData) => console.log('Failed to install dependency', dependencyData),
onDependenciesFailed: () => console.log('There are some errors'),
}
renderMboCdcDependencyResolver(context, '#cdc-container')
</script>
```
This example uses our public CDC which will display a page with the status of the dependencies and an action button to resolve them all
![Dependencies lib CDC](./docs/modules_to_activate.png)
#### Do it yourself
In your module
```php
$mboInstaller = new Prestashop\ModuleLibMboInstaller\DependencyBuilder($this);
$dependencies = $mboInstaller->handleDependencies();
return $this->render(
'@Modules/examplemodule/views/templates/admin/dependency_builder.html.twig',
[
'dependencies' => $dependencies,
]
);
```
In the template
```js
<script>
$(document).on('click', '.module_action', function(event) {
event.preventDefault();
const moduleName = window.$(this).attr('data-module')
window.$.ajax({
method: 'POST',
url: window.$(this).attr('data-url'),
}).done((response) => {
console.log(response[moduleName])
if (response[moduleName].status === true) {
window.$.growl.notice({message: response[moduleName].msg});
window.location.reload();
} else {
window.$.growl.error({message: response[moduleName].msg});
}
});
})
</script>
```
```twig
{% for dependency in dependencies.dependencies %}
<div>
{{ dependency.name }} :
{% if dependency.installed is same as(true) and dependency.enabled is same as(true) %}
OK
{% elseif dependency.installed is same as(false) and dependency.install is defined %}
<a class="btn btn-primary module_action" href="#" data-module="{{ dependency.name }}" data-url="{{ dependency.install }}">
Install
</a>
{% elseif dependency.enable is defined %}
<a class="btn btn-primary module_action" href="#" data-module="{{ dependency.name }}" data-url="{{ dependency.enable }}">
Enable
</a>
{% else %}
NOK
{% endif %}
</div>
{% endfor%}
```

View File

@@ -0,0 +1,35 @@
{
"name": "prestashop/module-lib-mbo-installer",
"description": "A helper to ease the download PS MBO from the Addons Marketplace",
"license": "AFL-3.0",
"require": {
"php": ">=5.6",
"prestashop/module-lib-guzzle-adapter": "^0.6",
"ext-json": "*"
},
"config": {
"platform": {
"php": "7.4.33"
}
},
"autoload": {
"psr-4": {
"Prestashop\\ModuleLibMboInstaller\\": "src/"
}
},
"authors": [
{
"name": "PrestaShop SA",
"email": "contact@prestashop.com"
},
{
"name": "Mikatux",
"email": "mickael@mayeur.eu"
}
],
"require-dev": {
"phpunit/phpunit": "^9.5|^8.5|^5.7",
"prestashop/php-dev-tools": "^4.2|^3.16",
"phpstan/phpstan": "^1.9"
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -0,0 +1,21 @@
includes:
- %currentWorkingDirectory%/vendor/prestashop/php-dev-tools/phpstan/ps-module-extension.neon
parameters:
paths:
- src
bootstrapFiles:
- vendor/autoload.php
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- '#Method PrestaShop\\PrestaShop\\Core\\Addon\\Module\\ModuleManager::install\(\) invoked with 2 parameters, 1 required.#'
- '#Call to function is_null\(\) with PrestaShop\\PrestaShop\\Core\\Addon\\Module\\ModuleManager will always evaluate to false.#'
- '#Call to function is_null\(\) with PrestaShop\\PrestaShop\\Core\\Module\\ModuleManager will always evaluate to false.#'
- '#Property Prestashop\\ModuleLibMboInstaller\\Installer::\$moduleManager has unknown class PrestaShop\\PrestaShop\\Core\\Addon\\Module\\ModuleManager as its type.#'
- '#Property Prestashop\\ModuleLibMboInstaller\\Installer::\$moduleManager has unknown class PrestaShop\\PrestaShop\\Core\\Module\\ModuleManager as its type.#'
- '#Call to method install\(\) on an unknown class PrestaShop\\PrestaShop\\Core\\Addon\\Module\\ModuleManager.#'
- '#Call to method install\(\) on an unknown class PrestaShop\\PrestaShop\\Core\\Module\\ModuleManager.#'
- '#Call to method enable\(\) on an unknown class PrestaShop\\PrestaShop\\Core\\Addon\\Module\\ModuleManager.#'
- '#Call to method enable\(\) on an unknown class PrestaShop\\PrestaShop\\Core\\Module\\ModuleManager.#'
level: max

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="tests/bootstrap.php"
colors="true"
stopOnFailure="false"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
>
<php>
<ini name="memory_limit" value="-1"/>
</php>
<testsuites>
<testsuite name="Integration">
<directory suffix="Test.php">tests/Integration</directory>
</testsuite>
</testsuites>
<logging/>
</phpunit>

View File

@@ -0,0 +1,384 @@
<?php
namespace Prestashop\ModuleLibMboInstaller;
use Prestashop\ModuleLibGuzzleAdapter\Interfaces\ClientExceptionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
class DependencyBuilder
{
const DEPENDENCY_FILENAME = 'module_dependencies.json';
const GET_PARAMETER = 'mbo_action_needed';
/**
* @var \ModuleCore
*/
protected $module;
/**
* @var Router
*/
protected $router;
/**
* @param \ModuleCore $module
*
* @throws \Exception
*/
public function __construct($module)
{
$this->module = $module;
$this->buildRouter();
}
/**
* Handle dependencies behavior and return dependencies data array to be given to the CDC
*
* @return array{
* "module_display_name": string,
* "module_name": string,
* "module_version": string,
* "ps_version": string,
* "php_version": string,
* "locale": string,
* "dependencies": array{}|array{ps_mbo: array<string, bool|string|int>}
* }
*
* @throws \Exception
* @throws ClientExceptionInterface
*/
public function handleDependencies()
{
$this->handleMboInstallation();
return $this->buildDependenciesContext();
}
/**
* @return bool
*
* @throws \Exception
*/
public function areDependenciesMet()
{
$dependencies = $this->getDependencies(false);
foreach ($dependencies as $dependencyName => $dependency) {
if (
!array_key_exists('installed', $dependency)
|| !array_key_exists('enabled', $dependency)
|| false === $dependency['installed']
|| false === $dependency['enabled']
) {
return false;
}
}
return true;
}
/**
* Install or enable the MBO depending on the action requested
*
* @return void
*
* @throws \Exception|ClientExceptionInterface
*/
protected function handleMboInstallation()
{
if (!isset($_GET[self::GET_PARAMETER]) || !$this->isMboNeeded()) {
return;
}
$mboStatus = (new Presenter())->present();
$installer = new Installer(_PS_VERSION_);
if ($mboStatus['isInstalled'] && $mboStatus['isEnabled']) {
return;
}
$data = [Installer::MODULE_NAME => [
'status' => true,
]];
try {
if (!$mboStatus['isInstalled']) {
$installer->installModule();
} elseif (!$mboStatus['isEnabled']) {
$installer->enableModule();
}
} catch (\Exception $e) {
$data[Installer::MODULE_NAME] = [
'status' => false,
'msg' => $e->getMessage(),
];
}
// This call is done in ajax by the CDC, bypass the normal return
header('Content-type: application/json');
echo json_encode($data);
exit;
}
/**
* Build the dependencies data array to be given to the CDC
*
* @return array{
* "module_display_name": string,
* "module_name": string,
* "module_version": string,
* "ps_version": string,
* "php_version": string,
* "locale": string,
* "dependencies": array{}|array{ps_mbo: array<string, bool|string|int>}
* }
*
* @throws \Exception
*/
protected function buildDependenciesContext()
{
return [
'module_display_name' => (string) $this->module->displayName,
'module_name' => (string) $this->module->name,
'module_version' => (string) $this->module->version,
'ps_version' => (string) _PS_VERSION_,
'php_version' => (string) PHP_VERSION,
'locale' => $this->getLocale(),
'dependencies' => $this->getDependencies(true),
];
}
/**
* @return string
*/
private function getLocale()
{
$context = \ContextCore::getContext();
if ($context !== null && $context->employee !== null) {
$locale = \DbCore::getInstance()->getValue(
sprintf(
'SELECT `locale` FROM `%slang` WHERE `id_lang`=%s',
_DB_PREFIX_,
pSQL((string) $context->employee->id_lang)
)
);
}
if (empty($locale)) {
return 'en-GB';
}
return $locale;
}
/**
* @param string $moduleName
*
* @return array<string, string>
*/
protected function buildRoutesForModule($moduleName)
{
$urls = [];
foreach (['install', 'enable', 'upgrade'] as $action) {
$route = $this->router->generate('admin_module_manage_action', [
'action' => $action,
'module_name' => $moduleName,
]);
if (is_string($route)) {
$urls[$action] = $route;
}
}
return $urls;
}
/**
* @return void
*
* @throws \Exception
*/
protected function buildRouter()
{
global $kernel;
if (!$kernel instanceof \AppKernel) {
throw new \Exception('Unable to retrieve Symfony AppKernel.');
}
$container = $kernel->getContainer();
if (!$container instanceof ContainerInterface) {
throw new \Exception('Unable to retrieve Symfony container.');
}
$router = $container->get('router');
if (!$router instanceof Router) {
throw new \Exception('Unable to retrieve Symfony router.');
}
$this->router = $router;
}
/**
* @param bool $addRoutes
*
* @return array{
* "name": string,
* "installed": bool,
* "enabled": bool,
* "current_version": string,
* }|non-empty-array<string, bool|string>|null
*
* @throws \Exception
*/
protected function addMboInDependencies($addRoutes = false)
{
if (!$this->isMboNeeded()) {
return null;
}
$mboStatus = (new Presenter())->present();
$specification = [
'current_version' => (string) $mboStatus['version'],
'installed' => (bool) $mboStatus['isInstalled'],
'enabled' => (bool) $mboStatus['isEnabled'],
'name' => Installer::MODULE_NAME,
];
if (!$addRoutes) {
return $specification;
}
return array_merge(
$specification,
$this->buildRoutesForModule(Installer::MODULE_NAME)
);
}
/**
* @return bool
*/
protected function isMboNeeded()
{
return version_compare(_PS_VERSION_, '1.7.5', '>=');
}
/**
* @param bool $addRoutes
*
* @return array<string, array{
* "name": string,
* "installed": bool,
* "enabled": bool,
* "current_version": string,
* }>|array<ps_mbo, non-empty-array<string, bool|string>>
*
* @throws \Exception
*/
private function getDependencies($addRoutes = false)
{
$dependenciesContent = $this->getDependenciesSpecification();
if (empty($dependenciesContent['dependencies'])) {
$mboDependency = $this->addMboInDependencies($addRoutes);
if (null === $mboDependency) {
return [];
}
return [
Installer::MODULE_NAME => $mboDependency,
];
}
if ($this->isMboNeeded() && !isset($dependenciesContent['dependencies'][Installer::MODULE_NAME])) {
$dependenciesContent['dependencies'][] = [
'name' => Installer::MODULE_NAME,
];
}
$dependencies = [];
foreach ($dependenciesContent['dependencies'] as $dependency) {
if (!is_array($dependency) || !array_key_exists('name', $dependency)) {
continue;
}
$dependencyData = \DbCore::getInstance()->getRow(
sprintf(
'SELECT `id_module`, `active`, `version` FROM `%smodule` WHERE `name` = "%s"',
_DB_PREFIX_,
pSQL((string) $dependency['name'])
)
);
if ($dependencyData && is_array($dependencyData) && !empty($dependencyData['id_module'])) {
// For PS < 8.0, enable/disable for a module is decided by the shop association
// We assume that if the module is disabled for one shop, i's considered as disabled
$isModuleActiveForAllShops = (bool) \DbCore::getInstance()->getValue(
sprintf("SELECT id_module
FROM `%smodule_shop`
WHERE id_module=%d AND id_shop IN ('%s')
GROUP BY id_module
HAVING COUNT(*)=%d",
_DB_PREFIX_,
(int) $dependencyData['id_module'],
implode(',', array_map('intval', \Shop::getContextListShopID())),
(int) count(\Shop::getContextListShopID())
)
);
$dependencyData['active'] = $isModuleActiveForAllShops;
}
if ($addRoutes) {
$dependencies[$dependency['name']] = array_merge(
$dependency,
$this->buildRoutesForModule($dependency['name'])
);
} else {
$dependencies[$dependency['name']] = $dependency;
}
if (!$dependencyData) {
$dependencies[$dependency['name']]['installed'] = false;
$dependencies[$dependency['name']]['enabled'] = false;
continue;
}
$dependencies[$dependency['name']] = array_merge($dependencies[$dependency['name']], [
'installed' => true,
'enabled' => isset($dependencyData['active']) && (bool) $dependencyData['active'],
'current_version' => isset($dependencyData['version']) ? $dependencyData['version'] : null,
]);
}
return $dependencies;
}
/**
* @return array{
* "dependencies": array<string, string|int|bool>
* }
*
* @throws \Exception
*/
private function getDependenciesSpecification()
{
$dependencyFile = $this->module->getLocalPath() . self::DEPENDENCY_FILENAME;
if (!file_exists($dependencyFile)) {
throw new \Exception(self::DEPENDENCY_FILENAME . ' file is not found in ' . $this->module->getLocalPath());
}
if ($fileContent = file_get_contents($dependencyFile)) {
$dependenciesContent = json_decode($fileContent, true);
}
if (
!isset($dependenciesContent)
|| !is_array($dependenciesContent)
|| !array_key_exists('dependencies', $dependenciesContent)
|| json_last_error() != JSON_ERROR_NONE
) {
throw new \Exception(self::DEPENDENCY_FILENAME . ' file may be malformed.');
}
return $dependenciesContent;
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace Prestashop\ModuleLibMboInstaller;
use GuzzleHttp\Psr7\Request;
use Prestashop\ModuleLibGuzzleAdapter\ClientFactory;
use Prestashop\ModuleLibGuzzleAdapter\Interfaces\ClientExceptionInterface;
use Prestashop\ModuleLibGuzzleAdapter\Interfaces\HttpClientInterface;
use PrestaShop\PrestaShop\Core\Addon\Module\ModuleManagerBuilder;
class Installer
{
const ADDONS_URL = 'https://api-addons.prestashop.com';
const MODULE_ID = 39574;
const MODULE_NAME = 'ps_mbo';
/**
* @var HttpClientInterface
*/
protected $marketplaceClient;
/**
* @var \PrestaShop\PrestaShop\Core\Module\ModuleManager|\PrestaShop\PrestaShop\Core\Addon\Module\ModuleManager
*/
protected $moduleManager;
/**
* @var string
*/
protected $prestashopVersion;
/**
* @param string $prestashopVersion
*
* @throws \Exception
*/
public function __construct($prestashopVersion)
{
$moduleManagerBuilder = ModuleManagerBuilder::getInstance();
if (is_null($moduleManagerBuilder)) {
throw new \Exception('ModuleManagerBuilder::getInstance() failed');
}
$this->moduleManager = $moduleManagerBuilder->build();
if (is_null($this->moduleManager)) {
throw new \Exception('ModuleManagerBuilder::build() failed');
}
$this->marketplaceClient = (new ClientFactory())->getClient(['base_uri' => self::ADDONS_URL]);
$this->prestashopVersion = $prestashopVersion;
}
/**
* Installs ps_mbo module
*
* @return bool
*
* @throws ClientExceptionInterface
*/
public function installModule()
{
// On PrestaShop 1.7, the signature is install($source), with $source a module name or a path to an archive.
// On PrestaShop 8, the signature is install(string $name, $source = null).
if (version_compare($this->prestashopVersion, '8.0.0', '>=')) {
return $this->moduleManager->install(self::MODULE_NAME, $this->downloadModule());
}
return $this->moduleManager->install(self::MODULE_NAME);
}
/**
* Enable ps_mbo module
*
* @return bool
*
* @throws \Exception
*/
public function enableModule()
{
return $this->moduleManager->enable(self::MODULE_NAME);
}
/**
* Downloads ps_mbo module source from addons, store it and returns the file name
*
* @return string
*
* @throws \Exception|ClientExceptionInterface
*/
private function downloadModule()
{
$params = [
'id_module' => self::MODULE_ID,
'channel' => 'stable',
'method' => 'module',
'version' => $this->prestashopVersion,
];
$moduleData = $this->marketplaceClient->sendRequest(
new Request('POST', '/?' . http_build_query($params))
)->getBody()->getContents();
$temporaryZipFilename = tempnam(sys_get_temp_dir(), 'mod');
if ($temporaryZipFilename === false) {
throw new \Exception('Cannot create temporary file in ' . sys_get_temp_dir());
}
if (file_put_contents($temporaryZipFilename, $moduleData) !== false) {
return $temporaryZipFilename;
} else {
throw new \Exception('Cannot store module content in temporary file !');
}
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Prestashop\ModuleLibMboInstaller;
use PrestaShop\PrestaShop\Core\Addon\Module\ModuleManagerBuilder;
class Presenter
{
/**
* @return array<string, string|boolean|null>
*/
public function present()
{
/**
* @var \Module|null
*/
$mboModule = \Module::getInstanceByName(Installer::MODULE_NAME);
$version = null;
if ($mboModule) {
$version = $mboModule->version;
}
$moduleManagerBuilder = ModuleManagerBuilder::getInstance();
if (is_null($moduleManagerBuilder)) {
throw new \Exception('ModuleManagerBuilder::getInstance() failed');
}
$moduleManager = $moduleManagerBuilder->build();
if (is_null($moduleManager)) {
throw new \Exception('ModuleManagerBuilder::build() failed');
}
return [
'isPresentOnDisk' => (bool) $mboModule,
'isInstalled' => ($mboModule && $moduleManager->isInstalled(Installer::MODULE_NAME)),
'isEnabled' => ($mboModule && $moduleManager->isEnabled(Installer::MODULE_NAME)),
'version' => $version,
];
}
}