From bc6600d592f42e5dbc8aca4c9dd3ccdb3122cfcc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?G=C3=BCnter=20Dressel?= <gd@protobyte.at>
Date: Sat, 27 Jan 2024 19:26:55 +0100
Subject: [PATCH] Optimizing for code sniffer complaints

---
 src/Access/OpcacheCtlAccess.php            | 23 +++++---
 src/Controller/OpcacheCtlController.php    | 62 +++++++++++-----------
 src/Controller/OpcacheReportController.php |  5 --
 src/Form/ConfirmResetOpcacheForm.php       |  3 +-
 src/Twig/Extension/FormatSize.php          | 25 +++++++--
 5 files changed, 71 insertions(+), 47 deletions(-)

diff --git a/src/Access/OpcacheCtlAccess.php b/src/Access/OpcacheCtlAccess.php
index 76ba739..72afe88 100644
--- a/src/Access/OpcacheCtlAccess.php
+++ b/src/Access/OpcacheCtlAccess.php
@@ -12,19 +12,29 @@ use Drupal\Core\Site\Settings;
 class OpcacheCtlAccess implements AccessInterface {
 
   /**
-   * List of IP addresses / network addresses allowed to access opcachectl
-   * sites.
+   * List of IP addresses allowed to access protected opcachectl routes.
    *
-   * settings.php:
+   * Example configuration in settings.php:
+   *
+   * ```
    * $settings['opcachectl_reset_remote_addresses'] = ['127.0.0.1', '::1'];
+   * ```
    *
    * @var array
    */
   protected $authorizedAddresses = [];
 
   /**
+   * Token required to access protected opcachectl routes.
+   *
+   * This Token will only be checked, if the request is made from a client
+   * with an address not listed in $authorizedAddresses.
+   *
    * Generate token via
+   *
+   * ```
    * #> cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1
+   * ```
    *
    * settings.php:
    * $settings['opcachectl_reset_token'] = 'somerandomvalue';
@@ -35,7 +45,6 @@ class OpcacheCtlAccess implements AccessInterface {
 
   /**
    * Constructs a new OpcacheCtlController object.
-   *
    */
   public function __construct() {
     $this->requestToken = trim(Settings::get("opcachectl_reset_token") ?? '');
@@ -43,12 +52,14 @@ class OpcacheCtlAccess implements AccessInterface {
   }
 
   /**
-   * A custom access check.
+   * A custom access check for protected opcachectl routes.
    *
    * @return \Drupal\Core\Access\AccessResult
+   *   Result of access check.
    */
   public function access() {
-    // TODO: set $request to method arguments once on Drupal 11 - see https://www.drupal.org/project/drupal/issues/2786941
+    // TODO: Set $request to method arguments once on
+    //   Drupal 11 - see https://www.drupal.org/project/drupal/issues/2786941
     $request = \Drupal::request();
     $ip = $request->getClientIp();
     if ($ip == $_SERVER['SERVER_ADDR'] || $ip == "127.0.0.1") {
diff --git a/src/Controller/OpcacheCtlController.php b/src/Controller/OpcacheCtlController.php
index 0ae3003..61715bd 100644
--- a/src/Controller/OpcacheCtlController.php
+++ b/src/Controller/OpcacheCtlController.php
@@ -1,16 +1,9 @@
 <?php
 
-/**
- * @file
- * Contains \Drupal\opcachectl\Controller\OpcacheCtlController.
- */
-
 namespace Drupal\opcachectl\Controller;
 
-use Drupal\Core\Config\ConfigFactoryInterface;
 use Drupal\Core\Controller\ControllerBase;
 use Drupal\Core\Logger\LoggerChannelFactory;
-use Drupal\Core\Site\Settings;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Request;
@@ -28,34 +21,14 @@ class OpcacheCtlController extends ControllerBase {
    */
   protected $logger;
 
-  /**
-   * List of IP addresses / network addresses allowed to access opcachectl
-   * sites.
-   *
-   * @var array
-   */
-  protected $authorizedAddresses = [];
-
-  /**
-   * Generate token via
-   * #> cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1
-   *
-   * settings.php:
-   * $config['opcachectl']['reset_token'] = 'somerandomvalue';
-   *
-   * @var string
-   */
-  protected $resetToken;
-
   /**
    * Constructs a new OpcacheCtlController object.
    *
-   * @param LoggerChannelFactory $logger
-   * @param ConfigFactoryInterface $config_factory
+   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger
+   *   Logger factory to use.
    */
-  public function __construct(LoggerChannelFactory $logger, ConfigFactoryInterface $config_factory) {
+  public function __construct(LoggerChannelFactory $logger) {
     $this->logger = $logger->get('opcachectl');
-    $this->resetToken = trim(Settings::get("opcachectl_reset_token") ?? '');
   }
 
   /**
@@ -64,14 +37,13 @@ class OpcacheCtlController extends ControllerBase {
   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('logger.factory'),
-      $container->get('config.factory')
     );
   }
 
   /**
    * Callback for the PHP OPcache statistics page.
    *
-   * @return string
+   * @return array
    *   The page output.
    */
   public function settingsPage() {
@@ -80,6 +52,14 @@ class OpcacheCtlController extends ControllerBase {
     return $output;
   }
 
+  /**
+   * Create JSON response to be used by opcachectl "API" routes.
+   *
+   * May help to keep responses consistent over various routes.
+   *
+   * @return \Symfony\Component\HttpFoundation\JsonResponse
+   *   The Response.
+   */
   protected function createControlResponse(array $data, $status = Response::HTTP_OK) {
     $data['host'] = gethostname();
     $data['address'] = $_SERVER['SERVER_ADDR'];
@@ -87,6 +67,15 @@ class OpcacheCtlController extends ControllerBase {
     return new JsonResponse($data, $status);
   }
 
+  /**
+   * Request current OPcache status.
+   *
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The Request.
+   *
+   * @return \Symfony\Component\HttpFoundation\JsonResponse
+   *   JSON Response describing current OPcache status.
+   */
   public function controlGet(Request $request) {
     if (!function_exists('opcache_get_status')) {
       return $this->createControlResponse(['error' => 'PHP OPcache not enabled'], Response::HTTP_INTERNAL_SERVER_ERROR);
@@ -94,6 +83,15 @@ class OpcacheCtlController extends ControllerBase {
     return $this->createControlResponse(['status' => opcache_get_status(FALSE)]);
   }
 
+  /**
+   * Request to reset OPcache.
+   *
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The request.
+   *
+   * @return \Symfony\Component\HttpFoundation\JsonResponse
+   *   JSON response describing operation error or current OPcache status.
+   */
   public function controlPurge(Request $request) {
     if (!function_exists('opcache_get_status')) {
       return $this->createControlResponse(['error' => 'PHP OPcache not enabled'], Response::HTTP_INTERNAL_SERVER_ERROR);
diff --git a/src/Controller/OpcacheReportController.php b/src/Controller/OpcacheReportController.php
index 7570ea0..b145ce9 100644
--- a/src/Controller/OpcacheReportController.php
+++ b/src/Controller/OpcacheReportController.php
@@ -1,10 +1,5 @@
 <?php
 
-/**
- * @file
- * Contains \Drupal\opcachectl\Controller\OpcacheReportController.
- */
-
 namespace Drupal\opcachectl\Controller;
 
 use Drupal\Core\Controller\ControllerBase;
diff --git a/src/Form/ConfirmResetOpcacheForm.php b/src/Form/ConfirmResetOpcacheForm.php
index 18c191b..83794d9 100644
--- a/src/Form/ConfirmResetOpcacheForm.php
+++ b/src/Form/ConfirmResetOpcacheForm.php
@@ -16,7 +16,8 @@ class ConfirmResetOpcacheForm extends ConfirmFormBase {
    */
   public function buildForm(array $form, FormStateInterface $form_state) {
     // TODO: check for opcache_get_status()[opcache_enabled]
-    // TODO: check for opcache_get_status()[restart_pending] or/and  opcache_get_status()[restart_in_progress]
+    // TODO: check for opcache_get_status()[restart_pending] or/and
+    //       opcache_get_status()[restart_in_progress]
     return parent::buildForm($form, $form_state);
   }
 
diff --git a/src/Twig/Extension/FormatSize.php b/src/Twig/Extension/FormatSize.php
index 8b6458a..5ff3db0 100644
--- a/src/Twig/Extension/FormatSize.php
+++ b/src/Twig/Extension/FormatSize.php
@@ -2,23 +2,42 @@
 
 namespace Drupal\opcachectl\Twig\Extension;
 
+use Drupal\Core\StringTranslation\ByteSizeMarkup;
 use Twig\Extension\AbstractExtension;
 use Twig\TwigFilter;
 
+/**
+ * Twig extensions to format byte counts.
+ */
 class FormatSize extends AbstractExtension {
 
+  /**
+   * {@inheritdoc}
+   */
   public function getFilters() {
     return [
-      new TwigFilter('format_size', [$this, 'formatSize']),
+      new TwigFilter('format_size', [$this, 'formatByteSize']),
     ];
   }
 
+  /**
+   * {@inheritdoc}
+   */
   public function getName() {
     return 'format_size';
   }
 
-  function formatSize($size) {
-    return format_size($size);
+  /**
+   * Format byte size in human-readable format.
+   *
+   * @param float|int $size
+   *   Bytes.
+   *
+   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
+   *   Formatted string.
+   */
+  public function formatByteSize($size) {
+    return ByteSizeMarkup::create($size ?? 0);
   }
 
 }
-- 
GitLab