Vergelijk commits

...

19 Commits

Auteur SHA1 Bericht Datum
Daniel Seifert fae28866eb
improve code style 2024-02-02 11:39:13 +01:00
Daniel Seifert 1aac154bcb
improve code quality 2024-02-02 11:33:11 +01:00
Daniel Seifert e47817b95d
drop PHP 7 support, improve code 2024-02-02 10:59:40 +01:00
Daniel Seifert 2b6ab8f809
adjust CHANGELOG 2022-09-05 14:13:51 +02:00
Daniel Seifert c37768f2fa
fix empty default parameter argument error 2022-09-05 09:05:54 +02:00
Daniel Seifert 6327bfb06d
adjust version informations 2022-08-18 14:20:07 +02:00
Daniel Seifert a57605a729
improve code 2022-08-18 14:18:43 +02:00
Daniel Seifert 9b1a1b24ed
adjust version informations 2021-04-29 15:51:32 +02:00
Daniel Seifert b76507025e
prevent the use of not countable parameters in prepared statemant rendering 2021-04-29 15:49:20 +02:00
Daniel Seifert f6f9ddc7e7
adjust documentation 2021-03-02 15:50:39 +01:00
Daniel Seifert 8397868fdf
Merge remote-tracking branch 'remotes/origin/dev_traceInLog' 2021-03-02 15:34:11 +01:00
Daniel Seifert e6e772a2ce
fix missing static methods 2021-03-02 15:31:09 +01:00
Daniel Seifert d587fde2e8
change static methods to non-static methods for better testable code 2021-01-23 21:55:06 +01:00
Daniel Seifert c74789faef
add prepared statement query generator 2021-01-23 21:53:18 +01:00
Daniel Seifert 001eafec6c
fix non https url in composer.json 2020-06-08 10:14:56 +02:00
Daniel Seifert 1a339d4644
change line endings for easy patching 2020-05-25 09:48:12 +02:00
Daniel Seifert 66a842db84
change line endings for easy patching 2020-05-25 09:46:53 +02:00
Daniel Seifert 806de37cc9
add configurable FirePHP handler 2020-05-13 18:53:56 +02:00
Daniel Seifert 491ceeac5a
add missing autoload file item in composer.json 2020-05-01 22:26:26 +02:00
14 gewijzigde bestanden met toevoegingen van 516 en 185 verwijderingen

BIN
.gitattributes vendored Normal file

Binair bestand niet weergegeven.

13
.php-cs-fixer.php Normal file
Bestand weergeven

@ -0,0 +1,13 @@
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
;
$config = new PhpCsFixer\Config();
return $config->setRules([
'@PHP80Migration' => true,
'@PSR12' => true
])
->setFinder($finder)
;

Bestand weergeven

@ -4,33 +4,53 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [Unreleased](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.3.3...master)
--- ## [1.3.3](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.3.2...1.3.3) - 2022-09-05
### Fixed
- fix argument error if no parameter list was set in stopDebug
## [1.2.0] - 2020-04-30 ## [1.3.2](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.3.1...1.3.2) - 2022-07-18
### Fixed
- fix some code style issues
## [1.3.1](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.3.0...1.3.1) - 2021-04-29
### Fixed
- prevent the use of not countable parameters in prepared statemant rendering
## [1.3.0](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.2.2...1.3.0) - 2021-03-02
### Fixed
- fix missing static methods
### Added ### Added
- add configurable FirePHP handler
## [1.2.2](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.2.1...1.2.2) - 2021-01-23
### Changed
- change static methods to non-static methods for better testable code
- change line endings for easy patching
### Added
- add prepared statement generator
## [1.2.1](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.2.0...1.2.1) - 2020-05-01
### Fixed
- add missing autoload file item in composer.json
## [1.2.0](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.1.0...1.2.0) - 2020-04-30
### Added
- Format SQL query - Format SQL query
- Measures the SQL execution time - Measures the SQL execution time
--- ## [1.1.0](https://git.d3data.de/D3Public/oxid-sql-logger/compare/1.0.0...1.1.0) - 2019-09-20
## [1.1.0] - 2019-09-20
### Added ### Added
- add log message - add log message
- add position specifications of the calling source code - add position specifications of the calling source code
--- ## [1.0.0](https://git.d3data.de/D3Public/oxid-sql-logger/releases/tag/1.0.0) - 2019-07-21
## [1.0.0] - 2019-07-21
available in tumtum/oxid-sql-logger package only available in tumtum/oxid-sql-logger package only
### Added ### Added
- Global function `StartSQLLog` and `StopSQLLog` - Global function `StartSQLLog` and `StopSQLLog`
- Display SQL Querys on Browser or CLI - Display SQL Querys on Browser or CLI

Bestand weergeven

@ -30,6 +30,33 @@ CLI:
![Example CLI](https://raw.githubusercontent.com/d3datadevelopment/oxid-sql-logger/master/img/screenshot-cli.jpg) ![Example CLI](https://raw.githubusercontent.com/d3datadevelopment/oxid-sql-logger/master/img/screenshot-cli.jpg)
## Configuration
Add the sections to the config.inc.php of the shop if needed:
```php
$this->SqlLoggerGUIHandlers = [
\Monolog\Handler\BrowserConsoleHandler::class,
\D3\OxidSqlLogger\Handler\d3FirePHPHandler::class
];
```
Standard handlers are BrowserConsoleHandler and d3FirePHPHandler.
```php
$this->SqlLoggerCLIHandlers = [
...
];
```
Standard handler is StreamHandler.
```php
$this->d3FirePHPOptions = [
\D3\OxidSqlLogger\Handler\d3FirePHPHandler::ADD_TRACE
];
```
## Credits ## Credits
Many thanks to [Tobias Matthaiou](https://github.com/TumTum/oxid-sql-logger) for his inspiration. Many thanks to [Tobias Matthaiou](https://github.com/TumTum/oxid-sql-logger) for his inspiration.

Bestand weergeven

@ -3,14 +3,23 @@
"description": "Returns all SQL queries in the browser.", "description": "Returns all SQL queries in the browser.",
"type": "library", "type": "library",
"require": { "require": {
"php": "^8.0",
"monolog/monolog": "^1", "monolog/monolog": "^1",
"nilportugues/sql-query-formatter": "^1.2.2" "nilportugues/sql-query-formatter": "^1.2.2",
"firephp/firephp-core": "^0.5.3"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "~3.13.0",
"phpstan/phpstan": "^1.10"
}, },
"license": "GPL-3.0", "license": "GPL-3.0",
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"D3\\OxidSqlLogger\\": "./src" "D3\\OxidSqlLogger\\": "./src"
} },
"files": [
"./src/functions.php"
]
}, },
"authors": [ "authors": [
{ {
@ -20,7 +29,12 @@
{ {
"name": "D3 Data Development (Inh. Thomas Dartsch)", "name": "D3 Data Development (Inh. Thomas Dartsch)",
"email": "info@shopmodule.com", "email": "info@shopmodule.com",
"homepage": "http://www.d3data.de" "homepage": "https://www.d3data.de"
} }
] ],
"scripts": {
"php-cs-fixer": "./vendor/bin/php-cs-fixer fix --config=vendor/d3/oxid-sql-logger/.php-cs-fixer.php",
"phpstan": "./vendor/bin/phpstan --configuration=vendor/d3/oxid-sql-logger/phpstan.neon analyse"
}
} }

Bestand weergeven

@ -1,19 +1,23 @@
<?php <?php
declare(strict_types=1);
use OxidEsales\Eshop\Core\DatabaseProvider;
require __DIR__ . '/../../../../source/bootstrap.php'; require __DIR__ . '/../../../../source/bootstrap.php';
\D3StartSQLLog('Query for 100 items cheaper than 49,99'); D3StartSQLLog('Query for 100 items cheaper than 49,99');
$db = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC); $db = DatabaseProvider::getDb(DatabaseProvider::FETCH_MODE_ASSOC);
$list = $db->getAll('SELECT * '.PHP_EOL.'FROM oxarticles WHERE oxprice < ? LIMIT 100', [49.99]); $list = $db->getAll('SELECT * '.PHP_EOL.'FROM oxarticles WHERE oxprice < ? LIMIT 100', [49.99]);
\D3StopSQLLog(); D3StopSQLLog();
// or // or
\D3StartSQLLog(); D3StartSQLLog();
$db = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC); $db = DatabaseProvider::getDb(DatabaseProvider::FETCH_MODE_ASSOC);
$list = $db->getAll('SELECT * FROM oxarticles WHERE oxprice < ? LIMIT 100', [49.99]); $list = $db->getAll('SELECT * FROM oxarticles WHERE oxprice < ? LIMIT 100', [49.99]);
\D3StopSQLLog(); D3StopSQLLog();

14
phpstan.neon Normal file
Bestand weergeven

@ -0,0 +1,14 @@
parameters:
scanFiles:
- ../../oxid-esales/oxideshop-ce/source/bootstrap.php
- ../../oxid-esales/oxideshop-ce/source/oxfunctions.php
- ../../oxid-esales/oxideshop-ce/source/overridablefunctions.php
paths:
- ./src
- ./example
level: 9
phpVersion: 80300
checkMissingIterableValueType: false
treatPhpDocTypesAsCertain: false
featureToggles:
disableRuntimeReflectionProvider: true

Bestand weergeven

@ -0,0 +1,80 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\OxidSqlLogger\Extensions;
use D3\OxidSqlLogger\Handler\d3FirePHPHandler;
use D3\OxidSqlLogger\OxidSQLLogger;
use Doctrine\DBAL\Connection;
use Exception;
use FirePHP;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use OxidEsales\EshopCommunity\Core\Database\Adapter\Doctrine\Database;
class d3FirePHP extends FirePHP
{
/**
* Gets singleton instance of FirePHP
*
* @param boolean $autoCreate
* @return FirePHP
*/
public static function getInstance($autoCreate = false): FirePHP
{
if ($autoCreate === true && !self::$instance) {
self::init();
}
return self::$instance;
}
/**
* Creates FirePHP object and stores it for singleton access
*
* @return FirePHP
*/
public static function init(): FirePHP
{
return self::setInstance(new self());
}
public function __construct()
{
parent::__construct();
$this->ignoreClassInTraces(d3FirePHP::class);
$this->ignoreClassInTraces(d3FirePHPHandler::class);
$this->ignoreClassInTraces(Logger::class);
$this->ignoreClassInTraces(AbstractProcessingHandler::class);
$this->ignoreClassInTraces(OxidSQLLogger::class);
$this->ignoreClassInTraces(Connection::class);
$this->ignoreClassInTraces(Database::class);
}
/**
* Log a trace in the firebug console
*
* @see FirePHP::TRACE
* @param string $label
* @return bool
* @throws Exception
*/
public function trace($label): bool
{
return $this->fb($label, $label, FirePHP::TRACE, [
'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),
]);
}
}

Bestand weergeven

@ -0,0 +1,50 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\OxidSqlLogger\Handler;
use D3\OxidSqlLogger\Extensions\d3FirePHP;
use Exception;
use Monolog\Handler\AbstractProcessingHandler;
use OxidEsales\Eshop\Core\Registry;
class d3FirePHPHandler extends AbstractProcessingHandler
{
public const ADD_TRACE = 'addTrace';
/**
* @param array $record
*
* @throws Exception
*/
protected function write(array $record): void
{
$options = Registry::getConfig()->getConfigParam('d3FirePHPOptions');
$options = isset($options) && is_array($options) ? $options : [];
$fp = d3FirePHP::getInstance(true);
if (in_array(self::ADD_TRACE, $options)) {
$fp->group($record['message'], [ 'Collapsed' => true ]);
}
$fp->log($record['formatted'], $record['message']);
if (in_array(self::ADD_TRACE, $options)) {
$fp->trace('trace');
$fp->groupEnd();
}
}
}

Bestand weergeven

@ -5,21 +5,23 @@
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com> * @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
*/ */
declare(strict_types=1);
namespace D3\OxidSqlLogger; namespace D3\OxidSqlLogger;
use Monolog; use Monolog;
use Monolog\Logger;
use OxidEsales\Eshop\Core\Registry;
use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Formatter\OutputFormatterStyle;
/**
* Class Factory
*/
class LoggerFactory class LoggerFactory
{ {
/** /**
* @param $name * @param string $name
* @return Monolog\Logger *
* @return Logger
*/ */
public function create($name) public function create(string $name): Monolog\Logger
{ {
return new Monolog\Logger($name, $this->getHandlers(), $this->getProcessors()); return new Monolog\Logger($name, $this->getHandlers(), $this->getProcessors());
} }
@ -27,22 +29,49 @@ class LoggerFactory
/** /**
* @return array * @return array
*/ */
private function getHandlers() private function getHandlers(): array
{ {
$handlers = [];
if (PHP_SAPI == 'cli') { if (PHP_SAPI == 'cli') {
$handlers[] = $this->getStreamHandler(); $configuredHandlers = Registry::getConfig()->getConfigParam('SqlLoggerCLIHandlers');
$handlers = (isset($configuredHandlers) && is_iterable($configuredHandlers)) ?
$this->getInstancesFromHandlerList($configuredHandlers) :
[
$this->getStreamHandler(),
];
} else { } else {
$handlers[] = $this->getBrowserConsoleHandler(); $configuredHandlers = Registry::getConfig()->getConfigParam('SqlLoggerGUIHandlers');
$handlers[] = $this->getFirePHPHandler();
$handlers = (isset($configuredHandlers) && is_iterable($configuredHandlers)) ?
$this->getInstancesFromHandlerList($configuredHandlers) :
[
$this->getBrowserConsoleHandler(),
$this->getFirePHPHandler(),
];
} }
return $handlers; return $handlers;
} }
/**
* @param iterable $classNames
*
* @return array
*/
private function getInstancesFromHandlerList(iterable $classNames): array
{
return array_map(
function ($className) {
return new $className();
},
(array) $classNames
);
}
/** /**
* @return Monolog\Handler\StreamHandler * @return Monolog\Handler\StreamHandler
*/ */
private function getStreamHandler() private function getStreamHandler(): Monolog\Handler\StreamHandler
{ {
$streamHandler = new Monolog\Handler\StreamHandler('php://stderr'); $streamHandler = new Monolog\Handler\StreamHandler('php://stderr');
@ -52,7 +81,7 @@ class LoggerFactory
$context = (new OutputFormatterStyle('yellow'))->apply('%context%'); $context = (new OutputFormatterStyle('yellow'))->apply('%context%');
$newline = PHP_EOL . str_repeat(' ', 10); $newline = PHP_EOL . str_repeat(' ', 10);
$ttl_color = "$channel $level_name: $message {$newline} $context {$newline} %extra%" . PHP_EOL; $ttl_color = "$channel $level_name: $message $newline $context $newline %extra%" . PHP_EOL;
$streamHandler->setFormatter( $streamHandler->setFormatter(
new Monolog\Formatter\LineFormatter( new Monolog\Formatter\LineFormatter(
@ -69,7 +98,7 @@ class LoggerFactory
/** /**
* @return Monolog\Handler\BrowserConsoleHandler * @return Monolog\Handler\BrowserConsoleHandler
*/ */
private function getBrowserConsoleHandler() private function getBrowserConsoleHandler(): Monolog\Handler\BrowserConsoleHandler
{ {
return new Monolog\Handler\BrowserConsoleHandler(); return new Monolog\Handler\BrowserConsoleHandler();
} }
@ -77,7 +106,7 @@ class LoggerFactory
/** /**
* @return Monolog\Handler\FirePHPHandler * @return Monolog\Handler\FirePHPHandler
*/ */
private function getFirePHPHandler() private function getFirePHPHandler(): Monolog\Handler\FirePHPHandler
{ {
return new Monolog\Handler\FirePHPHandler(); return new Monolog\Handler\FirePHPHandler();
} }
@ -85,10 +114,17 @@ class LoggerFactory
/** /**
* @return array * @return array
*/ */
private function getProcessors() private function getProcessors(): array
{ {
return [ return [
new Monolog\Processor\IntrospectionProcessor(Monolog\Logger::DEBUG, ['D3\\OxidSqlLogger', 'Doctrine\\DBAL\\Connection', 'OxidEsales\\EshopCommunity\\Core\\Database\\Adapter\\Doctrine\\Database']), new Monolog\Processor\IntrospectionProcessor(
Monolog\Logger::DEBUG,
[
'D3\\OxidSqlLogger',
'Doctrine\\DBAL\\Connection',
'OxidEsales\\EshopCommunity\\Core\\Database\\Adapter\\Doctrine\\Database',
]
),
new Monolog\Processor\PsrLogMessageProcessor(), new Monolog\Processor\PsrLogMessageProcessor(),
]; ];
} }

Bestand weergeven

@ -5,48 +5,72 @@
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com> * @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
*/ */
declare(strict_types=1);
namespace D3\OxidSqlLogger; namespace D3\OxidSqlLogger;
use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Logging\SQLLogger;
use OxidEsales\Eshop\Core\Database\Adapter\Doctrine\Database;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\ConnectionProvider;
use OxidEsales\EshopCommunity\Internal\Framework\Database\ConnectionProviderInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/** class OxidEsalesDatabase extends Database
* Class OxidEsalesDatabase
* Is a depenction injection Helper Class
*/
class OxidEsalesDatabase extends \OxidEsales\Eshop\Core\Database\Adapter\Doctrine\Database
{ {
public static function enableLogger($message = null) /**
* @param string|null $message
*
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function d3EnableLogger(string $message = null): void
{ {
$trace = debug_backtrace((PHP_VERSION_ID < 50306) ? 2 : DEBUG_BACKTRACE_IGNORE_ARGS); $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC); $this->d3GetConfiguration()->setSQLLogger(
$dbalConfig = $database->getConnection()->getConfiguration();
$dbalConfig->setSQLLogger(
new OxidSQLLogger( new OxidSQLLogger(
isset($trace[1]['file']) ? $trace[1]['file'] : null, $trace[1]['file'] ?? '',
isset($trace[1]['line']) ? $trace[1]['line'] : null, array_key_exists('line', $trace[1]) ? (int) $trace[1]['line'] : 0,
isset($trace[2]['class']) ? $trace[2]['class'] : null, $trace[2]['class'] ?? '',
isset($trace[2]['function']) ? $trace[2]['function'] : null, $trace[2]['function'] ?? '',
$message $message
) )
); );
} }
/** /**
* @return OxidSQLLogger * @return SQLLogger|null
* @throws \OxidEsales\Eshop\Core\Exception\DatabaseConnectionException * @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/ */
public static function getLogger() public function d3GetLogger(): ?SQLLogger
{ {
$database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC); return $this->d3GetConfiguration()->getSQLLogger();
$dbalConfig = $database->getConnection()->getConfiguration();
return $dbalConfig->getSQLLogger();
} }
public static function disableLogger() /**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function d3DisableLogger(): void
{ {
$database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC); $this->d3GetConfiguration()->setSQLLogger();
$dbalConfig = $database->getConnection()->getConfiguration(); }
$dbalConfig->setSQLLogger(null);
/**
* @return Configuration
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected function d3GetConfiguration(): Configuration
{
/** @var ConnectionProvider $connectionProvider */
$connectionProvider = ContainerFactory::getInstance()->getContainer()
->get(ConnectionProviderInterface::class);
return $connectionProvider->get()->getConfiguration();
} }
} }

Bestand weergeven

@ -5,38 +5,39 @@
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com> * @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
*/ */
declare(strict_types=1);
namespace D3\OxidSqlLogger; namespace D3\OxidSqlLogger;
use D3\ModCfg\Application\Model\d3database;
use Doctrine\DBAL\Logging\SQLLogger; use Doctrine\DBAL\Logging\SQLLogger;
use Monolog; use Monolog;
use NilPortugues\Sql\QueryFormatter\Formatter; use NilPortugues\Sql\QueryFormatter\Formatter;
/**
* Class OxidSQLLogger
*/
class OxidSQLLogger implements SQLLogger class OxidSQLLogger implements SQLLogger
{ {
public $message; public string $message;
public $logStartingFile; public string $logStartingFile;
public $logStartingLine; public int $logStartingLine;
public $logStartingClass; public string $logStartingClass;
public $logStartingFunction; public string $logStartingFunction;
private SQLQuery|null $SQLQuery = null;
/** /**
* @var SQLQuery * @param string $file
* @param int $line
* @param string $class
* @param string $function
* @param string|null $message
*/ */
private $SQLQuery = null; public function __construct(string $file, int $line, string $class, string $function, string $message = null)
/**
* @inheritDoc
*/
public function __construct($file, $line, $class, $function, $message = null)
{ {
if (!Monolog\Registry::hasLogger('sql')) { if (!Monolog\Registry::hasLogger('sql')) {
Monolog\Registry::addLogger((new LoggerFactory())->create('sql')); Monolog\Registry::addLogger((new LoggerFactory())->create('sql'));
} }
$this->message = $message; $this->message = (string) $message;
$this->logStartingFile = $file; $this->logStartingFile = $file;
$this->logStartingLine = $line; $this->logStartingLine = $line;
$this->logStartingClass = $class; $this->logStartingClass = $class;
@ -44,34 +45,56 @@ class OxidSQLLogger implements SQLLogger
} }
/** /**
* @inheritDoc * @param string $sql
* @param array|null $params
* @param array|null $types
*/ */
public function startQuery($sql, array $params = null, array $types = null) public function startQuery($sql, ?array $params = null, ?array $types = null): void
{ {
if ($this->SQLQuery) { if ($this->SQLQuery) {
$this->SQLQuery->setCanceled(); $this->SQLQuery->setCanceled();
$this->stopQuery(); $this->stopQuery();
} }
$this->SQLQuery = (new SQLQuery()) ->setSql($sql) $this->getPreparedStatementQuery($sql, $params ?? [], $types ?? []);
->setParams($params)
->setTypes($types) $this->SQLQuery = (new SQLQuery())->setSql($sql)
->setLogStartingFile($this->logStartingFile) ->setParams($params)
->setLogStartingLine($this->logStartingLine) ->setTypes($types)
->setLogStartingClass($this->logStartingClass) ->setLogStartingFile($this->logStartingFile)
->setLogStartingFunction($this->logStartingFunction); ->setLogStartingLine($this->logStartingLine)
->setLogStartingClass($this->logStartingClass)
->setLogStartingFunction($this->logStartingFunction);
}
/**
* @param string $sql
* @param array $params
* @param array $types
*/
public function getPreparedStatementQuery(string &$sql, array $params = [], array $types = []): void
{
if (class_exists(d3database::class)
&& method_exists(d3database::class, 'getPreparedStatementQuery')
&& count($params)
&& ($query = d3database::getInstance()->getPreparedStatementQuery($sql, $params, $types))
&& strlen(trim($query))
) {
$sql = $query;
}
} }
/** /**
* @inheritDoc * @inheritDoc
*/ */
public function stopQuery() public function stopQuery(): void
{ {
if ($this->SQLQuery) { if ($this->SQLQuery) {
$formatter = new Formatter(); $formatter = new Formatter();
// @phpstan-ignore-next-line
Monolog\Registry::sql()->addDebug( Monolog\Registry::sql()->addDebug(
'['.$this->SQLQuery->getReadableElapsedTime().'] ' . ( $this->message ? $this->message : $this->SQLQuery->getSql() ), '['.$this->SQLQuery->getReadableElapsedTime().'] ' . ($this->message ?: $this->SQLQuery->getSql()),
[ [
'query' => $formatter->format($this->SQLQuery->getSql()), 'query' => $formatter->format($this->SQLQuery->getSql()),
'params' => $this->SQLQuery->getParams(), 'params' => $this->SQLQuery->getParams(),

Bestand weergeven

@ -1,54 +1,43 @@
<?php <?php
/** /**
* Autor: Tobias Matthaiou <developer@tobimat.eu> * @author Tobias Matthaiou <developer@tobimat.eu>
* Date: 2019-08-20 * @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* Time: 21:56
*/ */
declare(strict_types=1);
namespace D3\OxidSqlLogger; namespace D3\OxidSqlLogger;
/**
* Class SQLQuery
* @package tm\oxid\sql\logger
*/
class SQLQuery class SQLQuery
{ {
/** /**
* @var float|null * @var float
*/ */
private $start_time = null; private float $start_time;
/** /**
* @var float|null * @var float
*/ */
private $stop_time = null; private float $stop_time = 0.0;
/** /**
* @var string * @var string
*/ */
private $sql = ''; private string $sql = '';
/** private ?array $parameters = null;
* @var null
*/
private $params = null;
/** private ?array $parameterTypes = null;
* @var null
*/ private string $logStartingFile;
private $types = null;
private int $logStartingLine;
private $logStartingFile;
private string $logStartingClass;
private $logStartingLine;
private string $logStartingFunction;
private $logStartingClass;
private $logStartingFunction;
/**
* @inheritDoc
*/
public function __construct() public function __construct()
{ {
$this->start_time = microtime(true); $this->start_time = microtime(true);
@ -57,88 +46,88 @@ class SQLQuery
/** /**
* @return string * @return string
*/ */
public function getSql() public function getSql(): string
{ {
return $this->sql; return $this->sql;
} }
/** /**
* @param string $sql * @param string $sql
* @return SQLQuery * @return static
*/ */
public function setSql($sql) public function setSql(string $sql): static
{ {
$this->sql = $sql; $this->sql = $sql;
return $this; return $this;
} }
/** /**
* @return null * @return array|null
*/ */
public function getParams() public function getParams(): ?array
{ {
return $this->params; return $this->parameters;
} }
/** /**
* @param null $params * @param array|null $params
* @return SQLQuery *
* @return static
*/ */
public function setParams($params) public function setParams(array $params = null): static
{ {
$this->params = $params; $this->parameters = $params;
return $this; return $this;
} }
/** /**
* @return null * @return array|null
*/ */
public function getTypes() public function getTypes(): ?array
{ {
return $this->types; return $this->parameterTypes;
} }
/** /**
* @param null $types * @param array|null $types
* @return SQLQuery *
* @return static
*/ */
public function setTypes($types) public function setTypes(array $types = null): static
{ {
$this->types = $types; $this->parameterTypes = $types;
return $this; return $this;
} }
/** /**
* @return string * @return string
*/ */
public function getLogStartingFile() public function getLogStartingFile(): string
{ {
return $this->logStartingFile; return $this->logStartingFile;
} }
/** /**
* @param $file * @param string $file
* @return SQLQuery * @return static
*/ */
public function setLogStartingFile($file) public function setLogStartingFile(string $file): static
{ {
$this->logStartingFile = $file; $this->logStartingFile = $file;
return $this; return $this;
} }
/** public function getLogStartingLine(): int
* @return string
*/
public function getLogStartingLine()
{ {
return $this->logStartingLine; return $this->logStartingLine;
} }
/** /**
* @param $line * @param int $line
* @return SQLQuery *
* @return static
*/ */
public function setLogStartingLine($line) public function setLogStartingLine(int $line): static
{ {
$this->logStartingLine = $line; $this->logStartingLine = $line;
return $this; return $this;
@ -147,16 +136,17 @@ class SQLQuery
/** /**
* @return string * @return string
*/ */
public function getLogStartingClass() public function getLogStartingClass(): string
{ {
return $this->logStartingClass; return $this->logStartingClass;
} }
/** /**
* @param $classname * @param string $classname
* @return SQLQuery *
* @return static
*/ */
public function setLogStartingClass($classname) public function setLogStartingClass(string $classname): static
{ {
$this->logStartingClass = $classname; $this->logStartingClass = $classname;
return $this; return $this;
@ -165,16 +155,17 @@ class SQLQuery
/** /**
* @return string * @return string
*/ */
public function getLogStartingFunction() public function getLogStartingFunction(): string
{ {
return $this->logStartingFunction; return $this->logStartingFunction;
} }
/** /**
* @param $functionname * @param string $functionname
* @return SQLQuery *
* @return static
*/ */
public function setLogStartingFunction($functionname) public function setLogStartingFunction(string $functionname): static
{ {
$this->logStartingFunction = $functionname; $this->logStartingFunction = $functionname;
return $this; return $this;
@ -183,25 +174,25 @@ class SQLQuery
/** /**
* Statement was cancelled prematurely, an error was thrown. * Statement was cancelled prematurely, an error was thrown.
* *
* @return $this * @return static
*/ */
public function setCanceled() public function setCanceled(): static
{ {
$this->start_time = null; $this->start_time = 0.0;
return $this; return $this;
} }
/** /**
* Returns elapsed time * Return elapsed time
* @return float|string * @return float
*/ */
public function getElapsedTime() public function getElapsedTime(): float
{ {
if ($this->start_time === null) { if ($this->start_time === 0.0) {
return 'Statement canceled'; return 0.0;
} }
if ($this->stop_time === null) { if ($this->stop_time === 0.0) {
$end_time = microtime(true); $end_time = microtime(true);
$this->stop_time = $end_time - $this->start_time; $this->stop_time = $end_time - $this->start_time;
} }
@ -210,28 +201,25 @@ class SQLQuery
} }
/** /**
* Returns a human readable elapsed time * Returns a human-readable elapsed time
* *
* @return string * @return string
*/ */
public function getReadableElapsedTime() public function getReadableElapsedTime(): string
{ {
return $this->readableElapsedTime($this->getElapsedTime()); return $this->readableElapsedTime($this->getElapsedTime());
} }
/** /**
* Returns a human readable elapsed time * Returns a human-readable elapsed time
* *
* @param float $microtime * @param float $microtime
* @param string $format The format to display (printf format) * @param string $format The format to display (printf format)
* @param int $round
* @return string * @return string
*/ */
private function readableElapsedTime($microtime, $format = '%.3f%s', $round = 3) protected function readableElapsedTime(float $microtime, string $format = '%.3f%s', int $round = 3): string
{ {
if (is_string($microtime)) {
return $microtime;
}
if ($microtime >= 1) { if ($microtime >= 1) {
$unit = 's'; $unit = 's';
$time = round($microtime, $round); $time = round($microtime, $round);
@ -239,7 +227,7 @@ class SQLQuery
$unit = 'ms'; $unit = 'ms';
$time = round($microtime*1000); $time = round($microtime*1000);
$format = preg_replace('/(%.[\d]+f)/', '%d', $format); $format = (string) preg_replace('/(%.\d+f)/', '%d', $format);
} }
return sprintf($format, $time, $unit); return sprintf($format, $time, $unit);

Bestand weergeven

@ -5,10 +5,48 @@
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com> * @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
*/ */
function D3StartSQLLog($message = null) { declare(strict_types=1);
\D3\OxidSqlLogger\OxidEsalesDatabase::enableLogger($message);
use D3\OxidSqlLogger\OxidEsalesDatabase;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* @param string|null $message
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
function D3StartSQLLog(string $message = null): void
{
/** @var OxidEsalesDatabase $database */
$database = oxNew(OxidEsalesDatabase::class);
$database->d3EnableLogger($message);
} }
function D3StopSQLLog() { /**
\D3\OxidSqlLogger\OxidEsalesDatabase::disableLogger(); * @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
function D3StopSQLLog(): void
{
/** @var OxidEsalesDatabase $database */
$database = oxNew(OxidEsalesDatabase::class);
$database->d3DisableLogger();
}
/**
* @param string $message
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
function D3AddSQLLogItem(string $message): void
{
/** @var OxidEsalesDatabase $database */
$database = oxNew(OxidEsalesDatabase::class);
if ($logger = $database->d3GetLogger()) {
$logger->startQuery($message);
$logger->stopQuery();
}
} }