33
0
mirror of https://github.com/joomla-extensions/patchtester.git synced 2024-12-22 10:58:58 +00:00

Switching to PSR-12 and updating composer dependencies

This commit is contained in:
Hannes Papenberg 2022-09-08 10:54:04 +02:00
parent 397c64c3e4
commit 8234d9a14a
35 changed files with 3717 additions and 3760 deletions

View File

@ -3,11 +3,13 @@ kind: pipeline
name: default name: default
clone: clone:
depth: 42
steps: steps:
- name: composer - name: composer
image: joomlaprojects/docker-tools:develop image: joomlaprojects/docker-images:php7.4
volumes:
- name: composer-cache
path: /tmp/composer-cache
commands: commands:
- composer validate --no-check-all --strict - composer validate --no-check-all --strict
- composer install --no-progress --no-suggest - composer install --no-progress --no-suggest
@ -16,10 +18,15 @@ steps:
image: joomlaprojects/docker-images:php7.2 image: joomlaprojects/docker-images:php7.2
commands: commands:
- echo $(date) - echo $(date)
- ./administrator/components/com_patchtester/vendor/bin/phpcs --extensions=php -p --ignore=administrator/components/com_patchtester/vendor --standard=administrator/components/com_patchtester/vendor/joomla/cms-coding-standards/lib/Joomla-CMS administrator - ./administrator/components/com_patchtester/vendor/bin/phpcs --extensions=php -p --ignore=administrator/components/com_patchtester/vendor --ignore=build/packaging --standard=PSR12 .
- echo $(date) - echo $(date)
volumes:
- name: composer-cache
host:
path: /tmp/composer-cache
--- ---
kind: signature kind: signature
hmac: c5899584898d37d46fb70cb22487532d41719c7a836be7f67ad4ac3c2267dafa hmac: 66f585c17b678699c15f48673fa52585c02eddab99c4dcfa2f1e1e85960a2a31
... ...

20
.editorconfig Normal file
View File

@ -0,0 +1,20 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style end of lines and a blank line at the end of the file
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.php]
indent_style = space
indent_size = 4
[*.{js,json,scss,css,vue}]
indent_style = space
indent_size = 2

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -28,7 +29,6 @@ abstract class AbstractController
* @since 4.0.0 * @since 4.0.0
*/ */
protected $app; protected $app;
/** /**
* The object context * The object context
* *
@ -36,7 +36,6 @@ abstract class AbstractController
* @since 2.0 * @since 2.0
*/ */
protected $context; protected $context;
/** /**
* The default view to display * The default view to display
* *
@ -44,7 +43,6 @@ abstract class AbstractController
* @since 2.0 * @since 2.0
*/ */
protected $defaultView = 'pulls'; protected $defaultView = 'pulls';
/** /**
* Instantiate the controller * Instantiate the controller
* *
@ -55,7 +53,6 @@ abstract class AbstractController
public function __construct(CMSApplication $app) public function __construct(CMSApplication $app)
{ {
$this->app = $app; $this->app = $app;
// Set the context for the controller // Set the context for the controller
$this->context = 'com_patchtester.' . $this->getInput()->getCmd('view', $this->defaultView); $this->context = 'com_patchtester.' . $this->getInput()->getCmd('view', $this->defaultView);
} }
@ -95,14 +92,11 @@ abstract class AbstractController
*/ */
protected function initializeState($model) protected function initializeState($model)
{ {
$state = new Registry; $state = new Registry();
// Load the parameters. // Load the parameters.
$params = ComponentHelper::getParams('com_patchtester'); $params = ComponentHelper::getParams('com_patchtester');
$state->set('github_user', $params->get('org', 'joomla')); $state->set('github_user', $params->get('org', 'joomla'));
$state->set('github_repo', $params->get('repo', 'joomla-cms')); $state->set('github_repo', $params->get('repo', 'joomla-cms'));
return $state; return $state;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -13,6 +14,11 @@ use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Route;
use PatchTester\Model\PullModel; use PatchTester\Model\PullModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Controller class to apply patches * Controller class to apply patches
* *
@ -29,26 +35,18 @@ class ApplyController extends AbstractController
*/ */
public function execute() public function execute()
{ {
try try {
{
$model = new PullModel(null, Factory::getDbo()); $model = new PullModel(null, Factory::getDbo());
// Initialize the state for the model // Initialize the state for the model
$model->setState($this->initializeState($model)); $model->setState($this->initializeState($model));
if ($model->apply($this->getInput()->getUint('pull_id'))) {
if ($model->apply($this->getInput()->getUint('pull_id')))
{
$msg = Text::_('COM_PATCHTESTER_APPLY_OK'); $msg = Text::_('COM_PATCHTESTER_APPLY_OK');
} } else {
else
{
$msg = Text::_('COM_PATCHTESTER_NO_FILES_TO_PATCH'); $msg = Text::_('COM_PATCHTESTER_NO_FILES_TO_PATCH');
} }
$type = 'message'; $type = 'message';
} } catch (\Exception $e) {
catch (\Exception $e)
{
$msg = $e->getMessage(); $msg = $e->getMessage();
$type = 'error'; $type = 'error';
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -13,6 +14,11 @@ use Joomla\CMS\Language\Text;
use Joomla\Registry\Registry; use Joomla\Registry\Registry;
use PatchTester\Model\AbstractModel; use PatchTester\Model\AbstractModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Default display controller * Default display controller
* *
@ -27,7 +33,6 @@ class DisplayController extends AbstractController
* @since 4.0.0 * @since 4.0.0
*/ */
protected $defaultFullOrdering = 'a.pull_id DESC'; protected $defaultFullOrdering = 'a.pull_id DESC';
/** /**
* Execute the controller. * Execute the controller.
* *
@ -41,54 +46,40 @@ class DisplayController extends AbstractController
// Set up variables to build our classes // Set up variables to build our classes
$view = $this->getInput()->getCmd('view', $this->defaultView); $view = $this->getInput()->getCmd('view', $this->defaultView);
$format = $this->getInput()->getCmd('format', 'html'); $format = $this->getInput()->getCmd('format', 'html');
// Register the layout paths for the view // Register the layout paths for the view
$paths = new \SplPriorityQueue; $paths = new \SplPriorityQueue();
// Add the path for template overrides // Add the path for template overrides
$paths->insert(JPATH_THEMES . '/' . $this->getApplication()->getTemplate() . '/html/com_patchtester/' . $view, 2); $paths->insert(JPATH_THEMES . '/' . $this->getApplication()->getTemplate() . '/html/com_patchtester/' . $view, 2);
// Add the path for the default layouts // Add the path for the default layouts
$paths->insert(dirname(__DIR__) . '/View/' . ucfirst($view) . '/tmpl', 1); $paths->insert(dirname(__DIR__) . '/View/' . ucfirst($view) . '/tmpl', 1);
// Build the class names for the model and view // Build the class names for the model and view
$viewClass = '\\PatchTester\\View\\' . ucfirst($view) . '\\' . ucfirst($view) . ucfirst($format) . 'View'; $viewClass = '\\PatchTester\\View\\' . ucfirst($view) . '\\' . ucfirst($view) . ucfirst($format) . 'View';
$modelClass = '\\PatchTester\\Model\\' . ucfirst($view) . 'Model'; $modelClass = '\\PatchTester\\Model\\' . ucfirst($view) . 'Model';
// Sanity check - Ensure our classes exist // Sanity check - Ensure our classes exist
if (!class_exists($viewClass)) if (!class_exists($viewClass)) {
{
// Try to use a default view // Try to use a default view
$viewClass = '\\PatchTester\\View\\Default' . ucfirst($format) . 'View'; $viewClass = '\\PatchTester\\View\\Default' . ucfirst($format) . 'View';
if (!class_exists($viewClass)) {
if (!class_exists($viewClass))
{
throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_VIEW_NOT_FOUND', $view, $format), 500); throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_VIEW_NOT_FOUND', $view, $format), 500);
} }
} }
if (!class_exists($modelClass)) if (!class_exists($modelClass)) {
{
throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_MODEL_NOT_FOUND', $modelClass), 500); throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_MODEL_NOT_FOUND', $modelClass), 500);
} }
// Initialize the model class now; need to do it before setting the state to get required data from it // Initialize the model class now; need to do it before setting the state to get required data from it
$model = new $modelClass($this->context, null, Factory::getDbo()); $model = new $modelClass($this->context, null, Factory::getDbo());
// Initialize the state for the model // Initialize the state for the model
$state = $this->initializeState($model); $state = $this->initializeState($model);
foreach ($state as $key => $value) {
foreach ($state as $key => $value)
{
$model->setState($key, $value); $model->setState($key, $value);
} }
// Initialize the view class now // Initialize the view class now
$view = new $viewClass($model, $paths); $view = new $viewClass($model, $paths);
// Echo the rendered view for the application // Echo the rendered view for the application
echo $view->render(); echo $view->render();
// Finished! // Finished!
return true; return true;
} }
@ -106,7 +97,6 @@ class DisplayController extends AbstractController
{ {
$state = parent::initializeState($model); $state = parent::initializeState($model);
$app = $this->getApplication(); $app = $this->getApplication();
// Load the filter state. // Load the filter state.
$state->set('filter.search', $app->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '')); $state->set('filter.search', $app->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', ''));
$state->set('filter.applied', $app->getUserStateFromRequest($this->context . '.filter.applied', 'filter_applied', '')); $state->set('filter.applied', $app->getUserStateFromRequest($this->context . '.filter.applied', 'filter_applied', ''));
@ -114,44 +104,32 @@ class DisplayController extends AbstractController
$state->set('filter.rtc', $app->getUserStateFromRequest($this->context . '.filter.rtc', 'filter_rtc', '')); $state->set('filter.rtc', $app->getUserStateFromRequest($this->context . '.filter.rtc', 'filter_rtc', ''));
$state->set('filter.npm', $app->getUserStateFromRequest($this->context . '.filter.npm', 'filter_npm', '')); $state->set('filter.npm', $app->getUserStateFromRequest($this->context . '.filter.npm', 'filter_npm', ''));
$state->set('filter.label', $app->getUserStateFromRequest($this->context . '.filter.label', 'filter_label', '')); $state->set('filter.label', $app->getUserStateFromRequest($this->context . '.filter.label', 'filter_label', ''));
// Pre-fill the limits. // Pre-fill the limits.
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->input->get('list_limit', 20), 'uint'); $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->input->get('list_limit', 20), 'uint');
$state->set('list.limit', $limit); $state->set('list.limit', $limit);
$fullOrdering = $app->getUserStateFromRequest($this->context . '.fullorder', 'list_fullordering', $this->defaultFullOrdering); $fullOrdering = $app->getUserStateFromRequest($this->context . '.fullorder', 'list_fullordering', $this->defaultFullOrdering);
$orderingParts = explode(' ', $fullOrdering); $orderingParts = explode(' ', $fullOrdering);
if (count($orderingParts) !== 2) {
if (count($orderingParts) !== 2)
{
$fullOrdering = $this->defaultFullOrdering; $fullOrdering = $this->defaultFullOrdering;
$orderingParts = explode(' ', $fullOrdering); $orderingParts = explode(' ', $fullOrdering);
} }
$state->set('list.fullordering', $fullOrdering); $state->set('list.fullordering', $fullOrdering);
// The 2nd part will be considered the direction // The 2nd part will be considered the direction
$direction = $orderingParts[array_key_last($orderingParts)]; $direction = $orderingParts[array_key_last($orderingParts)];
if (in_array(strtoupper($direction), ['ASC', 'DESC', ''])) {
if (in_array(strtoupper($direction), ['ASC', 'DESC', '']))
{
$state->set('list.direction', $direction); $state->set('list.direction', $direction);
} }
// The 1st part will be the ordering // The 1st part will be the ordering
$ordering = $orderingParts[array_key_first($orderingParts)]; $ordering = $orderingParts[array_key_first($orderingParts)];
if (in_array($ordering, $model->getSortFields())) {
if (in_array($ordering, $model->getSortFields()))
{
$state->set('list.ordering', $ordering); $state->set('list.ordering', $ordering);
} }
$value = $app->getUserStateFromRequest($this->context . '.limitstart', 'limitstart', 0); $value = $app->getUserStateFromRequest($this->context . '.limitstart', 'limitstart', 0);
$limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0); $limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
$state->set('list.start', $limitstart); $state->set('list.start', $limitstart);
return $state; return $state;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -13,6 +14,10 @@ use Joomla\CMS\Language\Text;
use Joomla\CMS\Response\JsonResponse; use Joomla\CMS\Response\JsonResponse;
use PatchTester\Model\PullsModel; use PatchTester\Model\PullsModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Controller class to fetch remote data * Controller class to fetch remote data
* *
@ -35,69 +40,51 @@ class FetchController extends AbstractController
$this->getApplication()->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false); $this->getApplication()->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false);
$this->getApplication()->setHeader('Pragma', 'no-cache'); $this->getApplication()->setHeader('Pragma', 'no-cache');
$this->getApplication()->setHeader('Content-Type', $this->getApplication()->mimeType . '; charset=' . $this->getApplication()->charSet); $this->getApplication()->setHeader('Content-Type', $this->getApplication()->mimeType . '; charset=' . $this->getApplication()->charSet);
$session = Factory::getSession(); $session = Factory::getSession();
try {
try
{
// Fetch our page from the session // Fetch our page from the session
$page = $session->get('com_patchtester_fetcher_page', 1); $page = $session->get('com_patchtester_fetcher_page', 1);
$model = new PullsModel();
$model = new PullsModel;
// Initialize the state for the model // Initialize the state for the model
$state = $this->initializeState($model); $state = $this->initializeState($model);
foreach ($state as $key => $value) {
foreach ($state as $key => $value)
{
$model->setState($key, $value); $model->setState($key, $value);
} }
$status = $model->requestFromGithub($page); $status = $model->requestFromGithub($page);
} } catch (\Exception $e) {
catch (\Exception $e)
{
$response = new JsonResponse($e); $response = new JsonResponse($e);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
// Store the last page to the session if given one // Store the last page to the session if given one
if (isset($status['lastPage']) && $status['lastPage'] !== false) if (isset($status['lastPage']) && $status['lastPage'] !== false) {
{
$session->set('com_patchtester_fetcher_last_page', $status['lastPage']); $session->set('com_patchtester_fetcher_last_page', $status['lastPage']);
} }
// Update the UI and session now // Update the UI and session now
if ($status['complete'] || $page === $session->get('com_patchtester_fetcher_last_page', false)) if ($status['complete'] || $page === $session->get('com_patchtester_fetcher_last_page', false)) {
{
$status['complete'] = true; $status['complete'] = true;
$status['header'] = Text::_('COM_PATCHTESTER_FETCH_SUCCESSFUL', true); $status['header'] = Text::_('COM_PATCHTESTER_FETCH_SUCCESSFUL', true);
$message = Text::_('COM_PATCHTESTER_FETCH_COMPLETE_CLOSE_WINDOW', true); $message = Text::_('COM_PATCHTESTER_FETCH_COMPLETE_CLOSE_WINDOW', true);
} } elseif (isset($status['page'])) {
elseif (isset($status['page']))
{
$session->set('com_patchtester_fetcher_page', $status['page']); $session->set('com_patchtester_fetcher_page', $status['page']);
$message = Text::sprintf('COM_PATCHTESTER_FETCH_PAGE_NUMBER', $status['page']); $message = Text::sprintf('COM_PATCHTESTER_FETCH_PAGE_NUMBER', $status['page']);
if ($session->has('com_patchtester_fetcher_last_page')) if ($session->has('com_patchtester_fetcher_last_page')) {
{
$message = Text::sprintf( $message = Text::sprintf(
'COM_PATCHTESTER_FETCH_PAGE_NUMBER_OF_TOTAL', $status['page'], $session->get('com_patchtester_fetcher_last_page') 'COM_PATCHTESTER_FETCH_PAGE_NUMBER_OF_TOTAL',
$status['page'],
$session->get('com_patchtester_fetcher_last_page')
); );
} }
} }
$response = new JsonResponse($status, $message, false, true); $response = new JsonResponse($status, $message, false, true);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(); $this->getApplication()->close();
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -18,6 +19,10 @@ use PatchTester\Model\PullModel;
use PatchTester\Model\PullsModel; use PatchTester\Model\PullsModel;
use PatchTester\Model\TestsModel; use PatchTester\Model\TestsModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Controller class to reset the system state * Controller class to reset the system state
* *
@ -34,117 +39,90 @@ class ResetController extends AbstractController
*/ */
public function execute(): void public function execute(): void
{ {
try try {
{
$hasErrors = false; $hasErrors = false;
$revertErrored = false; $revertErrored = false;
$pullModel = new PullModel(null, Factory::getDbo()); $pullModel = new PullModel(null, Factory::getDbo());
$pullsModel = new PullsModel($this->context, null, Factory::getDbo()); $pullsModel = new PullsModel($this->context, null, Factory::getDbo());
$testsModel = new TestsModel(null, Factory::getDbo()); $testsModel = new TestsModel(null, Factory::getDbo());
// Check the applied patches in the database first // Check the applied patches in the database first
$appliedPatches = $testsModel->getAppliedPatches(); $appliedPatches = $testsModel->getAppliedPatches();
$params = ComponentHelper::getParams('com_patchtester'); $params = ComponentHelper::getParams('com_patchtester');
// Decide based on repository settings whether patch will be applied through Github or CIServer // Decide based on repository settings whether patch will be applied through Github or CIServer
if ((bool) $params->get('ci_switch', 1)) if ((bool) $params->get('ci_switch', 1)) {
{
// Let's try to cleanly revert all applied patches with ci // Let's try to cleanly revert all applied patches with ci
foreach ($appliedPatches as $patch) foreach ($appliedPatches as $patch) {
{ try {
try
{
$pullModel->revertWithCIServer($patch->id); $pullModel->revertWithCIServer($patch->id);
} } catch (\RuntimeException $e) {
catch (\RuntimeException $e)
{
$revertErrored = true; $revertErrored = true;
} }
} }
} } else {
else
{
// Let's try to cleanly revert all applied patches // Let's try to cleanly revert all applied patches
foreach ($appliedPatches as $patch) foreach ($appliedPatches as $patch) {
{ try {
try
{
$pullModel->revertWithGitHub($patch->id); $pullModel->revertWithGitHub($patch->id);
} } catch (\RuntimeException $e) {
catch (\RuntimeException $e)
{
$revertErrored = true; $revertErrored = true;
} }
} }
} }
// If we errored out reverting patches, we'll need to truncate the table // If we errored out reverting patches, we'll need to truncate the table
if ($revertErrored) if ($revertErrored) {
{ try {
try
{
$testsModel->truncateTable(); $testsModel->truncateTable();
} } catch (\RuntimeException $e) {
catch (\RuntimeException $e)
{
$hasErrors = true; $hasErrors = true;
$this->getApplication()->enqueueMessage( $this->getApplication()->enqueueMessage(
Text::sprintf('COM_PATCHTESTER_ERROR_TRUNCATING_PULLS_TABLE', $e->getMessage()), 'error' Text::sprintf('COM_PATCHTESTER_ERROR_TRUNCATING_PULLS_TABLE', $e->getMessage()),
'error'
); );
} }
} }
// Now truncate the pulls table // Now truncate the pulls table
try try {
{
$pullsModel->truncateTable(); $pullsModel->truncateTable();
} } catch (\RuntimeException $e) {
catch (\RuntimeException $e)
{
$hasErrors = true; $hasErrors = true;
$this->getApplication()->enqueueMessage( $this->getApplication()->enqueueMessage(
Text::sprintf('COM_PATCHTESTER_ERROR_TRUNCATING_TESTS_TABLE', $e->getMessage()), 'error' Text::sprintf('COM_PATCHTESTER_ERROR_TRUNCATING_TESTS_TABLE', $e->getMessage()),
'error'
); );
} }
// Check the backups directory to see if any .txt files remain; clear them if so // Check the backups directory to see if any .txt files remain; clear them if so
$backups = Folder::files(JPATH_COMPONENT . '/backups', '.txt'); $backups = Folder::files(JPATH_COMPONENT . '/backups', '.txt');
if (count($backups)) if (count($backups)) {
{ foreach ($backups as $file) {
foreach ($backups as $file) if (!File::delete(JPATH_COMPONENT . '/backups/' . $file)) {
{
if (!File::delete(JPATH_COMPONENT . '/backups/' . $file))
{
$this->getApplication()->enqueueMessage( $this->getApplication()->enqueueMessage(
Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_DELETE_FILE', JPATH_COMPONENT . '/backups/' . $file), 'error' Text::sprintf('COM_PATCHTESTER_ERROR_CANNOT_DELETE_FILE', JPATH_COMPONENT . '/backups/' . $file),
'error'
); );
$hasErrors = true; $hasErrors = true;
} }
} }
} }
// Processing completed, inform the user of a success or fail // Processing completed, inform the user of a success or fail
if ($hasErrors) if ($hasErrors) {
{
$msg = Text::sprintf( $msg = Text::sprintf(
'COM_PATCHTESTER_RESET_HAS_ERRORS', JPATH_COMPONENT . '/backups', Factory::getDbo()->replacePrefix('#__patchtester_tests') 'COM_PATCHTESTER_RESET_HAS_ERRORS',
JPATH_COMPONENT . '/backups',
Factory::getDbo()->replacePrefix('#__patchtester_tests')
); );
$type = 'warning'; $type = 'warning';
} } else {
else
{
$msg = Text::_('COM_PATCHTESTER_RESET_OK'); $msg = Text::_('COM_PATCHTESTER_RESET_OK');
$type = 'notice'; $type = 'notice';
} }
} } catch (\Exception $exception) {
catch (\Exception $exception)
{
$msg = $exception->getMessage(); $msg = $exception->getMessage();
$type = 'error'; $type = 'error';
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -13,6 +14,10 @@ use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Route;
use PatchTester\Model\PullModel; use PatchTester\Model\PullModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Controller class to revert patches * Controller class to revert patches
* *
@ -29,20 +34,14 @@ class RevertController extends AbstractController
*/ */
public function execute() public function execute()
{ {
try try {
{
$model = new PullModel(null, Factory::getDbo()); $model = new PullModel(null, Factory::getDbo());
// Initialize the state for the model // Initialize the state for the model
$model->setState($this->initializeState($model)); $model->setState($this->initializeState($model));
$model->revert($this->getInput()->getUint('pull_id')); $model->revert($this->getInput()->getUint('pull_id'));
$msg = Text::_('COM_PATCHTESTER_REVERT_OK'); $msg = Text::_('COM_PATCHTESTER_REVERT_OK');
$type = 'message'; $type = 'message';
} } catch (\Exception $e) {
catch (\Exception $e)
{
$msg = $e->getMessage(); $msg = $e->getMessage();
$type = 'error'; $type = 'error';
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -15,6 +16,10 @@ use Joomla\CMS\Session\Session;
use PatchTester\Helper; use PatchTester\Helper;
use PatchTester\Model\TestsModel; use PatchTester\Model\TestsModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Controller class to start fetching remote data * Controller class to start fetching remote data
* *
@ -37,94 +42,54 @@ class StartfetchController extends AbstractController
$this->getApplication()->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false); $this->getApplication()->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', false);
$this->getApplication()->setHeader('Pragma', 'no-cache'); $this->getApplication()->setHeader('Pragma', 'no-cache');
$this->getApplication()->setHeader('Content-Type', $this->getApplication()->mimeType . '; charset=' . $this->getApplication()->charSet); $this->getApplication()->setHeader('Content-Type', $this->getApplication()->mimeType . '; charset=' . $this->getApplication()->charSet);
// Check for a valid token. If invalid, send a 403 with the error message. // Check for a valid token. If invalid, send a 403 with the error message.
if (!Session::checkToken('request')) if (!Session::checkToken('request')) {
{
$response = new JsonResponse(new \Exception(Text::_('JINVALID_TOKEN'), 403)); $response = new JsonResponse(new \Exception(Text::_('JINVALID_TOKEN'), 403));
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
// Make sure we can fetch the data from GitHub - throw an error on < 10 available requests // Make sure we can fetch the data from GitHub - throw an error on < 10 available requests
try try {
{
$rateResponse = Helper::initializeGithub()->getRateLimit(); $rateResponse = Helper::initializeGithub()->getRateLimit();
$rate = json_decode($rateResponse->body); $rate = json_decode($rateResponse->body);
} } catch (\Exception $e) {
catch (\Exception $e) $response = new JsonResponse(new \Exception(Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $e->getMessage()), $e->getCode(), $e));
{
$response = new JsonResponse(
new \Exception(
Text::sprintf('COM_PATCHTESTER_COULD_NOT_CONNECT_TO_GITHUB', $e->getMessage()),
$e->getCode(),
$e
)
);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
// If over the API limit, we can't build this list // If over the API limit, we can't build this list
if ($rate->resources->core->remaining < 10) if ($rate->resources->core->remaining < 10) {
{ $response = new JsonResponse(new \Exception(Text::sprintf('COM_PATCHTESTER_API_LIMIT_LIST', Factory::getDate($rate->resources->core->reset)), 429));
$response = new JsonResponse(
new \Exception(
Text::sprintf('COM_PATCHTESTER_API_LIMIT_LIST', Factory::getDate($rate->resources->core->reset)),
429
)
);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
$testsModel = new TestsModel(null, Factory::getDbo()); $testsModel = new TestsModel(null, Factory::getDbo());
try {
try
{
// Sanity check, ensure there aren't any applied patches // Sanity check, ensure there aren't any applied patches
if (count($testsModel->getAppliedPatches()) >= 1) if (count($testsModel->getAppliedPatches()) >= 1) {
{
$response = new JsonResponse(new \Exception(Text::_('COM_PATCHTESTER_ERROR_APPLIED_PATCHES'), 500)); $response = new JsonResponse(new \Exception(Text::_('COM_PATCHTESTER_ERROR_APPLIED_PATCHES'), 500));
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
} } catch (\Exception $e) {
catch (\Exception $e)
{
$response = new JsonResponse($e); $response = new JsonResponse($e);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(1); $this->getApplication()->close(1);
} }
// We're able to successfully pull data, prepare our environment // We're able to successfully pull data, prepare our environment
Factory::getSession()->set('com_patchtester_fetcher_page', 1); Factory::getSession()->set('com_patchtester_fetcher_page', 1);
$response = new JsonResponse(array('complete' => false, 'header' => Text::_('COM_PATCHTESTER_FETCH_PROCESSING', true)), Text::sprintf('COM_PATCHTESTER_FETCH_PAGE_NUMBER', 1), false, true);
$response = new JsonResponse(
array('complete' => false, 'header' => Text::_('COM_PATCHTESTER_FETCH_PROCESSING', true)),
Text::sprintf('COM_PATCHTESTER_FETCH_PAGE_NUMBER', 1),
false,
true
);
$this->getApplication()->sendHeaders(); $this->getApplication()->sendHeaders();
echo json_encode($response); echo json_encode($response);
$this->getApplication()->close(); $this->getApplication()->close();
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -11,7 +12,9 @@ namespace PatchTester\Field;
use Joomla\CMS\Factory; use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField; use Joomla\CMS\Form\Field\ListField;
defined('_JEXEC') or die; // phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* List of available branches. * List of available branches.
@ -28,7 +31,6 @@ class BranchField extends ListField
* @since 4.1.0 * @since 4.1.0
*/ */
protected $type = 'Branch'; protected $type = 'Branch';
/** /**
* Build a list of available branches. * Build a list of available branches.
* *
@ -40,15 +42,12 @@ class BranchField extends ListField
{ {
$db = Factory::getContainer()->get('DatabaseDriver'); $db = Factory::getContainer()->get('DatabaseDriver');
$query = $db->getQuery(true); $query = $db->getQuery(true);
$query->select('DISTINCT(' . $db->quoteName('branch') . ') AS ' . $db->quoteName('text')) $query->select('DISTINCT(' . $db->quoteName('branch') . ') AS ' . $db->quoteName('text'))
->select($db->quoteName('branch', 'value')) ->select($db->quoteName('branch', 'value'))
->from('#__patchtester_pulls') ->from('#__patchtester_pulls')
->where($db->quoteName('branch') . ' != ' . $db->quote('')) ->where($db->quoteName('branch') . ' != ' . $db->quote(''))
->order($db->quoteName('branch') . ' ASC'); ->order($db->quoteName('branch') . ' ASC');
$options = $db->setQuery($query)->loadAssocList(); $options = $db->setQuery($query)->loadAssocList();
return array_merge(parent::getOptions(), $options); return array_merge(parent::getOptions(), $options);
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -11,7 +12,9 @@ namespace PatchTester\Field;
use Joomla\CMS\Factory; use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\ListField; use Joomla\CMS\Form\Field\ListField;
defined('_JEXEC') or die; // phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* List of available banks. * List of available banks.
@ -28,7 +31,6 @@ class LabelField extends ListField
* @since 4.1.0 * @since 4.1.0
*/ */
protected $type = 'Label'; protected $type = 'Label';
/** /**
* Build a list of available fields. * Build a list of available fields.
* *
@ -40,14 +42,11 @@ class LabelField extends ListField
{ {
$db = Factory::getContainer()->get('DatabaseDriver'); $db = Factory::getContainer()->get('DatabaseDriver');
$query = $db->getQuery(true); $query = $db->getQuery(true);
$query->select('DISTINCT(' . $db->quoteName('name') . ') AS ' . $db->quoteName('text')) $query->select('DISTINCT(' . $db->quoteName('name') . ') AS ' . $db->quoteName('text'))
->select($db->quoteName('name', 'value')) ->select($db->quoteName('name', 'value'))
->from($db->quoteName('#__patchtester_pulls_labels')) ->from($db->quoteName('#__patchtester_pulls_labels'))
->order($db->quoteName('name') . ' ASC'); ->order($db->quoteName('name') . ' ASC');
$options = $db->setQuery($query)->loadAssocList(); $options = $db->setQuery($query)->loadAssocList();
return array_merge(parent::getOptions(), $options); return array_merge(parent::getOptions(), $options);
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -24,7 +25,6 @@ class UnexpectedResponse extends \DomainException
* @since 3.0.0 * @since 3.0.0
*/ */
private $response; private $response;
/** /**
* Constructor * Constructor
* *
@ -38,7 +38,6 @@ class UnexpectedResponse extends \DomainException
public function __construct(Response $response, $message = '', $code = 0, \Exception $previous = null) public function __construct(Response $response, $message = '', $code = 0, \Exception $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
$this->response = $response; $this->response = $response;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -28,7 +29,6 @@ class GitHub
* @since 3.0.0 * @since 3.0.0
*/ */
protected $options; protected $options;
/** /**
* The HTTP client object to use in sending HTTP requests. * The HTTP client object to use in sending HTTP requests.
* *
@ -36,7 +36,6 @@ class GitHub
* @since 3.0.0 * @since 3.0.0
*/ */
protected $client; protected $client;
/** /**
* Constructor. * Constructor.
* *
@ -47,7 +46,7 @@ class GitHub
*/ */
public function __construct(Registry $options = null, Http $client = null) public function __construct(Registry $options = null, Http $client = null)
{ {
$this->options = $options ?: new Registry; $this->options = $options ?: new Registry();
$this->client = $client ?: HttpFactory::getHttp($options); $this->client = $client ?: HttpFactory::getHttp($options);
} }
@ -78,15 +77,10 @@ class GitHub
{ {
// Build the request path. // Build the request path.
$path = "/repos/$user/$repo/pulls/" . (int) $pullId; $path = "/repos/$user/$repo/pulls/" . (int) $pullId;
// Build the request headers. // Build the request headers.
$headers = array('Accept' => 'application/vnd.github.diff'); $headers = array('Accept' => 'application/vnd.github.diff');
$prepared = $this->prepareRequest($path, 0, 0, $headers); $prepared = $this->prepareRequest($path, 0, 0, $headers);
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
);
} }
/** /**
@ -103,13 +97,14 @@ class GitHub
* *
* @since 3.0.0 * @since 3.0.0
*/ */
protected function prepareRequest($path, $page = 0, $limit = 0, protected function prepareRequest(
$path,
$page = 0,
$limit = 0,
array $headers = array() array $headers = array()
) { ) {
$url = $this->fetchUrl($path, $page, $limit); $url = $this->fetchUrl($path, $page, $limit);
if ($token = $this->options->get('gh.token', false)) {
if ($token = $this->options->get('gh.token', false))
{
$headers['Authorization'] = "token $token"; $headers['Authorization'] = "token $token";
} }
@ -134,16 +129,13 @@ class GitHub
{ {
// Get a new Uri object using the API URL and given path. // Get a new Uri object using the API URL and given path.
$uri = new Uri($this->options->get('api.url') . $path); $uri = new Uri($this->options->get('api.url') . $path);
// If we have a defined page number add it to the JUri object. // If we have a defined page number add it to the JUri object.
if ($page > 0) if ($page > 0) {
{
$uri->setVar('page', (int) $page); $uri->setVar('page', (int) $page);
} }
// If we have a defined items per page add it to the JUri object. // If we have a defined items per page add it to the JUri object.
if ($limit > 0) if ($limit > 0) {
{
$uri->setVar('per_page', (int) $limit); $uri->setVar('per_page', (int) $limit);
} }
@ -164,15 +156,16 @@ class GitHub
protected function processResponse(Response $response, $expectedCode = 200) protected function processResponse(Response $response, $expectedCode = 200)
{ {
// Validate the response code. // Validate the response code.
if ($response->code != $expectedCode) if ($response->code != $expectedCode) {
{
// Decode the error response and throw an exception. // Decode the error response and throw an exception.
$body = json_decode($response->body); $body = json_decode($response->body);
$error = isset($body->error) ? $body->error $error = isset($body->error) ? $body->error
: (isset($body->message) ? $body->message : 'Unknown Error'); : (isset($body->message) ? $body->message : 'Unknown Error');
throw new Exception\UnexpectedResponse( throw new Exception\UnexpectedResponse(
$response, $error, $response->code $response,
$error,
$response->code
); );
} }
@ -194,20 +187,14 @@ class GitHub
public function getFileContents($user, $repo, $path, $ref = null) public function getFileContents($user, $repo, $path, $ref = null)
{ {
$path = "/repos/$user/$repo/contents/$path"; $path = "/repos/$user/$repo/contents/$path";
$prepared = $this->prepareRequest($path); $prepared = $this->prepareRequest($path);
if ($ref) {
if ($ref)
{
$url = new Uri($prepared['url']); $url = new Uri($prepared['url']);
$url->setVar('ref', $ref); $url->setVar('ref', $ref);
$prepared['url'] = (string) $url; $prepared['url'] = (string) $url;
} }
return $this->processResponse( return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
$this->client->get($prepared['url'], $prepared['headers'])
);
} }
/** /**
@ -225,12 +212,8 @@ class GitHub
{ {
// Build the request path. // Build the request path.
$path = "/repos/$user/$repo/pulls/" . (int) $pullId . '/files?page=' . $page; $path = "/repos/$user/$repo/pulls/" . (int) $pullId . '/files?page=' . $page;
$prepared = $this->prepareRequest($path); $prepared = $this->prepareRequest($path);
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
);
} }
/** /**
@ -248,12 +231,11 @@ class GitHub
public function getOpenIssues($user, $repo, $page = 0, $limit = 0) public function getOpenIssues($user, $repo, $page = 0, $limit = 0)
{ {
$prepared = $this->prepareRequest( $prepared = $this->prepareRequest(
"/repos/$user/$repo/issues", $page, $limit "/repos/$user/$repo/issues",
); $page,
$limit
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
); );
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
} }
/** /**
@ -271,12 +253,11 @@ class GitHub
public function getOpenPulls($user, $repo, $page = 0, $limit = 0) public function getOpenPulls($user, $repo, $page = 0, $limit = 0)
{ {
$prepared = $this->prepareRequest( $prepared = $this->prepareRequest(
"/repos/$user/$repo/pulls", $page, $limit "/repos/$user/$repo/pulls",
); $page,
$limit
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
); );
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
} }
/** /**
@ -309,12 +290,8 @@ class GitHub
{ {
// Build the request path. // Build the request path.
$path = "/repos/$user/$repo/pulls/" . (int) $pullId; $path = "/repos/$user/$repo/pulls/" . (int) $pullId;
$prepared = $this->prepareRequest($path); $prepared = $this->prepareRequest($path);
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
);
} }
/** /**
@ -327,10 +304,7 @@ class GitHub
public function getRateLimit() public function getRateLimit()
{ {
$prepared = $this->prepareRequest('/rate_limit'); $prepared = $this->prepareRequest('/rate_limit');
return $this->processResponse($this->client->get($prepared['url'], $prepared['headers']));
return $this->processResponse(
$this->client->get($prepared['url'], $prepared['headers'])
);
} }
/** /**
@ -346,7 +320,6 @@ class GitHub
public function setOption($key, $value) public function setOption($key, $value)
{ {
$this->options->set($key, $value); $this->options->set($key, $value);
return $this; return $this;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -14,6 +15,10 @@ use Joomla\CMS\Language\Text;
use Joomla\Registry\Registry; use Joomla\Registry\Registry;
use PatchTester\GitHub\GitHub; use PatchTester\GitHub\GitHub;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Helper class for the patch tester component * Helper class for the patch tester component
* *
@ -31,26 +36,18 @@ abstract class Helper
public static function initializeGithub() public static function initializeGithub()
{ {
$params = ComponentHelper::getParams('com_patchtester'); $params = ComponentHelper::getParams('com_patchtester');
$options = new Registry();
$options = new Registry;
// Set a user agent for the request // Set a user agent for the request
$options->set('userAgent', 'PatchTester/3.0'); $options->set('userAgent', 'PatchTester/3.0');
// Set the default timeout to 120 seconds // Set the default timeout to 120 seconds
$options->set('timeout', 120); $options->set('timeout', 120);
// Set the API URL // Set the API URL
$options->set('api.url', 'https://api.github.com'); $options->set('api.url', 'https://api.github.com');
// If an API token is set in the params, use it for authentication // If an API token is set in the params, use it for authentication
if ($params->get('gh_token', '')) if ($params->get('gh_token', '')) {
{
$options->set('headers', ['Authorization' => 'token ' . $params->get('gh_token', '')]); $options->set('headers', ['Authorization' => 'token ' . $params->get('gh_token', '')]);
} } else {
// Display a message about the lowered API limit without credentials // Display a message about the lowered API limit without credentials
else
{
Factory::getApplication()->enqueueMessage(Text::_('COM_PATCHTESTER_NO_CREDENTIALS'), 'notice'); Factory::getApplication()->enqueueMessage(Text::_('COM_PATCHTESTER_NO_CREDENTIALS'), 'notice');
} }
@ -67,23 +64,17 @@ abstract class Helper
public static function initializeCISettings() public static function initializeCISettings()
{ {
$params = ComponentHelper::getParams('com_patchtester'); $params = ComponentHelper::getParams('com_patchtester');
$options = new Registry();
$options = new Registry;
// Set CI server address for the request // Set CI server address for the request
$options->set('server.url', $params->get('ci_server', 'https://ci.joomla.org:444')); $options->set('server.url', $params->get('ci_server', 'https://ci.joomla.org:444'));
// Set name of the zip archive // Set name of the zip archive
$options->set('zip.name', 'build.zip'); $options->set('zip.name', 'build.zip');
$options->set('zip.log.name', 'deleted_files.log'); $options->set('zip.log.name', 'deleted_files.log');
// Set temp archive for extracting and downloading files // Set temp archive for extracting and downloading files
$options->set('folder.temp', Factory::getConfig()->get('tmp_path')); $options->set('folder.temp', Factory::getConfig()->get('tmp_path'));
$options->set('folder.backups', JPATH_COMPONENT . '/backups'); $options->set('folder.backups', JPATH_COMPONENT . '/backups');
// Set full url for addressing the file // Set full url for addressing the file
$options->set('zip.url', $options->get('server.url') . '/artifacts/joomla/joomla-cms/4.0-dev/%s/patchtester/' . $options->get('zip.name')); $options->set('zip.url', $options->get('server.url') . '/artifacts/joomla/joomla-cms/4.0-dev/%s/patchtester/' . $options->get('zip.name'));
return $options; return $options;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -25,7 +26,6 @@ abstract class AbstractModel
* @since 4.0.0 * @since 4.0.0
*/ */
protected $db; protected $db;
/** /**
* The model state. * The model state.
* *
@ -33,7 +33,6 @@ abstract class AbstractModel
* @since 4.0.0 * @since 4.0.0
*/ */
protected $state; protected $state;
/** /**
* Instantiate the model. * Instantiate the model.
* *
@ -44,7 +43,7 @@ abstract class AbstractModel
*/ */
public function __construct(Registry $state = null, \JDatabaseDriver $db = null) public function __construct(Registry $state = null, \JDatabaseDriver $db = null)
{ {
$this->state = $state ?: new Registry; $this->state = $state ?: new Registry();
$this->db = $db ?: Factory::getDbo(); $this->db = $db ?: Factory::getDbo();
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -8,6 +9,10 @@
namespace PatchTester\Model; namespace PatchTester\Model;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Model class for the fetch modal view * Model class for the fetch modal view
* *

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -15,6 +16,10 @@ use Joomla\CMS\MVC\Model\ListModel;
use PatchTester\GitHub\Exception\UnexpectedResponse; use PatchTester\GitHub\Exception\UnexpectedResponse;
use PatchTester\Helper; use PatchTester\Helper;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Model class for the pulls list view * Model class for the pulls list view
* *
@ -29,7 +34,6 @@ class PullsModel extends ListModel
* @since 2.0 * @since 2.0
*/ */
protected $context; protected $context;
/** /**
* Array of fields the list can be sorted on * Array of fields the list can be sorted on
* *
@ -37,7 +41,6 @@ class PullsModel extends ListModel
* @since 2.0 * @since 2.0
*/ */
protected $sortFields = array('pulls.pull_id', 'pulls.title'); protected $sortFields = array('pulls.pull_id', 'pulls.title');
/** /**
* Constructor. * Constructor.
* *
@ -50,9 +53,7 @@ class PullsModel extends ListModel
public function __construct($config = []) public function __construct($config = [])
{ {
$config = []; $config = [];
if (empty($config['filter_fields'])) {
if (empty($config['filter_fields']))
{
$config['filter_fields'] = [ $config['filter_fields'] = [
'applied', 'applied',
'rtc', 'rtc',
@ -76,37 +77,27 @@ class PullsModel extends ListModel
public function getItems() public function getItems()
{ {
$store = $this->getStoreId(); $store = $this->getStoreId();
if (isset($this->cache[$store])) {
if (isset($this->cache[$store]))
{
return $this->cache[$store]; return $this->cache[$store];
} }
$items = $this->getList( $items = $this->getList(
$this->getListQueryCache(), $this->getStart(), $this->getListQueryCache(),
$this->getStart(),
$this->getState()->get('list.limit') $this->getState()->get('list.limit')
); );
$db = $this->getDbo(); $db = $this->getDbo();
$query = $db->getQuery(true) $query = $db->getQuery(true)
->select($db->quoteName(['name', 'color'])) ->select($db->quoteName(['name', 'color']))
->from($db->quoteName('#__patchtester_pulls_labels')); ->from($db->quoteName('#__patchtester_pulls_labels'));
array_walk($items, static function ($item) use ($db, $query) {
array_walk(
$items,
static function ($item) use ($db, $query) {
$query->clear('where'); $query->clear('where');
$query->where( $query->where($db->quoteName('pull_id') . ' = ' . $item->pull_id);
$db->quoteName('pull_id') . ' = ' . $item->pull_id
);
$db->setQuery($query); $db->setQuery($query);
$item->labels = $db->loadObjectList(); $item->labels = $db->loadObjectList();
} });
);
$this->cache[$store] = $items; $this->cache[$store] = $items;
return $this->cache[$store]; return $this->cache[$store];
} }
@ -130,7 +121,6 @@ class PullsModel extends ListModel
$id .= ':' . $this->getState()->get('list.limit'); $id .= ':' . $this->getState()->get('list.limit');
$id .= ':' . $this->getState()->get('list.ordering'); $id .= ':' . $this->getState()->get('list.ordering');
$id .= ':' . $this->getState()->get('list.direction'); $id .= ':' . $this->getState()->get('list.direction');
return md5($this->context . ':' . $id); return md5($this->context . ':' . $id);
} }
@ -165,13 +155,10 @@ class PullsModel extends ListModel
{ {
// Capture the last store id used. // Capture the last store id used.
static $lastStoreId; static $lastStoreId;
// Compute the current store id. // Compute the current store id.
$currentStoreId = $this->getStoreId(); $currentStoreId = $this->getStoreId();
// If the last store id is different from the current, refresh the query. // If the last store id is different from the current, refresh the query.
if ($lastStoreId != $currentStoreId || empty($this->query)) if ($lastStoreId != $currentStoreId || empty($this->query)) {
{
$lastStoreId = $currentStoreId; $lastStoreId = $currentStoreId;
$this->query = $this->getListQuery(); $this->query = $this->getListQuery();
} }
@ -191,137 +178,86 @@ class PullsModel extends ListModel
$db = $this->getDbo(); $db = $this->getDbo();
$query = $db->getQuery(true); $query = $db->getQuery(true);
$labelQuery = $db->getQuery(true); $labelQuery = $db->getQuery(true);
$query->select('pulls.*') $query->select('pulls.*')
->select($db->quoteName('tests.id', 'applied')) ->select($db->quoteName('tests.id', 'applied'))
->from($db->quoteName('#__patchtester_pulls', 'pulls')) ->from($db->quoteName('#__patchtester_pulls', 'pulls'))
->leftJoin( ->leftJoin($db->quoteName('#__patchtester_tests', 'tests')
$db->quoteName('#__patchtester_tests', 'tests')
. ' ON ' . $db->quoteName('tests.pull_id') . ' = ' . ' ON ' . $db->quoteName('tests.pull_id') . ' = '
. $db->quoteName('pulls.pull_id') . $db->quoteName('pulls.pull_id'));
);
$search = $this->getState()->get('filter.search'); $search = $this->getState()->get('filter.search');
if (!empty($search)) if (!empty($search)) {
{ if (stripos($search, 'id:') === 0) {
if (stripos($search, 'id:') === 0) $query->where($db->quoteName('pulls.pull_id') . ' = ' . (int) substr(
{ $search,
$query->where( 3
$db->quoteName('pulls.pull_id') . ' = ' . (int) substr( ));
$search, 3 } elseif (is_numeric($search)) {
) $query->where($db->quoteName('pulls.pull_id') . ' = ' . (int) $search);
); } else {
} $query->where('(' . $db->quoteName('pulls.title') . ' LIKE ' . $db->quote('%' . $db->escape($search, true) . '%') . ')');
elseif (is_numeric($search))
{
$query->where(
$db->quoteName('pulls.pull_id') . ' = ' . (int) $search
);
}
else
{
$query->where(
'(' . $db->quoteName('pulls.title') . ' LIKE ' . $db->quote(
'%' . $db->escape($search, true) . '%'
) . ')'
);
} }
} }
$applied = $this->getState()->get('filter.applied'); $applied = $this->getState()->get('filter.applied');
if (!empty($applied)) {
if (!empty($applied))
{
// Not applied patches have a NULL value, so build our value part of the query based on this // Not applied patches have a NULL value, so build our value part of the query based on this
$value = $applied === 'no' ? ' IS NULL' : ' = 1'; $value = $applied === 'no' ? ' IS NULL' : ' = 1';
$query->where($db->quoteName('applied') . $value); $query->where($db->quoteName('applied') . $value);
} }
$branch = $this->getState()->get('filter.branch'); $branch = $this->getState()->get('filter.branch');
if (!empty($branch)) {
if (!empty($branch)) $query->where($db->quoteName('pulls.branch') . ' IN (' . implode(',', $db->quote($branch)) . ')');
{
$query->where(
$db->quoteName('pulls.branch') . ' IN (' . implode(',', $db->quote($branch)) . ')'
);
} }
$applied = $this->getState()->get('filter.rtc'); $applied = $this->getState()->get('filter.rtc');
if (!empty($applied)) {
if (!empty($applied))
{
// Not applied patches have a NULL value, so build our value part of the query based on this // Not applied patches have a NULL value, so build our value part of the query based on this
$value = $applied === 'no' ? '0' : '1'; $value = $applied === 'no' ? '0' : '1';
$query->where($db->quoteName('pulls.is_rtc') . ' = ' . $value); $query->where($db->quoteName('pulls.is_rtc') . ' = ' . $value);
} }
$npm = $this->getState()->get('filter.npm'); $npm = $this->getState()->get('filter.npm');
if (!empty($npm)) {
if (!empty($npm))
{
// Not applied patches have a NULL value, so build our value part of the query based on this // Not applied patches have a NULL value, so build our value part of the query based on this
$value = $npm === 'no' ? '0' : '1'; $value = $npm === 'no' ? '0' : '1';
$query->where($db->quoteName('pulls.is_npm') . ' = ' . $value); $query->where($db->quoteName('pulls.is_npm') . ' = ' . $value);
} }
$draft = $this->getState()->get('filter.draft'); $draft = $this->getState()->get('filter.draft');
if (!empty($draft)) {
if (!empty($draft))
{
// Not applied patches have a NULL value, so build our value part of the query based on this // Not applied patches have a NULL value, so build our value part of the query based on this
$value = $draft === 'no' ? '0' : '1'; $value = $draft === 'no' ? '0' : '1';
$query->where($db->quoteName('pulls.is_draft') . ' = ' . $value); $query->where($db->quoteName('pulls.is_draft') . ' = ' . $value);
} }
$labels = $this->getState()->get('filter.label'); $labels = $this->getState()->get('filter.label');
if (!empty($labels) && $labels[0] !== '') if (!empty($labels) && $labels[0] !== '') {
{
$labelQuery $labelQuery
->select($db->quoteName('pulls_labels.pull_id')) ->select($db->quoteName('pulls_labels.pull_id'))
->select( ->select('COUNT(' . $db->quoteName('pulls_labels.name') . ') AS '
'COUNT(' . $db->quoteName('pulls_labels.name') . ') AS ' . $db->quoteName('labelCount'))
. $db->quoteName('labelCount') ->from($db->quoteName(
) '#__patchtester_pulls_labels',
->from(
$db->quoteName(
'#__patchtester_pulls_labels', 'pulls_labels'
)
)
->where(
$db->quoteName('pulls_labels.name') . ' IN (' . implode(
',', $db->quote($labels)
) . ')'
)
->group($db->quoteName('pulls_labels.pull_id'));
$query->leftJoin(
'(' . $labelQuery->__toString() . ') AS ' . $db->quoteName(
'pulls_labels' 'pulls_labels'
) ))
->where($db->quoteName('pulls_labels.name') . ' IN (' . implode(
',',
$db->quote($labels)
) . ')')
->group($db->quoteName('pulls_labels.pull_id'));
$query->leftJoin('(' . $labelQuery->__toString() . ') AS ' . $db->quoteName('pulls_labels')
. ' ON ' . $db->quoteName('pulls_labels.pull_id') . ' = ' . ' ON ' . $db->quoteName('pulls_labels.pull_id') . ' = '
. $db->quoteName('pulls.pull_id') . $db->quoteName('pulls.pull_id'))
) ->where($db->quoteName('pulls_labels.labelCount') . ' = ' . count($labels));
->where(
$db->quoteName('pulls_labels.labelCount') . ' = ' . count(
$labels
)
);
} }
$ordering = $this->getState()->get('list.ordering', 'pulls.pull_id'); $ordering = $this->getState()->get('list.ordering', 'pulls.pull_id');
$direction = $this->getState()->get('list.direction', 'DESC'); $direction = $this->getState()->get('list.direction', 'DESC');
if (!empty($ordering)) {
if (!empty($ordering)) $query->order($db->escape($ordering) . ' ' . $db->escape($direction));
{
$query->order(
$db->escape($ordering) . ' ' . $db->escape($direction)
);
} }
return $query; return $query;
@ -351,65 +287,44 @@ class PullsModel extends ListModel
*/ */
public function requestFromGithub($page) public function requestFromGithub($page)
{ {
if ($page === 1) if ($page === 1) {
{
$this->getDbo()->truncateTable('#__patchtester_pulls'); $this->getDbo()->truncateTable('#__patchtester_pulls');
$this->getDbo()->truncateTable('#__patchtester_pulls_labels'); $this->getDbo()->truncateTable('#__patchtester_pulls_labels');
} }
try try {
{
// TODO - Option to configure the batch size // TODO - Option to configure the batch size
$batchSize = 100; $batchSize = 100;
$pullsResponse = Helper::initializeGithub()->getOpenPulls($this->getState()->get('github_user'), $this->getState()->get('github_repo'), $page, $batchSize);
$pullsResponse = Helper::initializeGithub()->getOpenPulls(
$this->getState()->get('github_user'),
$this->getState()->get('github_repo'),
$page,
$batchSize
);
$pulls = json_decode($pullsResponse->body); $pulls = json_decode($pullsResponse->body);
} } catch (UnexpectedResponse $exception) {
catch (UnexpectedResponse $exception) throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_GITHUB_FETCH', $exception->getMessage()), $exception->getCode(), $exception);
{
throw new \RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_GITHUB_FETCH',
$exception->getMessage()
),
$exception->getCode(),
$exception
);
} }
// If this is page 1, let's check to see if we need to paginate // If this is page 1, let's check to see if we need to paginate
if ($page === 1) if ($page === 1) {
{
// Default this to being a single page of results // Default this to being a single page of results
$lastPage = 1; $lastPage = 1;
if (isset($pullsResponse->headers['link'])) {
if (isset($pullsResponse->headers['link']))
{
$linkHeader = $pullsResponse->headers['link']; $linkHeader = $pullsResponse->headers['link'];
// The `joomla/http` 2.0 package uses PSR-7 Responses which has a different format for headers, check for this // The `joomla/http` 2.0 package uses PSR-7 Responses which has a different format for headers, check for this
if (is_array($linkHeader)) if (is_array($linkHeader)) {
{
$linkHeader = $linkHeader[0]; $linkHeader = $linkHeader[0];
} }
preg_match( preg_match(
'/(\?page=[0-9]{1,3}&per_page=' . $batchSize '/(\?page=[0-9]{1,3}&per_page=' . $batchSize
. '+>; rel=\"last\")/', $linkHeader, $matches . '+>; rel=\"last\")/',
$linkHeader,
$matches
); );
if ($matches && isset($matches[0])) if ($matches && isset($matches[0])) {
{
$pageSegment = str_replace( $pageSegment = str_replace(
'&per_page=' . $batchSize, '', $matches[0] '&per_page=' . $batchSize,
'',
$matches[0]
); );
preg_match('/\d+/', $pageSegment, $pages); preg_match('/\d+/', $pageSegment, $pages);
$lastPage = (int) $pages[0]; $lastPage = (int) $pages[0];
} }
@ -417,111 +332,71 @@ class PullsModel extends ListModel
} }
// If there are no pulls to insert then bail, assume we're finished // If there are no pulls to insert then bail, assume we're finished
if (count($pulls) === 0) if (count($pulls) === 0) {
{
return ['complete' => true]; return ['complete' => true];
} }
$data = []; $data = [];
$labels = []; $labels = [];
foreach ($pulls as $pull) {
foreach ($pulls as $pull)
{
// Check if this PR is RTC and has a `PR-` branch label // Check if this PR is RTC and has a `PR-` branch label
$isRTC = false; $isRTC = false;
$isNPM = false; $isNPM = false;
$branch = $pull->base->ref; $branch = $pull->base->ref;
foreach ($pull->labels as $label) {
foreach ($pull->labels as $label) if (strtolower($label->name) === 'rtc') {
{
if (strtolower($label->name) === 'rtc')
{
$isRTC = true; $isRTC = true;
} } elseif (
elseif (in_array( in_array(strtolower($label->name), ['npm resource changed', 'composer dependency changed'], true)
strtolower($label->name), ) {
['npm resource changed', 'composer dependency changed'],
true
))
{
$isNPM = true; $isNPM = true;
} }
$labels[] = implode( $labels[] = implode(',', [
',',
[
(int) $pull->number, (int) $pull->number,
$this->getDbo()->quote($label->name), $this->getDbo()->quote($label->name),
$this->getDbo()->quote($label->color), $this->getDbo()->quote($label->color),
] ]);
);
} }
// Build the data object to store in the database // Build the data object to store in the database
$pullData = [ $pullData = [
(int) $pull->number, (int) $pull->number,
$this->getDbo()->quote( $this->getDbo()->quote(HTMLHelper::_('string.truncate', $pull->title, 150)),
HTMLHelper::_('string.truncate', $pull->title, 150) $this->getDbo()->quote(HTMLHelper::_('string.truncate', $pull->body, 100)),
),
$this->getDbo()->quote(
HTMLHelper::_('string.truncate', $pull->body, 100)
),
$this->getDbo()->quote($pull->html_url), $this->getDbo()->quote($pull->html_url),
(int) $isRTC, (int) $isRTC,
(int) $isNPM, (int) $isNPM,
$this->getDbo()->quote($branch), $this->getDbo()->quote($branch),
($pull->draft ? 1 : 0) ($pull->draft ? 1 : 0)
]; ];
$data[] = implode(',', $pullData); $data[] = implode(',', $pullData);
} }
// If there are no pulls to insert then bail, assume we're finished // If there are no pulls to insert then bail, assume we're finished
if (count($data) === 0) if (count($data) === 0) {
{
return array('complete' => true); return array('complete' => true);
} }
try try {
{ $this->getDbo()->setQuery($this->getDbo()->getQuery(true)
$this->getDbo()->setQuery(
$this->getDbo()->getQuery(true)
->insert('#__patchtester_pulls') ->insert('#__patchtester_pulls')
->columns( ->columns(['pull_id', 'title', 'description', 'pull_url',
['pull_id', 'title', 'description', 'pull_url', 'is_rtc', 'is_npm', 'branch', 'is_draft'])
'is_rtc', 'is_npm', 'branch', 'is_draft'] ->values($data));
)
->values($data)
);
$this->getDbo()->execute(); $this->getDbo()->execute();
} } catch (\RuntimeException $exception) {
catch (\RuntimeException $exception) throw new \RuntimeException(Text::sprintf('COM_PATCHTESTER_ERROR_INSERT_DATABASE', $exception->getMessage()), $exception->getCode(), $exception);
{
throw new \RuntimeException(
Text::sprintf(
'COM_PATCHTESTER_ERROR_INSERT_DATABASE',
$exception->getMessage()
),
$exception->getCode(),
$exception
);
} }
if ($labels) if ($labels) {
{ try {
try $this->getDbo()->setQuery($this->getDbo()->getQuery(true)
{
$this->getDbo()->setQuery(
$this->getDbo()->getQuery(true)
->insert('#__patchtester_pulls_labels') ->insert('#__patchtester_pulls_labels')
->columns(['pull_id', 'name', 'color']) ->columns(['pull_id', 'name', 'color'])
->values($labels) ->values($labels));
);
$this->getDbo()->execute(); $this->getDbo()->execute();
} } catch (\RuntimeException $exception) {
catch (\RuntimeException $exception)
{
throw new \RuntimeException( throw new \RuntimeException(
Text::sprintf( Text::sprintf(
'COM_PATCHTESTER_ERROR_INSERT_DATABASE', 'COM_PATCHTESTER_ERROR_INSERT_DATABASE',

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -8,6 +9,10 @@
namespace PatchTester\Model; namespace PatchTester\Model;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Methods supporting applied pull requests. * Methods supporting applied pull requests.
* *
@ -25,14 +30,10 @@ class TestsModel extends AbstractModel
public function getAppliedPatches(): array public function getAppliedPatches(): array
{ {
$db = $this->getDb(); $db = $this->getDb();
$db->setQuery($db->getQuery(true)
$db->setQuery(
$db->getQuery(true)
->select('*') ->select('*')
->from($db->quoteName('#__patchtester_tests')) ->from($db->quoteName('#__patchtester_tests'))
->where($db->quoteName('applied') . ' = 1') ->where($db->quoteName('applied') . ' = 1'));
);
return $db->loadObjectList('pull_id'); return $db->loadObjectList('pull_id');
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -52,14 +53,12 @@ abstract class TrackerHelper
public static function getTrackerAlias($githubUser, $githubRepo) public static function getTrackerAlias($githubUser, $githubRepo)
{ {
// If the repo isn't even listed, no point in going further // If the repo isn't even listed, no point in going further
if (!array_key_exists($githubRepo, self::$projects)) if (!array_key_exists($githubRepo, self::$projects)) {
{
return false; return false;
} }
// Now the GitHub user must match the project (we don't support forks, sorry!) // Now the GitHub user must match the project (we don't support forks, sorry!)
if (self::$projects[$githubRepo]['githubUser'] !== $githubUser) if (self::$projects[$githubRepo]['githubUser'] !== $githubUser) {
{
return false; return false;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -12,6 +13,10 @@ use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
use PatchTester\Model\AbstractModel; use PatchTester\Model\AbstractModel;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Base HTML view for the patch testing component * Base HTML view for the patch testing component
* *
@ -26,7 +31,6 @@ abstract class AbstractHtmlView extends AbstractView
* @since 4.0.0 * @since 4.0.0
*/ */
protected $layout = 'default'; protected $layout = 'default';
/** /**
* The paths queue. * The paths queue.
* *
@ -34,7 +38,6 @@ abstract class AbstractHtmlView extends AbstractView
* @since 4.0.0 * @since 4.0.0
*/ */
protected $paths; protected $paths;
/** /**
* Method to instantiate the view. * Method to instantiate the view.
* *
@ -46,9 +49,8 @@ abstract class AbstractHtmlView extends AbstractView
public function __construct($model, \SplPriorityQueue $paths = null) public function __construct($model, \SplPriorityQueue $paths = null)
{ {
parent::__construct($model); parent::__construct($model);
// Setup dependencies. // Setup dependencies.
$this->paths = $paths ?: new \SplPriorityQueue; $this->paths = $paths ?: new \SplPriorityQueue();
} }
/** /**
@ -91,10 +93,8 @@ abstract class AbstractHtmlView extends AbstractView
{ {
// Get the layout file name. // Get the layout file name.
$file = Path::clean($layout . '.php'); $file = Path::clean($layout . '.php');
// Find the layout file path. // Find the layout file path.
$path = Path::find(clone $this->paths, $file); $path = Path::find(clone $this->paths, $file);
return $path; return $path;
} }
@ -124,35 +124,27 @@ abstract class AbstractHtmlView extends AbstractView
{ {
// Get the path to the file // Get the path to the file
$file = $this->getLayout(); $file = $this->getLayout();
if (isset($tpl)) {
if (isset($tpl))
{
$file .= '_' . $tpl; $file .= '_' . $tpl;
} }
$path = $this->getPath($file); $path = $this->getPath($file);
if (!$path) {
if (!$path)
{
throw new \RuntimeException(Text::sprintf('JLIB_APPLICATION_ERROR_LAYOUTFILE_NOT_FOUND', $file), 500); throw new \RuntimeException(Text::sprintf('JLIB_APPLICATION_ERROR_LAYOUTFILE_NOT_FOUND', $file), 500);
} }
// Unset so as not to introduce into template scope // Unset so as not to introduce into template scope
unset($tpl); unset($tpl);
unset($file); unset($file);
// Never allow a 'this' property // Never allow a 'this' property
if (isset($this->this)) if (isset($this->this)) {
{
unset($this->this); unset($this->this);
} }
// Start an output buffer. // Start an output buffer.
ob_start(); ob_start();
// Load the template. // Load the template.
include $path; include $path;
// Get the layout contents. // Get the layout contents.
return ob_get_clean(); return ob_get_clean();
} }
@ -169,22 +161,17 @@ abstract class AbstractHtmlView extends AbstractView
{ {
// Get the layout path. // Get the layout path.
$path = $this->getPath($this->getLayout()); $path = $this->getPath($this->getLayout());
// Check if the layout path was found. // Check if the layout path was found.
if (!$path) if (!$path) {
{
throw new \RuntimeException('Layout Path Not Found'); throw new \RuntimeException('Layout Path Not Found');
} }
// Start an output buffer. // Start an output buffer.
ob_start(); ob_start();
// Load the layout. // Load the layout.
include $path; include $path;
// Get the layout contents. // Get the layout contents.
$output = ob_get_clean(); $output = ob_get_clean();
return $output; return $output;
} }
@ -200,7 +187,6 @@ abstract class AbstractHtmlView extends AbstractView
public function setLayout($layout) public function setLayout($layout)
{ {
$this->layout = $layout; $this->layout = $layout;
return $this; return $this;
} }
@ -216,7 +202,6 @@ abstract class AbstractHtmlView extends AbstractView
public function setPaths(\SplPriorityQueue $paths) public function setPaths(\SplPriorityQueue $paths)
{ {
$this->paths = $paths; $this->paths = $paths;
return $this; return $this;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -24,7 +25,6 @@ abstract class AbstractView
* @since 4.0.0 * @since 4.0.0
*/ */
protected $model; protected $model;
/** /**
* Method to instantiate the view. * Method to instantiate the view.
* *

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -8,6 +9,10 @@
namespace PatchTester\View; namespace PatchTester\View;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Default HTML view class. * Default HTML view class.
* *

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -10,6 +11,10 @@ use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** @var \PatchTester\View\DefaultHtmlView $this */ /** @var \PatchTester\View\DefaultHtmlView $this */
HTMLHelper::_('jquery.framework'); HTMLHelper::_('jquery.framework');

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -18,6 +19,10 @@ use Joomla\Registry\Registry;
use PatchTester\TrackerHelper; use PatchTester\TrackerHelper;
use PatchTester\View\DefaultHtmlView; use PatchTester\View\DefaultHtmlView;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* View class for a list of pull requests. * View class for a list of pull requests.
* *
@ -34,7 +39,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 2.0 * @since 2.0
*/ */
protected $envErrors = []; protected $envErrors = [];
/** /**
* Array of open pull requests * Array of open pull requests
* *
@ -42,7 +46,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 2.0 * @since 2.0
*/ */
protected $items; protected $items;
/** /**
* Pagination object * Pagination object
* *
@ -50,7 +53,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 2.0 * @since 2.0
*/ */
protected $pagination; protected $pagination;
/** /**
* Form object for search filters * Form object for search filters
* *
@ -58,7 +60,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 4.1.0 * @since 4.1.0
*/ */
public $filterForm; public $filterForm;
/** /**
* The active search filters * The active search filters
* *
@ -66,7 +67,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 4.1.0 * @since 4.1.0
*/ */
public $activeFilters; public $activeFilters;
/** /**
* The model state * The model state
* *
@ -74,7 +74,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 2.0.0 * @since 2.0.0
*/ */
protected $state; protected $state;
/** /**
* The issue tracker project alias * The issue tracker project alias
* *
@ -82,7 +81,6 @@ class PullsHtmlView extends DefaultHtmlView
* @since 2.0 * @since 2.0
*/ */
protected $trackerAlias; protected $trackerAlias;
/** /**
* Method to render the view. * Method to render the view.
* *
@ -93,39 +91,30 @@ class PullsHtmlView extends DefaultHtmlView
*/ */
public function render(): string public function render(): string
{ {
if (!extension_loaded('openssl')) if (!extension_loaded('openssl')) {
{
$this->envErrors[] = Text::_('COM_PATCHTESTER_REQUIREMENT_OPENSSL'); $this->envErrors[] = Text::_('COM_PATCHTESTER_REQUIREMENT_OPENSSL');
} }
if (!in_array('https', stream_get_wrappers(), true)) if (!in_array('https', stream_get_wrappers(), true)) {
{
$this->envErrors[] = Text::_('COM_PATCHTESTER_REQUIREMENT_HTTPS'); $this->envErrors[] = Text::_('COM_PATCHTESTER_REQUIREMENT_HTTPS');
} }
if (!count($this->envErrors)) if (!count($this->envErrors)) {
{
$this->state = $this->model->getState(); $this->state = $this->model->getState();
$this->items = $this->model->getItems(); $this->items = $this->model->getItems();
$this->pagination = $this->model->getPagination(); $this->pagination = $this->model->getPagination();
$this->filterForm = $this->model->getFilterForm(); $this->filterForm = $this->model->getFilterForm();
$this->activeFilters = $this->model->getActiveFilters(); $this->activeFilters = $this->model->getActiveFilters();
$this->trackerAlias = TrackerHelper::getTrackerAlias( $this->trackerAlias = TrackerHelper::getTrackerAlias($this->state->get('github_user'), $this->state->get('github_repo'));
$this->state->get('github_user'),
$this->state->get('github_repo')
);
} }
// Change the layout if there are environment errors // Change the layout if there are environment errors
if (count($this->envErrors)) if (count($this->envErrors)) {
{
$this->setLayout('errors'); $this->setLayout('errors');
} }
$this->addToolbar(); $this->addToolbar();
Text::script('COM_PATCHTESTER_CONFIRM_RESET'); Text::script('COM_PATCHTESTER_CONFIRM_RESET');
return parent::render(); return parent::render();
} }
@ -139,24 +128,9 @@ class PullsHtmlView extends DefaultHtmlView
protected function addToolbar(): void protected function addToolbar(): void
{ {
ToolbarHelper::title(Text::_('COM_PATCHTESTER'), 'patchtester fas fa-save'); ToolbarHelper::title(Text::_('COM_PATCHTESTER'), 'patchtester fas fa-save');
if (!count($this->envErrors)) {
if (!count($this->envErrors))
{
$toolbar = Toolbar::getInstance('toolbar'); $toolbar = Toolbar::getInstance('toolbar');
$toolbar->appendButton('Popup', 'sync', 'COM_PATCHTESTER_TOOLBAR_FETCH_DATA', 'index.php?option=com_patchtester&view=fetch&tmpl=component', 500, 210, 0, 0, 'window.parent.location.reload()', Text::_('COM_PATCHTESTER_HEADING_FETCH_DATA'));
$toolbar->appendButton(
'Popup',
'sync',
'COM_PATCHTESTER_TOOLBAR_FETCH_DATA',
'index.php?option=com_patchtester&view=fetch&tmpl=component',
500,
210,
0,
0,
'window.parent.location.reload()',
Text::_('COM_PATCHTESTER_HEADING_FETCH_DATA')
);
// Add a reset button. // Add a reset button.
$toolbar->appendButton('Standard', 'expired', 'COM_PATCHTESTER_TOOLBAR_RESET', 'reset', false); $toolbar->appendButton('Standard', 'expired', 'COM_PATCHTESTER_TOOLBAR_RESET', 'reset', false);
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -11,6 +12,10 @@ use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\LayoutHelper; use Joomla\CMS\Layout\LayoutHelper;
use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Route;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** @var \PatchTester\View\Pulls\PullsHtmlView $this */ /** @var \PatchTester\View\Pulls\PullsHtmlView $this */
HTMLHelper::_('stylesheet', 'com_patchtester/octicons.css', ['version' => '3.5.0', 'relative' => true]); HTMLHelper::_('stylesheet', 'com_patchtester/octicons.css', ['version' => '3.5.0', 'relative' => true]);
@ -22,12 +27,15 @@ HTMLHelper::_('script', 'com_patchtester/patchtester.js', ['version' => 'auto',
<div id="j-main-container" class="j-main-container"> <div id="j-main-container" class="j-main-container">
<?php echo LayoutHelper::render('joomla.searchtools.default', ['view' => $this]); ?> <?php echo LayoutHelper::render('joomla.searchtools.default', ['view' => $this]); ?>
<div id="j-main-container" class="j-main-container"> <div id="j-main-container" class="j-main-container">
<?php if (empty($this->items)) : ?> <?php if (empty($this->items)) :
?>
<div class="alert alert-info"> <div class="alert alert-info">
<span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span> <span class="fa fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span>
<?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?> <?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
</div> </div>
<?php else : ?> <?php
else :
?>
<table class="table"> <table class="table">
<caption id="captionTable" class="sr-only"> <caption id="captionTable" class="sr-only">
<?php echo Text::_('COM_PATCHTESTER_PULLS_TABLE_CAPTION'); ?>, <?php echo Text::_('JGLOBAL_SORTED_BY'); ?> <?php echo Text::_('COM_PATCHTESTER_PULLS_TABLE_CAPTION'); ?>, <?php echo Text::_('JGLOBAL_SORTED_BY'); ?>
@ -58,7 +66,8 @@ HTMLHelper::_('script', 'com_patchtester/patchtester.js', ['version' => 'auto',
<?php echo $this->loadTemplate('items'); ?> <?php echo $this->loadTemplate('items'); ?>
</tbody> </tbody>
</table> </table>
<?php endif; ?> <?php
endif; ?>
<?php echo $this->pagination->getListFooter(); ?> <?php echo $this->pagination->getListFooter(); ?>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -9,11 +10,14 @@
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
use PatchTester\View\Pulls\PullsHtmlView; use PatchTester\View\Pulls\PullsHtmlView;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** @var PullsHtmlView $this */ /** @var PullsHtmlView $this */
foreach ($this->items as $i => $item) : foreach ($this->items as $i => $item) :
$status = ''; $status = '';
if ($item->applied) : if ($item->applied) :
$status = ' class="table-active"'; $status = ' class="table-active"';
endif; endif;
@ -21,11 +25,13 @@ foreach ($this->items as $i => $item) :
<tr<?php echo $status; ?>> <tr<?php echo $status; ?>>
<th scope="row" class="text-center"> <th scope="row" class="text-center">
<?php echo $item->pull_id; ?> <?php echo $item->pull_id; ?>
<?php if ($item->is_draft) : ?> <?php if ($item->is_draft) :
?>
<span class="badge" style="color: #FFFFFF; background-color: #6e7681"> <span class="badge" style="color: #FFFFFF; background-color: #6e7681">
<?php echo Text::_('COM_PATCHTESTER_IS_DRAFT'); ?> <?php echo Text::_('COM_PATCHTESTER_IS_DRAFT'); ?>
</span> </span>
<?php endif; ?> <?php
endif; ?>
</th> </th>
<td> <td>
<span><?php echo $this->escape($item->title); ?></span> <span><?php echo $this->escape($item->title); ?></span>
@ -38,7 +44,8 @@ foreach ($this->items as $i => $item) :
<?php echo Text::_('COM_PATCHTESTER_VIEW_ON_GITHUB'); ?> <?php echo Text::_('COM_PATCHTESTER_VIEW_ON_GITHUB'); ?>
</a> </a>
</div> </div>
<?php if ($this->trackerAlias) : ?> <?php if ($this->trackerAlias) :
?>
<div class="col-md-auto"> <div class="col-md-auto">
<a class="badge bg-info" <a class="badge bg-info"
href="https://issues.joomla.org/tracker/<?php echo $this->trackerAlias; ?>/<?php echo $item->pull_id; ?>" href="https://issues.joomla.org/tracker/<?php echo $this->trackerAlias; ?>/<?php echo $item->pull_id; ?>"
@ -46,20 +53,24 @@ foreach ($this->items as $i => $item) :
<?php echo Text::_('COM_PATCHTESTER_VIEW_ON_JOOMLA_ISSUE_TRACKER'); ?> <?php echo Text::_('COM_PATCHTESTER_VIEW_ON_JOOMLA_ISSUE_TRACKER'); ?>
</a> </a>
</div> </div>
<?php endif; ?> <?php
<?php if ($item->applied) : ?> endif; ?>
<?php if ($item->applied) :
?>
<div class="col-md-auto"> <div class="col-md-auto">
<span class="badge bg-info"><?php echo Text::sprintf('COM_PATCHTESTER_APPLIED_COMMIT_SHA', substr($item->sha, 0, 10)); ?></span> <span class="badge bg-info"><?php echo Text::sprintf('COM_PATCHTESTER_APPLIED_COMMIT_SHA', substr($item->sha, 0, 10)); ?></span>
</div> </div>
<?php endif; ?> <?php
endif; ?>
</div> </div>
<?php if (count($item->labels) > 0) : ?> <?php if (count($item->labels) > 0) :
?>
<div class="row"> <div class="row">
<div class="col-md-auto"> <div class="col-md-auto">
<?php foreach ($item->labels as $label): ?> <?php foreach ($item->labels as $label) :
?>
<?php <?php
switch (strtolower($label->name)) switch (strtolower($label->name)) {
{
case 'a11y': case 'a11y':
case 'conflicting files': case 'conflicting files':
case 'documentation required': case 'documentation required':
@ -80,43 +91,60 @@ foreach ($this->items as $i => $item) :
case 'test instructions missing': case 'test instructions missing':
case 'updates requested': case 'updates requested':
$textColor = '000000'; $textColor = '000000';
break; break;
default: default:
$textColor = 'FFFFFF'; $textColor = 'FFFFFF';
break; break;
} }
?> ?>
<span class="badge" style="color: #<?php echo $textColor; ?>; background-color: #<?php echo $label->color; ?>"><?php echo $label->name; ?></span> <span class="badge" style="color: #<?php echo $textColor; ?>; background-color: #<?php echo $label->color; ?>"><?php echo $label->name; ?></span>
<?php endforeach; ?> <?php
endforeach; ?>
</div> </div>
</div> </div>
<?php endif; ?> <?php
endif; ?>
</td> </td>
<td class="d-none d-md-table-cell text-center"> <td class="d-none d-md-table-cell text-center">
<?php echo $this->escape($item->branch); ?> <?php echo $this->escape($item->branch); ?>
</td> </td>
<td class="d-none d-md-table-cell text-center"> <td class="d-none d-md-table-cell text-center">
<?php if ($item->is_rtc) : ?> <?php if ($item->is_rtc) :
?>
<span class="badge bg-success"><?php echo Text::_('JYES'); ?></span> <span class="badge bg-success"><?php echo Text::_('JYES'); ?></span>
<?php else : ?> <?php
else :
?>
<span class="badge bg-secondary"><?php echo Text::_('JNO'); ?></span> <span class="badge bg-secondary"><?php echo Text::_('JNO'); ?></span>
<?php endif; ?> <?php
endif; ?>
</td> </td>
<td class="text-center"> <td class="text-center">
<?php if ($item->applied) : ?> <?php if ($item->applied) :
?>
<span class="badge bg-success"><?php echo Text::_('COM_PATCHTESTER_APPLIED'); ?></span> <span class="badge bg-success"><?php echo Text::_('COM_PATCHTESTER_APPLIED'); ?></span>
<?php else : ?> <?php
else :
?>
<span class="badge bg-secondary"><?php echo Text::_('COM_PATCHTESTER_NOT_APPLIED'); ?></span> <span class="badge bg-secondary"><?php echo Text::_('COM_PATCHTESTER_NOT_APPLIED'); ?></span>
<?php endif; ?> <?php
endif; ?>
</td> </td>
<td class="text-center"> <td class="text-center">
<?php if ($item->applied) : ?> <?php if ($item->applied) :
?>
<button type="button" class="btn btn-sm btn-success submitPatch" <button type="button" class="btn btn-sm btn-success submitPatch"
data-task="revert" data-id="<?php echo (int) $item->applied; ?>"><?php echo Text::_('COM_PATCHTESTER_REVERT_PATCH'); ?></button> data-task="revert" data-id="<?php echo (int) $item->applied; ?>"><?php echo Text::_('COM_PATCHTESTER_REVERT_PATCH'); ?></button>
<?php else : ?> <?php
else :
?>
<button type="button" class="btn btn-sm btn-primary submitPatch" <button type="button" class="btn btn-sm btn-primary submitPatch"
data-task="apply" data-id="<?php echo (int) $item->pull_id; ?>"><?php echo Text::_('COM_PATCHTESTER_APPLY_PATCH'); ?></button> data-task="apply" data-id="<?php echo (int) $item->pull_id; ?>"><?php echo Text::_('COM_PATCHTESTER_APPLY_PATCH'); ?></button>
<?php endif; ?> <?php
endif; ?>
</td> </td>
</tr> </tr>
<?php endforeach; <?php
endforeach;

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -8,12 +9,18 @@
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** @var \PatchTester\View\Pulls\PullsHtmlView $this */ /** @var \PatchTester\View\Pulls\PullsHtmlView $this */
?> ?>
<h3><?php echo Text::_('COM_PATCHTESTER_REQUIREMENTS_HEADING'); ?></h3> <h3><?php echo Text::_('COM_PATCHTESTER_REQUIREMENTS_HEADING'); ?></h3>
<p><?php echo Text::_('COM_PATCHTESTER_REQUIREMENTS_NOT_MET'); ?></p> <p><?php echo Text::_('COM_PATCHTESTER_REQUIREMENTS_NOT_MET'); ?></p>
<ul> <ul>
<?php foreach ($this->envErrors as $error) : ?> <?php foreach ($this->envErrors as $error) :
?>
<li><?php echo $error; ?></li> <li><?php echo $error; ?></li>
<?php endforeach; ?> <?php
endforeach; ?>
</ul> </ul>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -6,35 +7,26 @@
* @license GNU General Public License version 2 or later * @license GNU General Public License version 2 or later
*/ */
defined('_JEXEC') or die; \defined('_JEXEC') or die;
use Joomla\CMS\Factory; use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
if (!Factory::getUser()->authorise('core.manage', 'com_patchtester')) {
if (!Factory::getUser()->authorise('core.manage', 'com_patchtester'))
{
throw new RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403); throw new RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
} }
// Application reference // Application reference
$app = Factory::getApplication(); $app = Factory::getApplication();
// Import our Composer autoloader to load the component classes // Import our Composer autoloader to load the component classes
require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/vendor/autoload.php';
// Build the controller class name based on task // Build the controller class name based on task
$task = $app->input->getCmd('task', 'display'); $task = $app->input->getCmd('task', 'display');
// If $task is an empty string, apply our default since JInput might not // If $task is an empty string, apply our default since JInput might not
if ($task === '') if ($task === '') {
{
$task = 'display'; $task = 'display';
} }
$class = '\\PatchTester\\Controller\\' . ucfirst(strtolower($task)) . 'Controller'; $class = '\\PatchTester\\Controller\\' . ucfirst(strtolower($task)) . 'Controller';
if (!class_exists($class)) {
if (!class_exists($class))
{
throw new InvalidArgumentException(Text::sprintf('JLIB_APPLICATION_ERROR_INVALID_CONTROLLER_CLASS', $class), 404); throw new InvalidArgumentException(Text::sprintf('JLIB_APPLICATION_ERROR_INVALID_CONTROLLER_CLASS', $class), 404);
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Patch testing component for the Joomla! CMS * Patch testing component for the Joomla! CMS
* *
@ -12,6 +13,10 @@ use Joomla\CMS\Installer\Adapter\ComponentAdapter;
use Joomla\CMS\Installer\InstallerScript; use Joomla\CMS\Installer\InstallerScript;
use Joomla\CMS\Language\Text; use Joomla\CMS\Language\Text;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/** /**
* Installation class to perform additional changes during install/uninstall/update * Installation class to perform additional changes during install/uninstall/update
* *
@ -19,7 +24,6 @@ use Joomla\CMS\Language\Text;
*/ */
class Com_PatchtesterInstallerScript extends InstallerScript class Com_PatchtesterInstallerScript extends InstallerScript
{ {
/** /**
* Extension script constructor. * Extension script constructor.
* *
@ -29,16 +33,13 @@ class Com_PatchtesterInstallerScript extends InstallerScript
{ {
$this->minimumJoomla = '4.0'; $this->minimumJoomla = '4.0';
$this->minimumPhp = JOOMLA_MINIMUM_PHP; $this->minimumPhp = JOOMLA_MINIMUM_PHP;
$this->deleteFiles = array( $this->deleteFiles = array(
'/administrator/components/com_patchtester/PatchTester/View/Pulls/tmpl/default_errors.php', '/administrator/components/com_patchtester/PatchTester/View/Pulls/tmpl/default_errors.php',
); );
$this->deleteFolders = array( $this->deleteFolders = array(
'/administrator/components/com_patchtester/PatchTester/Table', '/administrator/components/com_patchtester/PatchTester/Table',
'/components/com_patchtester', '/components/com_patchtester',
); );
Factory::getApplication() Factory::getApplication()
->getLanguage() ->getLanguage()
->load('com_patchtester.sys', JPATH_ADMINISTRATOR, null, true); ->load('com_patchtester.sys', JPATH_ADMINISTRATOR, null, true);

View File

@ -1,5 +1,6 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Script used to generate hashes for release packages * Script used to generate hashes for release packages
* *
@ -14,10 +15,8 @@ $packageDir = dirname(__DIR__) . '/packages';
$hashes = array(); $hashes = array();
/** @var DirectoryIterator $file */ /** @var DirectoryIterator $file */
foreach (new DirectoryIterator($packageDir) as $file) foreach (new DirectoryIterator($packageDir) as $file) {
{ if ($file->isDir() || $file->isDot()) {
if ($file->isDir() || $file->isDot())
{
continue; continue;
} }

View File

@ -1,5 +1,6 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Script used to prepare a patchtester release * Script used to prepare a patchtester release
* *
@ -39,8 +40,7 @@ $updateServerFile = '/manifest.xml';
// Check arguments (exit if incorrect cli arguments). // Check arguments (exit if incorrect cli arguments).
$opts = getopt('v:', array('exclude-manifest')); $opts = getopt('v:', array('exclude-manifest'));
if (empty($opts['v'])) if (empty($opts['v'])) {
{
usage($argv[0]); usage($argv[0]);
die(); die();
} }
@ -48,20 +48,17 @@ if (empty($opts['v']))
// Check version string (exit if not correct). // Check version string (exit if not correct).
$versionParts = explode('-', $opts['v']); $versionParts = explode('-', $opts['v']);
if (!preg_match('#^[0-9]+\.[0-9]+\.[0-9]+$#', $versionParts[0])) if (!preg_match('#^[0-9]+\.[0-9]+\.[0-9]+$#', $versionParts[0])) {
{
usage($argv[0]); usage($argv[0]);
die(); die();
} }
if (isset($versionParts[1]) && !preg_match('#(dev|alpha|beta|rc)[0-9]*#', $versionParts[1])) if (isset($versionParts[1]) && !preg_match('#(dev|alpha|beta|rc)[0-9]*#', $versionParts[1])) {
{
usage($argv[0]); usage($argv[0]);
die(); die();
} }
if (isset($versionParts[2]) && $versionParts[2] !== 'dev') if (isset($versionParts[2]) && $versionParts[2] !== 'dev') {
{
usage($argv[0]); usage($argv[0]);
die(); die();
} }
@ -96,8 +93,7 @@ echo PHP_EOL;
$rootPath = dirname(dirname(__DIR__)); $rootPath = dirname(dirname(__DIR__));
// Updates the version and creation date in the component manifest file. // Updates the version and creation date in the component manifest file.
if (file_exists($rootPath . $manifestFile)) if (file_exists($rootPath . $manifestFile)) {
{
$fileContents = file_get_contents($rootPath . $manifestFile); $fileContents = file_get_contents($rootPath . $manifestFile);
$fileContents = preg_replace('#<version>[^<]*</version>#', '<version>' . $version['main'] . '.' . $version['dev_devel'] . '</version>', $fileContents); $fileContents = preg_replace('#<version>[^<]*</version>#', '<version>' . $version['main'] . '.' . $version['dev_devel'] . '</version>', $fileContents);
$fileContents = preg_replace('#<creationDate>[^<]*</creationDate>#', '<creationDate>' . $version['credate'] . '</creationDate>', $fileContents); $fileContents = preg_replace('#<creationDate>[^<]*</creationDate>#', '<creationDate>' . $version['credate'] . '</creationDate>', $fileContents);
@ -108,10 +104,8 @@ if (file_exists($rootPath . $manifestFile))
system('cd ' . $rootPath . ' && find administrator -name "*.php" -type f -exec sed -i "s/__DEPLOY_VERSION__/' . $version['release'] . '/g" "{}" \;'); system('cd ' . $rootPath . ' && find administrator -name "*.php" -type f -exec sed -i "s/__DEPLOY_VERSION__/' . $version['release'] . '/g" "{}" \;');
// If not instructed to exclude it, update the update server's manifest // If not instructed to exclude it, update the update server's manifest
if (!isset($opts['exclude-manifest'])) if (!isset($opts['exclude-manifest'])) {
{ if (file_exists($rootPath . $updateServerFile)) {
if (file_exists($rootPath . $updateServerFile))
{
$fileContents = file_get_contents($rootPath . $updateServerFile); $fileContents = file_get_contents($rootPath . $updateServerFile);
$fileContents = preg_replace('#<infourl title="Patch Tester Component">[^<]*</infourl>#', '<infourl title="Patch Tester Component">https://github.com/joomla-extensions/patchtester/releases/tag/' . $version['release'] . '</infourl>', $fileContents); $fileContents = preg_replace('#<infourl title="Patch Tester Component">[^<]*</infourl>#', '<infourl title="Patch Tester Component">https://github.com/joomla-extensions/patchtester/releases/tag/' . $version['release'] . '</infourl>', $fileContents);
$fileContents = preg_replace('#<downloadurl type="full" format="zip">[^<]*</downloadurl>#', '<downloadurl type="full" format="zip">https://github.com/joomla-extensions/patchtester/releases/download/' . $version['release'] . '/com_patchtester_' . $version['release'] . '.zip</downloadurl>', $fileContents); $fileContents = preg_replace('#<downloadurl type="full" format="zip">[^<]*</downloadurl>#', '<downloadurl type="full" format="zip">https://github.com/joomla-extensions/patchtester/releases/download/' . $version['release'] . '/com_patchtester_' . $version['release'] . '.zip</downloadurl>', $fileContents);

View File

@ -14,8 +14,6 @@
}, },
"require-dev": { "require-dev": {
"joomla/crowdin-sync": "dev-master", "joomla/crowdin-sync": "dev-master",
"joomla/cms-coding-standards": "~2.0.0-alpha2@dev",
"joomla/coding-standards": "~3.0@dev",
"squizlabs/php_codesniffer": "~3.0" "squizlabs/php_codesniffer": "~3.0"
}, },
"autoload": { "autoload": {

978
composer.lock generated

File diff suppressed because it is too large Load Diff

32
ruleset.xml Normal file
View File

@ -0,0 +1,32 @@
<?xml version="1.0"?>
<ruleset name="Joomla-CMS">
<description>The Joomla CMS PSR-12 exceptions.</description>
<!-- Exclude folders not containing production code -->
<exclude-pattern type="relative">build/packag*</exclude-pattern>
<exclude-pattern type="relative">administrator/components/com_patchtester/vendor/*</exclude-pattern>
<rule ref="PSR12">
<exclude name="Generic.Files.LineEndings"/>
</rule>
<!-- temporary extend the line length -->
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="560"/>
<property name="absoluteLineLimit" value="560"/>
</properties>
</rule>
<rule ref="PSR1.Files.SideEffects">
<exclude-pattern type="relative">build/patchtester/release\.php</exclude-pattern>
</rule>
<rule ref="PSR1.Classes.ClassDeclaration">
<exclude-pattern type="relative">administrator/components/com_patchtester/script\.php</exclude-pattern>
</rule>
<rule ref="Squiz.Classes.ValidClassName">
<exclude-pattern type="relative">administrator/components/com_patchtester/script\.php</exclude-pattern>
</rule>
</ruleset>