[TASK] Move extConf into its own Object 52/46952/3
authorStefan Froemken <froemken@gmail.com>
Mon, 29 Feb 2016 07:23:25 +0000 (08:23 +0100)
committerFrancois Suter <francois@typo3.org>
Wed, 6 Jul 2016 14:13:09 +0000 (16:13 +0200)
Move extension configuration into a model object,
to be injected wherever it is needed.

Resolves: #73691
Releases: master
Change-Id: I5ca33428ccce04f4e3eaa879393615256f1581a8
Reviewed-on: https://review.typo3.org/46952
Reviewed-by: Francois Suter <francois@typo3.org>
Tested-by: Francois Suter <francois@typo3.org>
Classes/Domain/Model/ExtensionConfiguration.php [new file with mode: 0644]
Classes/Domain/Repository/EntryRepository.php
Classes/Utility/Logger.php
Classes/Writer/AbstractWriter.php
Classes/Writer/DatabaseWriter.php
Classes/Writer/FileWriter.php
Classes/Writer/WriterInterface.php
Tests/Unit/Domain/Model/EntryTest.php
Tests/Unit/Domain/Model/ExtensionConfigurationTest.php [new file with mode: 0644]
Tests/Unit/Utility/LoggerTest.php

diff --git a/Classes/Domain/Model/ExtensionConfiguration.php b/Classes/Domain/Model/ExtensionConfiguration.php
new file mode 100644 (file)
index 0000000..dfc73a2
--- /dev/null
@@ -0,0 +1,302 @@
+<?php
+
+namespace Devlog\Devlog\Domain\Model;
+
+/**
+ * This file is part of the TYPO3 CMS project.
+ *
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
+ *
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
+ *
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use TYPO3\CMS\Core\SingletonInterface;
+
+/**
+ * Object containing the extension configuration.
+ *
+ * NOTE: this is not a true Extbase object.
+ * 
+ * @author Stefan Froemken <froemken@gmail.com>
+ */
+class ExtensionConfiguration implements SingletonInterface
+{
+    /**
+     * Minimum log level
+     *
+     * @var int
+     */
+    protected $minimumLogLevel = -1;
+
+    /**
+     * Exclude Keys
+     *
+     * @var string
+     */
+    protected $excludeKeys = '';
+
+    /**
+     * Ip Filter
+     *
+     * @var string
+     */
+    protected $ipFilter = '';
+
+    /**
+     * Refresh Frequency
+     *
+     * @var int
+     */
+    protected $refreshFrequency = 2;
+
+    /**
+     * Entries per Page
+     *
+     * @var int
+     */
+    protected $entriesPerPage = 25;
+
+    /**
+     * Maximum Rows
+     *
+     * @var int
+     */
+    protected $maximumRows = 1000;
+
+    /**
+     * optimizeTable
+     *
+     * @var bool
+     */
+    protected $optimizeTable = true;
+
+    /**
+     * Maximum extra data size
+     *
+     * @var int
+     */
+    protected $maximumExtraDataSize = 1000000;
+
+    /**
+     * Log file path
+     *
+     * @var string
+     */
+    protected $logFilePath = '';
+
+    /**
+     * Constructor.
+     *
+     * Reads the global configuration and calls the setter methods.
+     */
+    public function __construct()
+    {
+        // Get global configuration
+        $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['devlog']);
+        if (is_array($extensionConfiguration)) {
+            // Call setter method foreach configuration entry
+            foreach ($extensionConfiguration as $key => $value) {
+                $methodName = 'set' . ucfirst($key);
+                if (method_exists($this, $methodName)) {
+                    $this->$methodName($value);
+                }
+            }
+        }
+    }
+
+    /**
+     * Returns the minimumLogLevel.
+     *
+     * @return int $minimumLogLevel
+     */
+    public function getMinimumLogLevel()
+    {
+        return $this->minimumLogLevel;
+    }
+
+    /**
+     * Sets the minimumLogLevel.
+     *
+     * @param int $minimumLogLevel
+     * @return void
+     */
+    public function setMinimumLogLevel($minimumLogLevel)
+    {
+        $this->minimumLogLevel = (int)$minimumLogLevel;
+    }
+
+    /**
+     * Returns the excludeKeys.
+     *
+     * @return string $excludeKeys
+     */
+    public function getExcludeKeys()
+    {
+        return $this->excludeKeys;
+    }
+
+    /**
+     * Sets the excludeKeys.
+     *
+     * @param string $excludeKeys
+     * @return void
+     */
+    public function setExcludeKeys($excludeKeys)
+    {
+        $this->excludeKeys = (string)$excludeKeys;
+    }
+
+    /**
+     * Returns the ipFilter.
+     *
+     * @return string $ipFilter
+     */
+    public function getIpFilter()
+    {
+        return $this->ipFilter;
+    }
+
+    /**
+     * Sets the ipFilter.
+     *
+     * @param string $ipFilter
+     * @return void
+     */
+    public function setIpFilter($ipFilter)
+    {
+        $this->ipFilter = (string)$ipFilter;
+    }
+
+    /**
+     * Returns the refreshFrequency.
+     *
+     * @return int $refreshFrequency
+     */
+    public function getRefreshFrequency()
+    {
+        return $this->refreshFrequency;
+    }
+
+    /**
+     * Sets the refreshFrequency.
+     *
+     * @param int $refreshFrequency
+     * @return void
+     */
+    public function setRefreshFrequency($refreshFrequency)
+    {
+        $this->refreshFrequency = (int)$refreshFrequency;
+    }
+
+    /**
+     * Returns the entriesPerPage.
+     *
+     * @return int $entriesPerPage
+     */
+    public function getEntriesPerPage()
+    {
+        return $this->entriesPerPage;
+    }
+
+    /**
+     * Sets the entriesPerPage.
+     *
+     * @param int $entriesPerPage
+     * @return void
+     */
+    public function setEntriesPerPage($entriesPerPage)
+    {
+        $this->entriesPerPage = (int)$entriesPerPage;
+    }
+
+    /**
+     * Returns the maximumRows.
+     *
+     * @return int $maximumRows
+     */
+    public function getMaximumRows()
+    {
+        return $this->maximumRows;
+    }
+
+    /**
+     * Sets the maximumRows.
+     *
+     * @param int $maximumRows
+     * @return void
+     */
+    public function setMaximumRows($maximumRows)
+    {
+        $this->maximumRows = (int)$maximumRows;
+    }
+
+    /**
+     * Returns the optimizeTable.
+     *
+     * @return bool $optimizeTable
+     */
+    public function getOptimizeTable()
+    {
+        return $this->optimizeTable;
+    }
+
+    /**
+     * Sets the optimizeTable.
+     *
+     * @param bool $optimizeTable
+     * @return void
+     */
+    public function setOptimizeTable($optimizeTable)
+    {
+        $this->optimizeTable = (bool)$optimizeTable;
+    }
+
+    /**
+     * Returns the maximumExtraDataSize.
+     *
+     * @return int $maximumExtraDataSize
+     */
+    public function getMaximumExtraDataSize()
+    {
+        return $this->maximumExtraDataSize;
+    }
+
+    /**
+     * Sets the maximumExtraDataSize.
+     *
+     * @param int $maximumExtraDataSize
+     * @return void
+     */
+    public function setMaximumExtraDataSize($maximumExtraDataSize)
+    {
+        $this->maximumExtraDataSize = (int)$maximumExtraDataSize;
+    }
+
+    /**
+     * Returns the logFilePath.
+     *
+     * @return string $logFilePath
+     *
+     * @throws \UnexpectedValueException
+     */
+    public function getLogFilePath()
+    {
+        return $this->logFilePath;
+    }
+
+    /**
+     * Sets the logFilePath.
+     *
+     * @param string $logFilePath
+     * @return void
+     */
+    public function setLogFilePath($logFilePath)
+    {
+        $this->logFilePath = (string)$logFilePath;
+    }
+}
index 2535f88..1dae7b6 100644 (file)
@@ -14,6 +14,7 @@ namespace Devlog\Devlog\Domain\Repository;
  * The TYPO3 project - inspiring people to share!
  */
 
+use Devlog\Devlog\Domain\Model\ExtensionConfiguration;
 use TYPO3\CMS\Core\SingletonInterface;
 
 /**
@@ -32,7 +33,7 @@ class EntryRepository implements SingletonInterface
     protected $databaseTable = 'tx_devlog_domain_model_entry';
 
     /**
-     * @var array Extension configuration
+     * @var ExtensionConfiguration Extension configuration
      */
     protected $extensionConfiguration = null;
 
@@ -47,7 +48,7 @@ class EntryRepository implements SingletonInterface
      * By default records are sorted by descending creation date and
      * ascending order.
      *
-     * @return array|NULL
+     * @return array|null
      */
     public function findAll()
     {
@@ -93,7 +94,7 @@ class EntryRepository implements SingletonInterface
         // Handle extra data
         $fields['extra_data'] = gzcompress(serialize($entry->getExtraData()));
         $extraDataSize = strlen($fields['extra_data']);
-        $maximumExtraDataSize = $this->extensionConfiguration['maximumExtraDataSize'];
+        $maximumExtraDataSize = $this->extensionConfiguration->getMaximumExtraDataSize();
         // If the entry's extra data is above the limit, replace it with a warning
         if (!empty($maximumExtraDataSize) && $extraDataSize > $maximumExtraDataSize) {
             $fields['extra_data'] = gzcompress(serialize('Extra data too large, not saved.'));
@@ -119,12 +120,12 @@ class EntryRepository implements SingletonInterface
             );
         }
         // Check if number of rows is above the limit and clean up if necessary
-        if ($this->numberOfRows > $this->extensionConfiguration['maximumRows']) {
+        if ($this->numberOfRows > $this->extensionConfiguration->getMaximumRows()) {
             // Select the row from which to start cleaning up
             // To achieve this, order by creation date (so oldest comes first)
             // then offset by 10% of maximumRows and get the next record
             // This will return a timestamp that is used as a cut-off date
-            $numberOfRowsToRemove = round(0.1 * $this->extensionConfiguration['maximumRows']);
+            $numberOfRowsToRemove = round(0.1 * $this->extensionConfiguration->getMaximumRows());
             $cutOffRow = $this->getDatabaseConnection()->exec_SELECTgetRows(
                     'crdate',
                     'tx_devlog_domain_model_entry',
@@ -145,7 +146,7 @@ class EntryRepository implements SingletonInterface
             // Update (cached) number of rows
             $this->numberOfRows -= $numberOfRemovedRows;
             // Optimize the table (if option is active)
-            if ($this->extensionConfiguration['optimize']) {
+            if ($this->extensionConfiguration->getOptimizeTable()) {
                 $this->getDatabaseConnection()->sql_query('OPTIMIZE table tx_devlog_domain_model_entry');
             }
         }
@@ -157,7 +158,7 @@ class EntryRepository implements SingletonInterface
      *
      * Used to pass the "devlog" configuration down to the entry repository.
      *
-     * @param array $configuration
+     * @param ExtensionConfiguration $configuration
      */
     public function setExtensionConfiguration($configuration)
     {
index 31ec6e8..be520c1 100644 (file)
@@ -14,6 +14,8 @@ namespace Devlog\Devlog\Utility;
  * The TYPO3 project - inspiring people to share!
  */
 
+use Devlog\Devlog\Domain\Model\Entry;
+use Devlog\Devlog\Domain\Model\ExtensionConfiguration;
 use Devlog\Devlog\Writer\WriterInterface;
 use TYPO3\CMS\Core\SingletonInterface;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
@@ -28,9 +30,11 @@ use TYPO3\CMS\Core\Utility\GeneralUtility;
 class Logger implements SingletonInterface
 {
     /**
-     * @var array Devlog extension configuration
+     * Devlog extension configuration
+     *
+     * @var ExtensionConfiguration
      */
-    protected $extensionConfiguration = array();
+    protected $extensionConfiguration = null;
 
     /**
      * @var array List of instances of each available log writer
@@ -40,7 +44,7 @@ class Logger implements SingletonInterface
     /**
      * @var bool Flag used to turn logging off
      */
-    protected $isLoggingEnabled = TRUE;
+    protected $isLoggingEnabled = true;
 
     /**
      * @var string Unique ID of the current run
@@ -55,7 +59,7 @@ class Logger implements SingletonInterface
     public function __construct()
     {
         // Read the extension configuration
-        $this->extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['devlog']);
+        $this->extensionConfiguration = GeneralUtility::makeInstance(ExtensionConfiguration::class);
 
         // Use microtime as unique ID (in format "sec.msec")
         $microtimeParts = explode(' ', microtime());
@@ -65,14 +69,13 @@ class Logger implements SingletonInterface
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['devlog']['writers'] as $logWriterClass) {
             try {
                 $logWriter = GeneralUtility::makeInstance(
-                    $logWriterClass,
-                    $this
+                        $logWriterClass,
+                        $this
                 );
                 if ($logWriter instanceof WriterInterface) {
                     $this->logWriters[] = $logWriter;
                 }
-            }
-            catch (\Exception $e) {
+            } catch (\Exception $e) {
                 // TODO: report somewhere that writer could not be instantiated (sys_log?)
             }
         }
@@ -82,10 +85,10 @@ class Logger implements SingletonInterface
      * Logs calls passed to \TYPO3\CMS\Core\Utility\GeneralUtility::devLog().
      *
      * $logData = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
-     *         'msg'           string          Message (in english).
-     *         'extKey'        string          Extension key (from which extension you are calling the log)
-     *         'severity'      integer         Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
-     *         'dataVar'       array           Additional data you want to pass to the logger.
+     *        'msg'        string        Message (in english).
+     *        'extKey'    string        Extension key (from which extension you are calling the log)
+     *        'severity'    integer        Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
+     *        'dataVar'    array        Additional data you want to pass to the logger.
      *
      * @param array $logData Log data
      * @return void
@@ -103,34 +106,34 @@ class Logger implements SingletonInterface
             return;
         }
         // Disable logging while inside the devlog, to avoid recursive calls
-        $this->isLoggingEnabled = FALSE;
+        $this->isLoggingEnabled = false;
 
         // Create an entry and fill it with data
-        /** @var \Devlog\Devlog\Domain\Model\Entry $entry */
-        $entry = GeneralUtility::makeInstance('Devlog\\Devlog\\Domain\\Model\\Entry');
+        /** @var Entry $entry */
+        $entry = GeneralUtility::makeInstance(Entry::class);
         $entry->setRunId(
-            $this->runId
+                $this->runId
         );
         $entry->setSorting(
-            $this->counter
+                $this->counter
         );
         $this->counter++;
         $entry->setCrdate($GLOBALS['EXEC_TIME']);
         $entry->setMessage(
-            GeneralUtility::removeXSS($logData['msg'])
+                GeneralUtility::removeXSS($logData['msg'])
         );
         $entry->setExtkey(
-            strip_tags($logData['extKey'])
+                strip_tags($logData['extKey'])
         );
         $entry->setSeverity(
-            intval($logData['severity'])
+                (int)$logData['severity']
         );
         $entry->setExtraData($logData['dataVar']);
 
         // Try to get a page id that makes sense
         $pid = 0;
         // In the FE context, this is obviously the current page
-        if (TYPO3_MODE == 'FE') {
+        if (TYPO3_MODE === 'FE') {
             $pid = $GLOBALS['TSFE']->id;
 
         // In other contexts, a global variable may be set with a relevant pid
@@ -140,19 +143,18 @@ class Logger implements SingletonInterface
         $entry->setPid($pid);
 
         $entry->setCruserId(
-            (isset($GLOBALS['BE_USER']->user['uid'])) ? $GLOBALS['BE_USER']->user['uid'] : 0
+                (isset($GLOBALS['BE_USER']->user['uid'])) ? $GLOBALS['BE_USER']->user['uid'] : 0
         );
         $entry->setIp(
-            $logData['ip']
+                $logData['ip']
         );
 
         // Get information about the place where this method was called from
         try {
-            $callPlaceInfo = $this->getCallPlaceInfo(debug_backtrace());
+            $callPlaceInfo = $this->getCallPlaceInfo();
             $entry->setLocation($callPlaceInfo['basename']);
             $entry->setLine($callPlaceInfo['line']);
-        }
-        catch (\OutOfBoundsException $e) {
+        } catch (\OutOfBoundsException $e) {
             // Do nothing
         }
 
@@ -161,7 +163,7 @@ class Logger implements SingletonInterface
         foreach ($this->logWriters as $logWriter) {
             $logWriter->write($entry);
         }
-        $this->isLoggingEnabled = TRUE;
+        $this->isLoggingEnabled = true;
     }
 
     /**
@@ -173,18 +175,18 @@ class Logger implements SingletonInterface
     public function isEntryAccepted($logData)
     {
         // Skip entry if severity is below minimum level
-        if ($logData['severity'] < $this->extensionConfiguration['minimumLogLevel']) {
-            return FALSE;
+        if ($logData['severity'] < $this->extensionConfiguration->getMinimumLogLevel()) {
+            return false;
         }
         // Skip entry if key is in excluded list
-        if (GeneralUtility::inList($this->extensionConfiguration['excludeKeys'], $logData['extKey'])) {
-            return FALSE;
+        if (GeneralUtility::inList($this->extensionConfiguration->getExcludeKeys(), $logData['extKey'])) {
+            return false;
         }
         // Skip entry if referrer does not match IP mask
         if (!$this->isIpAddressAccepted($logData['ip'])) {
-            return FALSE;
+            return false;
         }
-        return TRUE;
+        return true;
     }
 
     /**
@@ -195,7 +197,7 @@ class Logger implements SingletonInterface
      */
     public function isIpAddressAccepted($ipAddress)
     {
-        $ipFilter = $this->extensionConfiguration['ipFilter'];
+        $ipFilter = $this->extensionConfiguration->getIpFilter();
         // Re-use global IP mask if so defined
         if (strtolower($ipFilter) === 'devipmask') {
             $ipFilter = $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask'];
@@ -207,7 +209,7 @@ class Logger implements SingletonInterface
      * Given a backtrace, this method tries to find the place where a "devLog" function was called
      * and returns info about that place.
      *
-     * @return array   information about the call place
+     * @return    array    information about the call place
      */
     protected function getCallPlaceInfo()
     {
@@ -220,15 +222,15 @@ class Logger implements SingletonInterface
             }
         }
         throw new \OutOfBoundsException(
-            'No devLog() call found withing debug stack.',
-            1414338781
+                'No devLog() call found withing debug stack.',
+                1414338781
         );
     }
 
     /**
      * Returns the extension's configuration.
      *
-     * @return array
+     * @return ExtensionConfiguration
      */
     public function getExtensionConfiguration()
     {
@@ -240,7 +242,7 @@ class Logger implements SingletonInterface
      *
      * This should normally not be used. It is designed for unit testing.
      *
-     * @param array $extensionConfiguration
+     * @param ExtensionConfiguration $extensionConfiguration
      * @return void
      */
     public function setExtensionConfiguration($extensionConfiguration)
index 6dc13c1..90af414 100644 (file)
@@ -1,30 +1,20 @@
 <?php
 namespace Devlog\Devlog\Writer;
 
-/***************************************************************
- *
- *  Copyright notice
- *
- *  (c) 2014 François Suter <typo3@cobweb.ch>, Cobweb Development Sarl
- *
- *  All rights reserved
- *
- *  This script is part of the TYPO3 project. The TYPO3 project is
- *  free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
+/**
+ * This file is part of the TYPO3 CMS project.
  *
- *  The GNU General Public License can be found at
- *  http://www.gnu.org/copyleft/gpl.html.
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
  *
- *  This script is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
  *
- *  This copyright notice MUST APPEAR in all copies of the script!
- ***************************************************************/
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use Devlog\Devlog\Utility\Logger;
 
 /**
  * Abstract base class for all Writers.
@@ -32,14 +22,14 @@ namespace Devlog\Devlog\Writer;
 abstract class AbstractWriter implements WriterInterface
 {
     /**
-     * @var \Devlog\Devlog\Utility\Logger Back-reference to the logger class
+     * @var Logger Back-reference to the logger class
      */
     protected $logger;
 
     /**
      * Base constructor sets the Logger reference.
      *
-     * @param \Devlog\Devlog\Utility\Logger $logger
+     * @param Logger $logger
      */
     public function __construct($logger)
     {
index 77a5a6a..9e91769 100644 (file)
@@ -1,31 +1,23 @@
 <?php
 namespace Devlog\Devlog\Writer;
 
-
-/***************************************************************
- *
- *  Copyright notice
- *
- *  (c) 2014 François Suter <typo3@cobweb.ch>, Cobweb Development Sarl
- *
- *  All rights reserved
- *
- *  This script is part of the TYPO3 project. The TYPO3 project is
- *  free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
+/**
+ * This file is part of the TYPO3 CMS project.
  *
- *  The GNU General Public License can be found at
- *  http://www.gnu.org/copyleft/gpl.html.
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
  *
- *  This script is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
  *
- *  This copyright notice MUST APPEAR in all copies of the script!
- ***************************************************************/
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use Devlog\Devlog\Domain\Model\Entry;
+use Devlog\Devlog\Domain\Repository\EntryRepository;
+use Devlog\Devlog\Utility\Logger;
+use TYPO3\CMS\Core\Utility\GeneralUtility;
 
 /**
  * Writes log entries to a database table.
@@ -33,28 +25,28 @@ namespace Devlog\Devlog\Writer;
 class DatabaseWriter extends AbstractWriter
 {
     /**
-     * @var \Devlog\Devlog\Domain\Repository\EntryRepository
+     * @var EntryRepository
      */
     protected $entryRepository;
 
     /**
      * DatabaseWriter constructor.
      *
-     * @param \Devlog\Devlog\Utility\Logger $logger
+     * @param Logger $logger
      */
     public function __construct($logger)
     {
         parent::__construct($logger);
-        $this->entryRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Devlog\\Devlog\\Domain\\Repository\\EntryRepository');
+        $this->entryRepository = GeneralUtility::makeInstance(EntryRepository::class);
         $this->entryRepository->setExtensionConfiguration(
-            $this->logger->getExtensionConfiguration()
+                $this->logger->getExtensionConfiguration()
         );
     }
 
     /**
      * Writes the entry to the DB storage.
      *
-     * @param \Devlog\Devlog\Domain\Model\Entry $entry
+     * @param Entry $entry
      * @return void
      */
     public function write($entry)
index 76f9413..ecce25e 100644 (file)
@@ -1,31 +1,20 @@
 <?php
 namespace Devlog\Devlog\Writer;
 
-
-/***************************************************************
- *
- *  Copyright notice
- *
- *  (c) 2014 François Suter <typo3@cobweb.ch>, Cobweb Development Sarl
- *
- *  All rights reserved
- *
- *  This script is part of the TYPO3 project. The TYPO3 project is
- *  free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
+/**
+ * This file is part of the TYPO3 CMS project.
  *
- *  The GNU General Public License can be found at
- *  http://www.gnu.org/copyleft/gpl.html.
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
  *
- *  This script is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
  *
- *  This copyright notice MUST APPEAR in all copies of the script!
- ***************************************************************/
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use Devlog\Devlog\Utility\Logger;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 
 /**
@@ -43,40 +32,30 @@ class FileWriter extends AbstractWriter
     /**
      * FileWriter constructor.
      *
-     * @param \Devlog\Devlog\Utility\Logger $logger
+     * @param Logger $logger
      *
-     * @throws \Exception
+     * @throws \UnexpectedValueException
      */
     public function __construct($logger)
     {
         parent::__construct($logger);
         $configuration = $this->logger->getExtensionConfiguration();
         $absoluteFilePath = GeneralUtility::getFileAbsFileName(
-            $configuration['logFilePath']
+                $configuration->getLogFilePath()
         );
-        // If the file path is not valid, throw an exception
-        if (empty($absoluteFilePath)) {
-            throw new \Exception(
-                sprintf(
-                    'Path to log file %s is invalid.',
-                    $configuration['logFilePath']
-                ),
-                1416486859
-            );
-        }
         // If the file path is valid, try opening the file
         $this->fileHandle = @fopen(
-            $absoluteFilePath,
-            'a'
+                $absoluteFilePath,
+                'a'
         );
         // Throw an exception if log file could not be opened properly
         if (!$this->fileHandle) {
-            throw new \Exception(
-                sprintf(
-                    'Log file %s could not be opened.',
-                    $configuration['logFilePath']
-                ),
-                1416486470
+            throw new \UnexpectedValueException(
+                    sprintf(
+                            'Log file %s could not be opened.',
+                            $configuration->getLogFilePath()
+                    ),
+                    1416486470
             );
         }
     }
@@ -120,8 +99,8 @@ class FileWriter extends AbstractWriter
         $logLine .= ' (' . $entry->getLocation() . ' ' . $entry->getLine() . ')';
         $logLine .= "\n";
         @fwrite(
-            $this->fileHandle,
-            $logLine
+                $this->fileHandle,
+                $logLine
         );
     }
 }
\ No newline at end of file
index e1419f3..ef3b678 100644 (file)
@@ -1,30 +1,20 @@
 <?php
 namespace Devlog\Devlog\Writer;
 
-/***************************************************************
- *
- *  Copyright notice
- *
- *  (c) 2014 François Suter <typo3@cobweb.ch>, Cobweb Development Sarl
- *
- *  All rights reserved
- *
- *  This script is part of the TYPO3 project. The TYPO3 project is
- *  free software; you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 3 of the License, or
- *  (at your option) any later version.
+/**
+ * This file is part of the TYPO3 CMS project.
  *
- *  The GNU General Public License can be found at
- *  http://www.gnu.org/copyleft/gpl.html.
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
  *
- *  This script is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
  *
- *  This copyright notice MUST APPEAR in all copies of the script!
- ***************************************************************/
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use Devlog\Devlog\Domain\Model\Entry;
 
 /**
  * API definition for log writers
@@ -34,7 +24,7 @@ interface WriterInterface
     /**
      * Writes the entry to the relevant storage.
      *
-     * @param \Devlog\Devlog\Domain\Model\Entry $entry
+     * @param Entry $entry
      * @return mixed
      */
     public function write($entry);
index 7c502d7..89f200f 100644 (file)
@@ -16,13 +16,14 @@ namespace Devlog\Devlog\Tests\Unit\Domain\Model;
  */
 
 use Devlog\Devlog\Domain\Model\Entry;
+use TYPO3\CMS\Core\Tests\UnitTestCase;
 
 /**
  * Test case for class \Devlog\Devlog\Domain\Model\Entry.
  *
  * @author François Suter <typo3@cobweb.ch>
  */
-class EntryTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
+class EntryTest extends UnitTestCase
 {
     /**
      * @var array List of globals to exclude (contain closures which cannot be serialized)
diff --git a/Tests/Unit/Domain/Model/ExtensionConfigurationTest.php b/Tests/Unit/Domain/Model/ExtensionConfigurationTest.php
new file mode 100644 (file)
index 0000000..f5022ac
--- /dev/null
@@ -0,0 +1,347 @@
+<?php
+
+namespace Devlog\Devlog\Tests\Unit\Domain\Model;
+
+/**
+ * This file is part of the TYPO3 CMS project.
+ *
+ * It is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License, either version 2
+ * of the License, or any later version.
+ *
+ * For the full copyright and license information, please read the
+ * LICENSE.txt file that was distributed with this source code.
+ *
+ * The TYPO3 project - inspiring people to share!
+ */
+
+use Devlog\Devlog\Domain\Model\ExtensionConfiguration;
+use TYPO3\CMS\Core\Tests\UnitTestCase;
+
+/**
+ * Test case for class \Devlog\Devlog\Domain\Model\ExtensionConfiguration.
+ *
+ * @author François Suter <typo3@cobweb.ch>
+ */
+class ExtensionConfigurationTest extends UnitTestCase
+{
+    /**
+     * @var array List of globals to exclude (contain closures which cannot be serialized)
+     */
+    protected $backupGlobalsBlacklist = array('TYPO3_LOADED_EXT', 'TYPO3_CONF_VARS');
+
+    /**
+     * @var ExtensionConfiguration
+     */
+    protected $subject = null;
+
+    protected function setUp()
+    {
+        // Override existing configuration for testing
+        $GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['devlog'] = serialize(array());
+        $this->subject = new ExtensionConfiguration();
+    }
+
+    protected function tearDown()
+    {
+        unset($this->subject);
+    }
+
+    /**
+     * @test
+     */
+    public function getMinimumLogLevelInitiallyReturnsDefaultValue()
+    {
+        self::assertSame(
+                -1,
+                $this->subject->getMinimumLogLevel()
+        );
+    }
+
+    /**
+     * @test
+     * @param mixed $input Input value
+     * @param int $expected Value cast to integer
+     * @dataProvider integerProvider
+     */
+    public function setMinimumLogLevelSetsLevel($input, $expected)
+    {
+        $this->subject->setMinimumLogLevel($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getMinimumLogLevel()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getExcludeKeysInitiallyReturnsEmptryString()
+    {
+        self::assertSame(
+                '',
+                $this->subject->getExcludeKeys()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function setExcludeKeysSetsKeys()
+    {
+        $keys = 'core,extbase';
+        $this->subject->setExcludeKeys($keys);
+        self::assertSame(
+                $keys,
+                $this->subject->getExcludeKeys()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getIpFilterInitiallyReturnsEmptyString()
+    {
+        self::assertSame(
+                '',
+                $this->subject->getIpFilter()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function setIpFilterSetsFilter()
+    {
+        $filter = '::1,127.0.0.1';
+        $this->subject->setIpFilter($filter);
+        self::assertSame(
+                $filter,
+                $this->subject->getIpFilter()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getRefreshFrequencyInitiallyReturnsDefaultValue()
+    {
+        self::assertSame(
+                2,
+                $this->subject->getRefreshFrequency()
+        );
+    }
+
+    /**
+     * @test
+     * @param mixed $input Input value
+     * @param int $expected Value cast to integer
+     * @dataProvider integerProvider
+     */
+    public function setRefreshFrequencySetFrequency($input, $expected)
+    {
+        $this->subject->setRefreshFrequency($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getRefreshFrequency()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getEntriesPerPageInitiallyReturnsDefaultValue()
+    {
+        self::assertSame(
+                25,
+                $this->subject->getEntriesPerPage()
+        );
+    }
+
+    /**
+     * @test
+     * @param mixed $input Input value
+     * @param int $expected Value cast to integer
+     * @dataProvider integerProvider
+     */
+    public function setEntriesPerPageSetsEntries($input, $expected)
+    {
+        $this->subject->setEntriesPerPage($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getEntriesPerPage()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getMaximumRowsInitiallyReturnsDefaultValue() {
+        self::assertSame(
+                1000,
+                $this->subject->getMaximumRows()
+        );
+    }
+
+    /**
+     * @test
+     * @param mixed $input Input value
+     * @param int $expected Value cast to integer
+     * @dataProvider integerProvider
+     */
+    public function setMaximumRowsSetsMaximum($input, $expected)
+    {
+        $this->subject->setMaximumRows($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getMaximumRows()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getOptimizeTableInitiallyReturnsTrue() {
+        self::assertTrue(
+                $this->subject->getOptimizeTable()
+        );
+    }
+
+    /**
+     * @test
+     * @param $input
+     * @param $expected
+     * @dataProvider booleanProvider
+     */
+    public function setOptimizeTableSetsOptimizeFlag($input, $expected)
+    {
+        $this->subject->setOptimizeTable($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getOptimizeTable()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getMaximumExtraDataSizeInitiallyReturnsDefaultValue() {
+        self::assertSame(
+                1000000,
+                $this->subject->getMaximumExtraDataSize()
+        );
+    }
+
+    /**
+     * @test
+     * @param mixed $input Input value
+     * @param int $expected Value cast to integer
+     * @dataProvider integerProvider
+     */
+    public function setMaximumExtraDataSizeSetsMaximum($input, $expected)
+    {
+        $this->subject->setMaximumExtraDataSize($input);
+        self::assertSame(
+                $expected,
+                $this->subject->getMaximumExtraDataSize()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function getLogFilePathInitiallyReturnsEmptyString() {
+        self::assertSame(
+                '',
+                $this->subject->getLogFilePath()
+        );
+    }
+
+    /**
+     * @test
+     */
+    public function setLogFilePathSetsPath() {
+        $path = 'typo3temp/foo.txt';
+        $this->subject->setLogFilePath($path);
+        self::assertSame(
+                $path,
+                $this->subject->getLogFilePath()
+        );
+    }
+
+    /**
+     * Provides integer or pseudo-integer values for testing
+     * integer setters.
+     *
+     * @return array
+     */
+    public function integerProvider()
+    {
+        return array(
+            'true integer' => array(
+                10,
+                10
+            ),
+            'integer string' => array(
+                '12',
+                12
+            ),
+            'integer and more string' => array(
+                '9 yards',
+                9
+            ),
+            'arbitrary string' => array(
+                'foo bar',
+                0
+            ),
+            'boolean true' => array(
+                true,
+                1
+            ),
+            'boolean false' => array(
+                false,
+                0
+            )
+        );
+    }
+
+    /**
+     * Provides boolean or pseudo-boolean values for testing
+     * boolean setters.
+     *
+     * @return array
+     */
+    public function booleanProvider()
+    {
+        return array(
+            'boolean' => array(
+                true,
+                true
+            ),
+            'integer 0' => array(
+                0,
+                false
+            ),
+            'any integer' => array(
+                23,
+                true
+            ),
+            'true string' => array(
+                'true',
+                true
+            ),
+            'false string' => array(
+                'false',
+                true
+            ),
+            'empty string' => array(
+                '',
+                false
+            ),
+            'null' => array(
+                '',
+                false
+            )
+        );
+    }
+}
index 990f08a..de87f6b 100644 (file)
@@ -14,14 +14,17 @@ namespace Devlog\Devlog\Tests\Unit\Utility;
  *
  * The TYPO3 project - inspiring people to share!
  */
+
+use Devlog\Devlog\Domain\Model\ExtensionConfiguration;
 use Devlog\Devlog\Utility\Logger;
+use TYPO3\CMS\Core\Tests\UnitTestCase;
 
 /**
  * Test case for class \Devlog\Devlog\Logger.
  *
  * @author François Suter <typo3@cobweb.ch>
  */
-class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
+class LoggerTest extends UnitTestCase
 {
     /**
      * @var array List of globals to exclude (contain closures which cannot be serialized)
@@ -34,23 +37,22 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
     protected $subject = null;
 
     /**
-     * @var array Test extension configuration
+     * @var ExtensionConfiguration
      */
-    protected $testConfiguration = array(
-            'minimumLogLevel' => 1,
-            'excludeKeys' => 'foo,bar',
-            'ipFilter' => '127.0.0.1,::1'
-    );
+    protected $extensionConfiguration = null;
 
     /**
      * Set up
      */
     protected function setUp()
     {
+        $this->extensionConfiguration = new ExtensionConfiguration();
+        $this->extensionConfiguration->setMinimumLogLevel(1);
+        $this->extensionConfiguration->setExcludeKeys('foo,bar');
+        $this->extensionConfiguration->setIpFilter('127.0.0.1,::1');
+
         $this->subject = new Logger();
-        $this->subject->setExtensionConfiguration(
-                $this->testConfiguration
-        );
+        $this->subject->setExtensionConfiguration($this->extensionConfiguration);
     }
 
     /**
@@ -58,7 +60,7 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
      */
     protected function tearDown()
     {
-        unset($this->subject);
+        unset($this->extensionConfiguration, $this->subject);
     }
 
     /**
@@ -166,7 +168,7 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
      * @param string $testValue IP address to test
      * @param string $configurationOverride Override IP filter in extension configuration
      * @param string $devIpMask Value for overriding $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
-     * @param boolean $result TRUE or FALSE, depending on IP address validity
+     * @param boolean $result true or false, depending on IP address validity
      * @test
      * @dataProvider ipAddressesProvider
      * @covers       \Devlog\Devlog\Utility\Logger::isIpAddressAccepted
@@ -180,11 +182,9 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
         }
         // Override extension configuration
         if (!empty($configurationOverride)) {
-            $specialConfiguration = $this->testConfiguration;
-            $specialConfiguration['ipFilter'] = $configurationOverride;
-            $this->subject->setExtensionConfiguration(
-                    $specialConfiguration
-            );
+            $specialConfiguration = clone $this->extensionConfiguration;
+            $specialConfiguration->setIpFilter($configurationOverride);
+            $this->subject->setExtensionConfiguration($specialConfiguration);
         }
         // Perform the actual test
         self::assertSame(
@@ -194,9 +194,7 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
                 )
         );
         // Restore extension configuration
-        $this->subject->setExtensionConfiguration(
-                $this->testConfiguration
-        );
+        $this->subject->setExtensionConfiguration($this->extensionConfiguration);
         // Restore devIPmask
         $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask'] = $savedIpMask;
     }
@@ -209,8 +207,8 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
     public function getConfigurationReturnsTestValue()
     {
         self::assertSame(
-                $this->subject->getExtensionConfiguration(),
-                $this->testConfiguration
+            $this->subject->getExtensionConfiguration(),
+            $this->extensionConfiguration
         );
     }
 
@@ -235,9 +233,9 @@ class LoggerTest extends \TYPO3\CMS\Core\Tests\UnitTestCase
         $this->subject->setIsLoggingEnabled(false);
 
         self::assertAttributeEquals(
-                false,
-                'isLoggingEnabled',
-                $this->subject
+            false,
+            'isLoggingEnabled',
+            $this->subject
         );
     }
 }