Merge pull request #10921 from nupplaphil/feat/httpclient_restructuring

Paradigm Restructuring Part 3 - Logger & HTTPClient
This commit is contained in:
Hypolite Petovan 2021-10-29 09:56:38 -04:00 committed by GitHub
commit 4242539059
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
53 changed files with 497 additions and 607 deletions

View file

@ -39,7 +39,7 @@ use Friendica\Model\Event;
use Friendica\Model\Photo;
use Friendica\Model\Post;
use Friendica\Model\Tag;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Object\Image;
use Friendica\Protocol\Activity;
use Friendica\Util\Images;
@ -1201,7 +1201,7 @@ class BBCode
$text = DI::cache()->get($cache_key);
if (is_null($text)) {
$curlResult = DI::httpClient()->head($match[1], [HTTPClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
$curlResult = DI::httpClient()->head($match[1], [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
if ($curlResult->isSuccess()) {
$mimetype = $curlResult->getHeader('Content-Type')[0] ?? '';
} else {
@ -1272,7 +1272,7 @@ class BBCode
return $text;
}
$curlResult = DI::httpClient()->head($match[1], [HTTPClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
$curlResult = DI::httpClient()->head($match[1], [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]);
if ($curlResult->isSuccess()) {
$mimetype = $curlResult->getHeader('Content-Type')[0] ?? '';
} else {

View file

@ -22,7 +22,7 @@
namespace Friendica\Core;
use Friendica\DI;
use Friendica\Util\Logger\WorkerLogger;
use Friendica\Core\Logger\Type\WorkerLogger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Logger\Exception;
use Throwable;
class LogLevelException extends \InvalidArgumentException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Logger\Exception;
use Throwable;
class LoggerArgumentException extends \InvalidArgumentException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Logger\Exception;
use Throwable;
class LoggerException extends \Exception
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -19,45 +19,45 @@
*
*/
namespace Friendica\Factory;
namespace Friendica\Core\Logger\Factory;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Logger;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core;
use Friendica\Core\Logger\Exception\LogLevelException;
use Friendica\Database\Database;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\FileSystem;
use Friendica\Util\Introspection;
use Friendica\Util\Logger\Monolog\DevelopHandler;
use Friendica\Util\Logger\Monolog\IntrospectionProcessor;
use Friendica\Util\Logger\ProfilerLogger;
use Friendica\Util\Logger\StreamLogger;
use Friendica\Util\Logger\SyslogLogger;
use Friendica\Util\Logger\VoidLogger;
use Friendica\Core\Logger\Util\Introspection;
use Friendica\Core\Logger\Type\Monolog\DevelopHandler;
use Friendica\Core\Logger\Type\Monolog\IntrospectionProcessor;
use Friendica\Core\Logger\Type\ProfilerLogger;
use Friendica\Core\Logger\Type\StreamLogger;
use Friendica\Core\Logger\Type\SyslogLogger;
use Friendica\Util\Profiler;
use Monolog;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\Log\NullLogger;
/**
* A logger factory
*
* Currently only Monolog is supported
*/
class LoggerFactory
class Logger
{
const DEV_CHANNEL = 'dev';
/**
* A list of classes, which shouldn't get logged
*
* @var array
* @var string[]
*/
private static $ignoreClassList = [
Logger::class,
Core\Logger::class,
Profiler::class,
'Friendica\\Util\\Logger',
'Friendica\\Core\\Logger\\Type',
];
/** @var string The log-channel (app, worker, ...) */
private $channel;
public function __construct(string $channel)
@ -72,20 +72,21 @@ class LoggerFactory
* @param IManageConfigValues $config The config
* @param Profiler $profiler The profiler of the app
* @param FileSystem $fileSystem FileSystem utils
* @param string|null $minLevel (optional) Override minimum Loglevel to log
*
* @return LoggerInterface The PSR-3 compliant logger instance
*/
public function create(Database $database, IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
public function create(Database $database, IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem, ?string $minLevel = null): LoggerInterface
{
if (empty($config->get('system', 'debugging', false))) {
$logger = new VoidLogger();
$logger = new NullLogger();
$database->setLogger($logger);
return $logger;
}
$introspection = new Introspection(self::$ignoreClassList);
$level = $config->get('system', 'loglevel');
$loglevel = self::mapLegacyConfigDebugLevel((string)$level);
$minLevel = $minLevel ?? $config->get('system', 'loglevel');
$loglevel = self::mapLegacyConfigDebugLevel((string)$minLevel);
switch ($config->get('system', 'logger_config', 'stream')) {
case 'monolog':
@ -106,7 +107,12 @@ class LoggerFactory
static::addStreamHandler($logger, $stream, $loglevel);
} catch (\Throwable $e) {
// No Logger ..
$logger = new VoidLogger();
try {
$logger = new SyslogLogger($this->channel, $introspection, $loglevel);
} catch (\Throwable $e) {
// No logger ...
$logger = new NullLogger();
}
}
}
break;
@ -114,9 +120,13 @@ class LoggerFactory
case 'syslog':
try {
$logger = new SyslogLogger($this->channel, $introspection, $loglevel);
} catch (LogLevelException $exception) {
// If there's a wrong config value for loglevel, try again with standard
$logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
$logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
} catch (\Throwable $e) {
// No logger ...
$logger = new VoidLogger();
$logger = new NullLogger();
}
break;
@ -127,12 +137,25 @@ class LoggerFactory
if (!is_file($stream) || is_writable($stream)) {
try {
$logger = new StreamLogger($this->channel, $stream, $introspection, $fileSystem, $loglevel);
} catch (LogLevelException $exception) {
// If there's a wrong config value for loglevel, try again with standard
$logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
$logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
} catch (\Throwable $t) {
// No logger ...
$logger = new VoidLogger();
$logger = new NullLogger();
}
} else {
$logger = new VoidLogger();
try {
$logger = new SyslogLogger($this->channel, $introspection, $loglevel);
} catch (LogLevelException $exception) {
// If there's a wrong config value for loglevel, try again with standard
$logger = $this->create($database, $config, $profiler, $fileSystem, LogLevel::NOTICE);
$logger->warning('Invalid loglevel set in config.', ['loglevel' => $loglevel]);
} catch (\Throwable $e) {
// No logger ...
$logger = new NullLogger();
}
}
break;
}
@ -161,8 +184,6 @@ class LoggerFactory
* @param FileSystem $fileSystem FileSystem utils
*
* @return LoggerInterface The PSR-3 compliant logger instance
*
* @throws InternalServerErrorException
* @throws \Exception
*/
public static function createDev(IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
@ -172,9 +193,8 @@ class LoggerFactory
$developerIp = $config->get('system', 'dlogip');
if ((!isset($developerIp) || !$debugging) &&
(!is_file($stream) || is_writable($stream))) {
$logger = new VoidLogger();
return $logger;
(!is_file($stream) || is_writable($stream))) {
return new NullLogger();
}
$loggerTimeZone = new \DateTimeZone('UTC');
@ -228,7 +248,7 @@ class LoggerFactory
*
* @return string the PSR-3 compliant level
*/
private static function mapLegacyConfigDebugLevel($level)
private static function mapLegacyConfigDebugLevel(string $level): string
{
switch ($level) {
// legacy WARNING
@ -263,9 +283,9 @@ class LoggerFactory
*
* @return void
*
* @throws \Exception in case of general failures
* @throws LoggerException
*/
public static function addStreamHandler($logger, $stream, $level = LogLevel::NOTICE)
public static function addStreamHandler(LoggerInterface $logger, $stream, string $level = LogLevel::NOTICE)
{
if ($logger instanceof Monolog\Logger) {
$loglevel = Monolog\Logger::toMonologLevel($level);
@ -275,19 +295,16 @@ class LoggerFactory
$loglevel = LogLevel::NOTICE;
}
$fileHandler = new Monolog\Handler\StreamHandler($stream, $loglevel);
try {
$fileHandler = new Monolog\Handler\StreamHandler($stream, $loglevel);
$formatter = new Monolog\Formatter\LineFormatter("%datetime% %channel% [%level_name%]: %message% %context% %extra%\n");
$fileHandler->setFormatter($formatter);
$formatter = new Monolog\Formatter\LineFormatter("%datetime% %channel% [%level_name%]: %message% %context% %extra%\n");
$fileHandler->setFormatter($formatter);
$logger->pushHandler($fileHandler);
}
}
public static function addVoidHandler($logger)
{
if ($logger instanceof Monolog\Logger) {
$logger->pushHandler(new Monolog\Handler\NullHandler());
$logger->pushHandler($fileHandler);
} catch (\Exception $exception) {
throw new LoggerException('Cannot create Monolog Logger.', $exception);
}
}
}
}

View file

@ -19,9 +19,10 @@
*
*/
namespace Friendica\Util\Logger;
namespace Friendica\Core\Logger\Type;
use Friendica\Util\Introspection;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core\Logger\Util\Introspection;
use Friendica\Util\Strings;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
@ -58,29 +59,35 @@ abstract class AbstractLogger implements LoggerInterface
/**
* Adds a new entry to the log
*
* @param int $level
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
abstract protected function addEntry($level, $message, $context = []);
abstract protected function addEntry($level, string $message, array $context = []);
/**
* @param string $channel The output channel
* @param Introspection $introspection The introspection of the current call
*
* @throws \Exception
* @throws LoggerException
*/
public function __construct($channel, Introspection $introspection)
public function __construct(string $channel, Introspection $introspection)
{
$this->channel = $channel;
$this->introspection = $introspection;
$this->logUid = Strings::getRandomHex(6);
try {
$this->logUid = Strings::getRandomHex(6);
} catch (\Exception $exception) {
throw new LoggerException('Cannot generate log Id', $exception);
}
}
/**
* Simple interpolation of PSR-3 compliant replacements ( variables between '{' and '}' )
*
* @see https://www.php-fig.org/psr/psr-3/#12-message
*
* @param string $message
@ -88,7 +95,7 @@ abstract class AbstractLogger implements LoggerInterface
*
* @return string the interpolated message
*/
protected function psrInterpolate($message, array $context = array())
protected function psrInterpolate(string $message, array $context = []): string
{
$replace = [];
foreach ($context as $key => $value) {
@ -104,7 +111,7 @@ abstract class AbstractLogger implements LoggerInterface
}
/**
* JSON Encodes an complete array including objects with "__toString()" methods
* JSON Encodes a complete array including objects with "__toString()" methods
*
* @param array $input an Input Array to encode
*
@ -128,7 +135,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function emergency($message, array $context = array())
public function emergency($message, array $context = [])
{
$this->addEntry(LogLevel::EMERGENCY, (string) $message, $context);
}
@ -136,7 +143,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function alert($message, array $context = array())
public function alert($message, array $context = [])
{
$this->addEntry(LogLevel::ALERT, (string) $message, $context);
}
@ -144,7 +151,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function critical($message, array $context = array())
public function critical($message, array $context = [])
{
$this->addEntry(LogLevel::CRITICAL, (string) $message, $context);
}
@ -152,7 +159,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function error($message, array $context = array())
public function error($message, array $context = [])
{
$this->addEntry(LogLevel::ERROR, (string) $message, $context);
}
@ -160,7 +167,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function warning($message, array $context = array())
public function warning($message, array $context = [])
{
$this->addEntry(LogLevel::WARNING, (string) $message, $context);
}
@ -168,7 +175,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function notice($message, array $context = array())
public function notice($message, array $context = [])
{
$this->addEntry(LogLevel::NOTICE, (string) $message, $context);
}
@ -176,7 +183,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function info($message, array $context = array())
public function info($message, array $context = [])
{
$this->addEntry(LogLevel::INFO, (string) $message, $context);
}
@ -184,7 +191,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function debug($message, array $context = array())
public function debug($message, array $context = [])
{
$this->addEntry(LogLevel::DEBUG, (string) $message, $context);
}
@ -192,7 +199,7 @@ abstract class AbstractLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
$this->addEntry($level, (string) $message, $context);
}

View file

@ -19,7 +19,7 @@
*
*/
namespace Friendica\Util\Logger\Monolog;
namespace Friendica\Core\Logger\Type\Monolog;
use Monolog\Handler;
use Monolog\Logger;
@ -42,7 +42,7 @@ class DevelopHandler extends Handler\AbstractHandler
* @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($developerIp, $level = Logger::DEBUG, $bubble = true)
public function __construct($developerIp, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
@ -52,15 +52,14 @@ class DevelopHandler extends Handler\AbstractHandler
/**
* {@inheritdoc}
*/
public function handle(array $record)
public function handle(array $record): bool
{
if (!$this->isHandling($record)) {
return false;
}
/// Just in case the remote IP is the same as the developer IP log the output
if (!is_null($this->developerIp) && $_SERVER['REMOTE_ADDR'] != $this->developerIp)
{
if (!is_null($this->developerIp) && $_SERVER['REMOTE_ADDR'] != $this->developerIp) {
return false;
}

View file

@ -19,9 +19,9 @@
*
*/
namespace Friendica\Util\Logger\Monolog;
namespace Friendica\Core\Logger\Type\Monolog;
use Friendica\Util\Introspection;
use Friendica\Core\Logger\Util\Introspection;
use Monolog\Logger;
use Monolog\Processor\ProcessorInterface;
@ -41,11 +41,11 @@ class IntrospectionProcessor implements ProcessorInterface
public function __construct(Introspection $introspection, $level = Logger::DEBUG)
{
$this->level = Logger::toMonologLevel($level);
$introspection->addClasses(array('Monolog\\'));
$introspection->addClasses(['Monolog\\']);
$this->introspection = $introspection;
}
public function __invoke(array $record)
public function __invoke(array $record): array
{
// return if the level is not high enough
if ($record['level'] < $this->level) {

View file

@ -19,9 +19,8 @@
*
*/
namespace Friendica\Util\Logger;
namespace Friendica\Core\Logger\Type;
use Friendica\Core\System;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
@ -50,14 +49,14 @@ class ProfilerLogger implements LoggerInterface
*/
public function __construct(LoggerInterface $logger, Profiler $profiler)
{
$this->logger = $logger;
$this->logger = $logger;
$this->profiler = $profiler;
}
/**
* {@inheritdoc}
*/
public function emergency($message, array $context = array())
public function emergency($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->emergency($message, $context);
@ -67,7 +66,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function alert($message, array $context = array())
public function alert($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->alert($message, $context);
@ -77,7 +76,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function critical($message, array $context = array())
public function critical($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->critical($message, $context);
@ -87,7 +86,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function error($message, array $context = array())
public function error($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->error($message, $context);
@ -97,7 +96,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function warning($message, array $context = array())
public function warning($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->warning($message, $context);
@ -107,7 +106,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function notice($message, array $context = array())
public function notice($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->notice($message, $context);
@ -117,7 +116,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function info($message, array $context = array())
public function info($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->info($message, $context);
@ -127,7 +126,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function debug($message, array $context = array())
public function debug($message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->debug($message, $context);
@ -137,7 +136,7 @@ class ProfilerLogger implements LoggerInterface
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
$this->profiler->startRecording('file');
$this->logger->log($level, $message, $context);

View file

@ -19,11 +19,14 @@
*
*/
namespace Friendica\Util\Logger;
namespace Friendica\Core\Logger\Type;
use Friendica\Core\Logger\Exception\LoggerArgumentException;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core\Logger\Exception\LogLevelException;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\FileSystem;
use Friendica\Util\Introspection;
use Friendica\Core\Logger\Util\Introspection;
use Psr\Log\LogLevel;
/**
@ -80,9 +83,10 @@ class StreamLogger extends AbstractLogger
* @param string|resource $stream The stream to write with this logger (either a file or a stream, i.e. stdout)
* @param string $level The minimum loglevel at which this logger will be triggered
*
* @throws \Exception
* @throws LoggerArgumentException
* @throws LogLevelException
*/
public function __construct($channel, $stream, Introspection $introspection, FileSystem $fileSystem, $level = LogLevel::DEBUG)
public function __construct($channel, $stream, Introspection $introspection, FileSystem $fileSystem, string $level = LogLevel::DEBUG)
{
$this->fileSystem = $fileSystem;
@ -93,14 +97,14 @@ class StreamLogger extends AbstractLogger
} elseif (is_string($stream)) {
$this->url = $stream;
} else {
throw new \InvalidArgumentException('A stream must either be a resource or a string.');
throw new LoggerArgumentException('A stream must either be a resource or a string.');
}
$this->pid = getmypid();
if (array_key_exists($level, $this->levelToInt)) {
$this->logLevel = $this->levelToInt[$level];
} else {
throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
}
$this->checkStream();
@ -118,16 +122,19 @@ class StreamLogger extends AbstractLogger
/**
* Adds a new entry to the log
*
* @param int $level
* @param mixed $level
* @param string $message
* @param array $context
* @param array $context
*
* @return void
*
* @throws LoggerException
* @throws LogLevelException
*/
protected function addEntry($level, $message, $context = [])
protected function addEntry($level, string $message, array $context = [])
{
if (!array_key_exists($level, $this->levelToInt)) {
throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
}
$logLevel = $this->levelToInt[$level];
@ -145,19 +152,24 @@ class StreamLogger extends AbstractLogger
/**
* Formats a log record for the syslog output
*
* @param int $level The loglevel/priority
* @param mixed $level The loglevel/priority
* @param string $message The message
* @param array $context The context of this call
*
* @return string the formatted syslog output
*
* @throws LoggerException
*/
private function formatLog($level, $message, $context = [])
private function formatLog($level, string $message, array $context = []): string
{
$record = $this->introspection->getRecord();
$record = array_merge($record, ['uid' => $this->logUid, 'process_id' => $this->pid]);
$logMessage = '';
$logMessage .= DateTimeFormat::utcNow(DateTimeFormat::ATOM) . ' ';
try {
$logMessage = DateTimeFormat::utcNow(DateTimeFormat::ATOM) . ' ';
} catch (\Exception $exception) {
throw new LoggerException('Cannot get current datetime.', $exception);
}
$logMessage .= $this->channel . ' ';
$logMessage .= '[' . strtoupper($level) . ']: ';
$logMessage .= $this->psrInterpolate($message, $context) . ' ';
@ -168,6 +180,12 @@ class StreamLogger extends AbstractLogger
return $logMessage;
}
/**
* Checks the current stream
*
* @throws LoggerException
* @throws LoggerArgumentException
*/
private function checkStream()
{
if (is_resource($this->stream)) {
@ -175,9 +193,13 @@ class StreamLogger extends AbstractLogger
}
if (empty($this->url)) {
throw new \LogicException('Missing stream URL.');
throw new LoggerArgumentException('Missing stream URL.');
}
$this->stream = $this->fileSystem->createStream($this->url);
try {
$this->stream = $this->fileSystem->createStream($this->url);
} catch (\UnexpectedValueException $exception) {
throw new LoggerException('Cannot create stream.', $exception);
}
}
}

View file

@ -19,10 +19,11 @@
*
*/
namespace Friendica\Util\Logger;
namespace Friendica\Core\Logger\Type;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\Introspection;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core\Logger\Exception\LogLevelException;
use Friendica\Core\Logger\Util\Introspection;
use Psr\Log\LogLevel;
/**
@ -97,27 +98,29 @@ class SyslogLogger extends AbstractLogger
* @param int $logOpts Indicates what logging options will be used when generating a log message
* @param int $logFacility Used to specify what type of program is logging the message
*
* @throws \Exception
* @throws LogLevelException
* @throws LoggerException
*/
public function __construct($channel, Introspection $introspection, $level = LogLevel::NOTICE, $logOpts = LOG_PID, $logFacility = LOG_USER)
public function __construct($channel, Introspection $introspection, string $level = LogLevel::NOTICE, int $logOpts = LOG_PID, int $logFacility = LOG_USER)
{
parent::__construct($channel, $introspection);
$this->logOpts = $logOpts;
$this->logOpts = $logOpts;
$this->logFacility = $logFacility;
$this->logLevel = $this->mapLevelToPriority($level);
$this->introspection->addClasses(array(self::class));
$this->logLevel = $this->mapLevelToPriority($level);
$this->introspection->addClasses([self::class]);
}
/**
* Adds a new entry to the syslog
*
* @param int $level
* @param mixed $level
* @param string $message
* @param array $context
*
* @throws InternalServerErrorException if the syslog isn't available
* @throws LogLevelException in case the level isn't valid
* @throws LoggerException In case the syslog cannot be opened for writing
*/
protected function addEntry($level, $message, $context = [])
protected function addEntry($level, string $message, array $context = [])
{
$logLevel = $this->mapLevelToPriority($level);
@ -136,12 +139,12 @@ class SyslogLogger extends AbstractLogger
*
* @return int The SysLog priority
*
* @throws \Psr\Log\InvalidArgumentException If the loglevel isn't valid
* @throws LogLevelException If the loglevel isn't valid
*/
public function mapLevelToPriority($level)
public function mapLevelToPriority(string $level): int
{
if (!array_key_exists($level, $this->logLevels)) {
throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level));
throw new LogLevelException(sprintf('The level "%s" is not valid.', $level));
}
return $this->logLevels[$level];
@ -157,21 +160,22 @@ class SyslogLogger extends AbstractLogger
/**
* Writes a message to the syslog
*
* @see http://php.net/manual/en/function.syslog.php#refsect1-function.syslog-parameters
*
* @param int $priority The Priority
* @param string $message The message of the log
*
* @throws InternalServerErrorException if syslog cannot be used
* @throws LoggerException In case the syslog cannot be opened/written
*/
private function write($priority, $message)
private function write(int $priority, string $message)
{
set_error_handler([$this, 'customErrorHandler']);
$opened = openlog(self::IDENT, $this->logOpts, $this->logFacility);
restore_error_handler();
if (!$opened) {
throw new \UnexpectedValueException(sprintf('Can\'t open syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
throw new LoggerException(sprintf('Can\'t open syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
}
$this->syslogWrapper($priority, $message);
@ -186,13 +190,12 @@ class SyslogLogger extends AbstractLogger
*
* @return string the formatted syslog output
*/
private function formatLog($level, $message, $context = [])
private function formatLog(int $level, string $message, array $context = []): string
{
$record = $this->introspection->getRecord();
$record = array_merge($record, ['uid' => $this->logUid]);
$logMessage = '';
$logMessage .= $this->channel . ' ';
$logMessage = $this->channel . ' ';
$logMessage .= '[' . $this->logToString[$level] . ']: ';
$logMessage .= $this->psrInterpolate($message, $context) . ' ';
$logMessage .= $this->jsonEncodeArray($context) . ' - ';
@ -211,15 +214,17 @@ class SyslogLogger extends AbstractLogger
*
* @param int $level The syslog priority
* @param string $entry The message to send to the syslog function
*
* @throws LoggerException
*/
protected function syslogWrapper($level, $entry)
protected function syslogWrapper(int $level, string $entry)
{
set_error_handler([$this, 'customErrorHandler']);
$written = syslog($level, $entry);
restore_error_handler();
if (!$written) {
throw new \UnexpectedValueException(sprintf('Can\'t write into syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
throw new LoggerException(sprintf('Can\'t write into syslog for ident "%s" and facility "%s": ' . $this->errorMessage, $this->channel, $this->logFacility));
}
}
}

View file

@ -19,13 +19,14 @@
*
*/
namespace Friendica\Util\Logger;
namespace Friendica\Core\Logger\Type;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Util\Strings;
use Psr\Log\LoggerInterface;
/**
* A Logger for specific worker tasks, which adds an additional woker-id to it.
* A Logger for specific worker tasks, which adds a worker id to it.
* Uses the decorator pattern (https://en.wikipedia.org/wiki/Decorator_pattern)
*/
class WorkerLogger implements LoggerInterface
@ -46,15 +47,21 @@ class WorkerLogger implements LoggerInterface
private $functionName;
/**
* @param LoggerInterface $logger The logger for worker entries
* @param string $functionName The current function name of the worker
* @param int $idLength The length of the generated worker ID
* @param LoggerInterface $logger The logger for worker entries
* @param string $functionName The current function name of the worker
* @param int $idLength The length of the generated worker ID
*
* @throws LoggerException
*/
public function __construct(LoggerInterface $logger, $functionName = '', $idLength = 7)
public function __construct(LoggerInterface $logger, string $functionName = '', int $idLength = 7)
{
$this->logger = $logger;
$this->logger = $logger;
$this->functionName = $functionName;
$this->workerId = Strings::getRandomHex($idLength);
try {
$this->workerId = Strings::getRandomHex($idLength);
} catch (\Exception $exception) {
throw new LoggerException('Cannot generate random Hex.', $exception);
}
}
/**
@ -74,7 +81,7 @@ class WorkerLogger implements LoggerInterface
*/
private function addContext(array &$context)
{
$context['worker_id'] = $this->workerId;
$context['worker_id'] = $this->workerId;
$context['worker_cmd'] = $this->functionName;
}
@ -83,7 +90,7 @@ class WorkerLogger implements LoggerInterface
*
* @return string
*/
public function getWorkerId()
public function getWorkerId(): string
{
return $this->workerId;
}

View file

@ -19,15 +19,17 @@
*
*/
namespace Friendica\Util;
namespace Friendica\Core\Logger\Util;
/**
* Get Introspection information about the current call
*/
class Introspection
{
/** @var int */
private $skipStackFramesCount;
/** @var string[] */
private $skipClassesPartials;
private $skipFunctions = [
@ -36,10 +38,10 @@ class Introspection
];
/**
* @param array $skipClassesPartials An array of classes to skip during logging
* @param int $skipStackFramesCount If the logger should use information from other hierarchy levels of the call
* @param string[] $skipClassesPartials An array of classes to skip during logging
* @param int $skipStackFramesCount If the logger should use information from other hierarchy levels of the call
*/
public function __construct($skipClassesPartials = array(), $skipStackFramesCount = 0)
public function __construct(array $skipClassesPartials = [], int $skipStackFramesCount = 0)
{
$this->skipClassesPartials = $skipClassesPartials;
$this->skipStackFramesCount = $skipStackFramesCount;
@ -47,6 +49,7 @@ class Introspection
/**
* Adds new classes to get skipped
*
* @param array $classNames
*/
public function addClasses(array $classNames)
@ -59,7 +62,7 @@ class Introspection
*
* @return array
*/
public function getRecord()
public function getRecord(): array
{
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
@ -73,8 +76,8 @@ class Introspection
return [
'file' => isset($trace[$i - 1]['file']) ? basename($trace[$i - 1]['file']) : null,
'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null,
'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
'line' => $trace[$i - 1]['line'] ?? null,
'function' => $trace[$i]['function'] ?? null,
];
}
@ -86,7 +89,7 @@ class Introspection
*
* @return bool True if the class or function should get skipped, otherwise false
*/
private function isTraceClassOrSkippedFunction(array $trace, $index)
private function isTraceClassOrSkippedFunction(array $trace, int $index): bool
{
if (!isset($trace[$index])) {
return false;

View file

@ -24,7 +24,7 @@ namespace Friendica\Core;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Object\Search\ContactResult;
use Friendica\Object\Search\ResultList;
use Friendica\Util\Network;
@ -228,7 +228,7 @@ class Search
$return = Contact::searchByName($search, $mode);
} else {
$p = $page > 1 ? 'p=' . $page : '';
$curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), [HTTPClientOptions::ACCEPT_CONTENT => ['application/json']]);
$curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), [HttpClientOptions::ACCEPT_CONTENT => ['application/json']]);
if ($curlResult->isSuccess()) {
$searchResult = json_decode($curlResult->getBody(), true);
if (!empty($searchResult['profiles'])) {

View file

@ -243,7 +243,7 @@ abstract class DI
*/
public static function workerLogger()
{
return self::$dice->create(Util\Logger\WorkerLogger::class);
return self::$dice->create(Core\Logger\Type\WorkerLogger::class);
}
//
@ -415,11 +415,11 @@ abstract class DI
//
/**
* @return Network\IHTTPClient
* @return Network\HTTPClient\Capability\ICanSendHttpRequests
*/
public static function httpClient()
{
return self::$dice->create(Network\IHTTPClient::class);
return self::$dice->create(Network\HTTPClient\Capability\ICanSendHttpRequests::class);
}
//

View file

@ -32,8 +32,8 @@ use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Module\Register;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\IHTTPResult;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use Friendica\Protocol\Relay;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
@ -315,7 +315,7 @@ class GServer
// When a nodeinfo is present, we don't need to dig further
$xrd_timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
$curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if ($curlResult->isTimeout()) {
self::setFailure($url);
return false;
@ -323,7 +323,7 @@ class GServer
// On a redirect follow the new host but mark the old one as failure
if ($curlResult->isSuccess() && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
self::setFailure($url);
@ -359,7 +359,7 @@ class GServer
$basedata = ['detection-method' => self::DETECT_MANUAL];
}
$curlResult = DI::httpClient()->get($baseurl, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
$curlResult = DI::httpClient()->get($baseurl, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if ($curlResult->isSuccess()) {
if ((parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
@ -383,7 +383,7 @@ class GServer
// When the base path doesn't seem to contain a social network we try the complete path.
// Most detectable system have to be installed in the root directory.
// We checked the base to avoid false positives.
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if ($curlResult->isSuccess()) {
$urldata = self::analyseRootHeader($curlResult, $serverdata);
$urldata = self::analyseRootBody($curlResult, $urldata, $url);
@ -672,13 +672,13 @@ class GServer
/**
* Detect server type by using the nodeinfo data
*
* @param string $url address of the server
* @param IHTTPResult $httpResult
* @param string $url address of the server
* @param ICanHandleHttpResponses $httpResult
*
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function fetchNodeinfo(string $url, IHTTPResult $httpResult)
private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
{
if (!$httpResult->isSuccess()) {
return [];
@ -959,7 +959,7 @@ class GServer
private static function validHostMeta(string $url)
{
$xrd_timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
$curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if (!$curlResult->isSuccess()) {
return false;
}
@ -1725,7 +1725,7 @@ class GServer
if (!empty($accesstoken)) {
$api = 'https://instances.social/api/1.0/instances/list?count=0';
$curlResult = DI::httpClient()->get($api, [HTTPClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
$curlResult = DI::httpClient()->get($api, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
if ($curlResult->isSuccess()) {
$servers = json_decode($curlResult->getBody(), true);

View file

@ -26,7 +26,7 @@ use Friendica\Core\System;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\Proxy;
/**
@ -100,7 +100,7 @@ class Link
{
$timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->head($url, [HTTPClientOptions::TIMEOUT => $timeout]);
$curlResult = DI::httpClient()->head($url, [HttpClientOptions::TIMEOUT => $timeout]);
if ($curlResult->isSuccess()) {
if (empty($media['mimetype'])) {
return $curlResult->getHeader('Content-Type')[0] ?? '';

View file

@ -30,7 +30,7 @@ use Friendica\DI;
use Friendica\Model\Item;
use Friendica\Model\Photo;
use Friendica\Model\Post;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\Images;
use Friendica\Util\Network;
use Friendica\Util\ParseUrl;
@ -168,7 +168,7 @@ class Media
// Fetch the mimetype or size if missing.
if (empty($media['mimetype']) || empty($media['size'])) {
$timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->head($media['url'], [HTTPClientOptions::TIMEOUT => $timeout]);
$curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
if ($curlResult->isSuccess()) {
if (empty($media['mimetype'])) {
$media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';

View file

@ -28,7 +28,7 @@ use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\HTTPSignature;
use Friendica\Util\Strings;
@ -102,7 +102,7 @@ class Magic extends BaseModule
);
// Try to get an authentication token from the other instance.
$curlResult = DI::httpClient()->get($basepath . '/owa', [HTTPClientOptions::HEADERS => $header]);
$curlResult = DI::httpClient()->get($basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
if ($curlResult->isSuccess()) {
$j = json_decode($curlResult->getBody(), true);

View file

@ -1,13 +1,13 @@
<?php
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Capability;
use Psr\Http\Message\MessageInterface;
/**
* Temporary class to map Friendica used variables based on PSR-7 HTTPResponse
*/
interface IHTTPResult
interface ICanHandleHttpResponses
{
/**
* Gets the Return Code
@ -25,13 +25,14 @@ interface IHTTPResult
/**
* Returns the headers
* @see MessageInterface::getHeader()
*
* @param string $header optional header field. Return all fields if empty
*
* @return string[] the headers or the specified content of the header variable
*@see MessageInterface::getHeader()
*
*/
public function getHeader($header);
public function getHeader(string $header);
/**
* Returns all headers

View file

@ -19,14 +19,14 @@
*
*/
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Capability;
use GuzzleHttp\Exception\TransferException;
/**
* Interface for calling HTTP requests and returning their responses
*/
interface IHTTPClient
interface ICanSendHttpRequests
{
/**
* Fetches the content of an URL
@ -41,7 +41,7 @@ interface IHTTPClient
*
* @return string The fetched content
*/
public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '');
public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): string;
/**
* Fetches the whole response of an URL.
@ -54,12 +54,12 @@ interface IHTTPClient
* @param string $accept_content supply Accept: header with 'accept_content' as the value
* @param string $cookiejar Path to cookie jar file
*
* @return IHTTPResult With all relevant information, 'body' contains the actual fetched content.
* @return ICanHandleHttpResponses With all relevant information, 'body' contains the actual fetched content.
*/
public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '');
public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): ICanHandleHttpResponses;
/**
* Send a HEAD to an URL.
* Send a HEAD to a URL.
*
* @param string $url URL to fetch
* @param array $opts (optional parameters) associative array with:
@ -68,9 +68,9 @@ interface IHTTPClient
* 'cookiejar' => path to cookie jar file
* 'header' => header array
*
* @return CurlResult
* @return ICanHandleHttpResponses
*/
public function head(string $url, array $opts = []);
public function head(string $url, array $opts = []): ICanHandleHttpResponses;
/**
* Send a GET to an URL.
@ -83,9 +83,9 @@ interface IHTTPClient
* 'header' => header array
* 'content_length' => int maximum File content length
*
* @return IHTTPResult
* @return ICanHandleHttpResponses
*/
public function get(string $url, array $opts = []);
public function get(string $url, array $opts = []): ICanHandleHttpResponses;
/**
* Sends a HTTP request to a given url
@ -101,9 +101,9 @@ interface IHTTPClient
* 'content_length' => int maximum File content length
* 'auth' => array authentication settings
*
* @return IHTTPResult
* @return ICanHandleHttpResponses
*/
public function request(string $method, string $url, array $opts = []);
public function request(string $method, string $url, array $opts = []): ICanHandleHttpResponses;
/**
* Send POST request to an URL
@ -113,9 +113,9 @@ interface IHTTPClient
* @param array $headers HTTP headers
* @param int $timeout The timeout in seconds, default system config value or 60 seconds
*
* @return IHTTPResult The content
* @return ICanHandleHttpResponses The content
*/
public function post(string $url, $params, array $headers = [], int $timeout = 0);
public function post(string $url, $params, array $headers = [], int $timeout = 0): ICanHandleHttpResponses;
/**
* Returns the original URL of the provided URL
@ -129,5 +129,5 @@ interface IHTTPClient
*
* @throws TransferException In case there's an error during the resolving
*/
public function finalUrl(string $url);
public function finalUrl(string $url): string;
}

View file

@ -19,9 +19,14 @@
*
*/
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Client;
use Friendica\Core\System;
use Friendica\Network\HTTPClient\Response\CurlResult;
use Friendica\Network\HTTPClient\Response\GuzzleResponse;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\Network;
use Friendica\Util\Profiler;
use GuzzleHttp\Client;
@ -37,7 +42,7 @@ use Psr\Log\LoggerInterface;
/**
* Performs HTTP requests to a given URL
*/
class HTTPClient implements IHTTPClient
class HttpClient implements ICanSendHttpRequests
{
/** @var LoggerInterface */
private $logger;
@ -59,7 +64,7 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function request(string $method, string $url, array $opts = []): IHTTPResult
public function request(string $method, string $url, array $opts = []): ICanHandleHttpResponses
{
$this->profiler->startRecording('network');
$this->logger->debug('Request start.', ['url' => $url, 'method' => $method]);
@ -95,43 +100,43 @@ class HTTPClient implements IHTTPClient
$conf = [];
if (!empty($opts[HTTPClientOptions::COOKIEJAR])) {
$jar = new FileCookieJar($opts[HTTPClientOptions::COOKIEJAR]);
if (!empty($opts[HttpClientOptions::COOKIEJAR])) {
$jar = new FileCookieJar($opts[HttpClientOptions::COOKIEJAR]);
$conf[RequestOptions::COOKIES] = $jar;
}
$headers = [];
if (!empty($opts[HTTPClientOptions::ACCEPT_CONTENT])) {
$headers['Accept'] = $opts[HTTPClientOptions::ACCEPT_CONTENT];
if (!empty($opts[HttpClientOptions::ACCEPT_CONTENT])) {
$headers['Accept'] = $opts[HttpClientOptions::ACCEPT_CONTENT];
}
if (!empty($opts[HTTPClientOptions::LEGACY_HEADER])) {
if (!empty($opts[HttpClientOptions::LEGACY_HEADER])) {
$this->logger->notice('Wrong option \'headers\' used.');
$headers = array_merge($opts[HTTPClientOptions::LEGACY_HEADER], $headers);
$headers = array_merge($opts[HttpClientOptions::LEGACY_HEADER], $headers);
}
if (!empty($opts[HTTPClientOptions::HEADERS])) {
$headers = array_merge($opts[HTTPClientOptions::HEADERS], $headers);
if (!empty($opts[HttpClientOptions::HEADERS])) {
$headers = array_merge($opts[HttpClientOptions::HEADERS], $headers);
}
$conf[RequestOptions::HEADERS] = array_merge($this->client->getConfig(RequestOptions::HEADERS), $headers);
if (!empty($opts[HTTPClientOptions::TIMEOUT])) {
$conf[RequestOptions::TIMEOUT] = $opts[HTTPClientOptions::TIMEOUT];
if (!empty($opts[HttpClientOptions::TIMEOUT])) {
$conf[RequestOptions::TIMEOUT] = $opts[HttpClientOptions::TIMEOUT];
}
if (!empty($opts[HTTPClientOptions::BODY])) {
$conf[RequestOptions::BODY] = $opts[HTTPClientOptions::BODY];
if (!empty($opts[HttpClientOptions::BODY])) {
$conf[RequestOptions::BODY] = $opts[HttpClientOptions::BODY];
}
if (!empty($opts[HTTPClientOptions::AUTH])) {
$conf[RequestOptions::AUTH] = $opts[HTTPClientOptions::AUTH];
if (!empty($opts[HttpClientOptions::AUTH])) {
$conf[RequestOptions::AUTH] = $opts[HttpClientOptions::AUTH];
}
$conf[RequestOptions::ON_HEADERS] = function (ResponseInterface $response) use ($opts) {
if (!empty($opts[HTTPClientOptions::CONTENT_LENGTH]) &&
(int)$response->getHeaderLine('Content-Length') > $opts[HTTPClientOptions::CONTENT_LENGTH]) {
if (!empty($opts[HttpClientOptions::CONTENT_LENGTH]) &&
(int)$response->getHeaderLine('Content-Length') > $opts[HttpClientOptions::CONTENT_LENGTH]) {
throw new TransferException('The file is too big!');
}
};
@ -159,7 +164,7 @@ class HTTPClient implements IHTTPClient
/** {@inheritDoc}
*/
public function head(string $url, array $opts = []): IHTTPResult
public function head(string $url, array $opts = []): ICanHandleHttpResponses
{
return $this->request('head', $url, $opts);
}
@ -167,7 +172,7 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function get(string $url, array $opts = []): IHTTPResult
public function get(string $url, array $opts = []): ICanHandleHttpResponses
{
return $this->request('get', $url, $opts);
}
@ -175,18 +180,18 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function post(string $url, $params, array $headers = [], int $timeout = 0): IHTTPResult
public function post(string $url, $params, array $headers = [], int $timeout = 0): ICanHandleHttpResponses
{
$opts = [];
$opts[HTTPClientOptions::BODY] = $params;
$opts[HttpClientOptions::BODY] = $params;
if (!empty($headers)) {
$opts[HTTPClientOptions::HEADERS] = $headers;
$opts[HttpClientOptions::HEADERS] = $headers;
}
if (!empty($timeout)) {
$opts[HTTPClientOptions::TIMEOUT] = $timeout;
$opts[HttpClientOptions::TIMEOUT] = $timeout;
}
return $this->request('post', $url, $opts);
@ -195,7 +200,7 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function finalUrl(string $url)
public function finalUrl(string $url): string
{
$this->profiler->startRecording('network');
@ -229,7 +234,7 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): string
{
$ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar);
@ -239,7 +244,7 @@ class HTTPClient implements IHTTPClient
/**
* {@inheritDoc}
*/
public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '')
public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = ''): ICanHandleHttpResponses
{
return $this->get(
$url,

View file

@ -1,13 +1,13 @@
<?php
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Client;
use GuzzleHttp\RequestOptions;
/**
* This class contains a list of possible HTTPClient request options.
*/
class HTTPClientOptions
class HttpClientOptions
{
/**
* accept_content: (array) supply Accept: header with 'accept_content' as the value

View file

@ -1,15 +1,15 @@
<?php
namespace Friendica\Factory;
namespace Friendica\Network\HTTPClient\Factory;
use Friendica\App;
use Friendica\BaseFactory;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Network\HTTPClient;
use Friendica\Network\IHTTPClient;
use Friendica\Network\HTTPClient\Client;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Util\Profiler;
use Friendica\Util\Strings;
use GuzzleHttp\Client;
use GuzzleHttp;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\RequestOptions;
use mattwright\URLResolver;
@ -18,9 +18,9 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../../static/dbstructure.config.php';
require_once __DIR__ . '/../../../../static/dbstructure.config.php';
class HTTPClientFactory extends BaseFactory
class HttpClient extends BaseFactory
{
/** @var IManageConfigValues */
private $config;
@ -42,17 +42,17 @@ class HTTPClientFactory extends BaseFactory
*
* @param HandlerStack|null $handlerStack (optional) A handler replacement (just usefull at test environments)
*
* @return IHTTPClient
* @return ICanSendHttpRequests
*/
public function createClient(HandlerStack $handlerStack = null): IHTTPClient
public function createClient(HandlerStack $handlerStack = null): ICanSendHttpRequests
{
$proxy = $this->config->get('system', 'proxy');
if (!empty($proxy)) {
$proxyuser = $this->config->get('system', 'proxyuser');
$proxyUser = $this->config->get('system', 'proxyuser');
if (!empty($proxyuser)) {
$proxy = $proxyuser . '@' . $proxy;
if (!empty($proxyUser)) {
$proxy = $proxyUser . '@' . $proxy;
}
}
@ -72,7 +72,7 @@ class HTTPClientFactory extends BaseFactory
DB_UPDATE_VERSION . '; ' .
$this->baseUrl->get();
$guzzle = new Client([
$guzzle = new GuzzleHttp\Client([
RequestOptions::ALLOW_REDIRECTS => [
'max' => 8,
'on_redirect' => $onRedirect,
@ -88,7 +88,7 @@ class HTTPClientFactory extends BaseFactory
RequestOptions::FORCE_IP_RESOLVE => ($this->config->get('system', 'ipv4_resolve') ? 'v4' : null),
RequestOptions::CONNECT_TIMEOUT => 10,
RequestOptions::TIMEOUT => $this->config->get('system', 'curl_timeout', 60),
// by default we will allow self-signed certs
// by default, we will allow self-signed certs,
// but it can be overridden
RequestOptions::VERIFY => (bool)$this->config->get('system', 'verifyssl'),
RequestOptions::PROXY => $proxy,
@ -108,6 +108,6 @@ class HTTPClientFactory extends BaseFactory
// Some websites test the browser for cookie support, so this enhances results.
$resolver->setCookieJar(get_temppath() .'/resolver-cookie-' . Strings::getRandomName(10));
return new HTTPClient($logger, $this->profiler, $guzzle, $resolver);
return new Client\HttpClient($logger, $this->profiler, $guzzle, $resolver);
}
}

View file

@ -19,17 +19,17 @@
*
*/
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Response;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\Network;
/**
* A content class for Curl call results
*/
class CurlResult implements IHTTPResult
class CurlResult implements ICanHandleHttpResponses
{
/**
* @var int HTTP return code or 0 if timeout or failure
@ -101,35 +101,36 @@ class CurlResult implements IHTTPResult
*
* @param string $url optional URL
*
* @return IHTTPResult a CURL with error response
* @return ICanHandleHttpResponses a CURL with error response
* @throws InternalServerErrorException
*/
public static function createErrorCurl($url = '')
public static function createErrorCurl(string $url = '')
{
return new CurlResult($url, '', ['http_code' => 0]);
}
/**
* Curl constructor.
* @param string $url the URL which was called
* @param string $result the result of the curl execution
* @param array $info an additional info array
* @param int $errorNumber the error number or 0 (zero) if no error
* @param string $error the error message or '' (the empty string) if no
*
* @param string $url the URL which was called
* @param string $result the result of the curl execution
* @param array $info an additional info array
* @param int $errorNumber the error number or 0 (zero) if no error
* @param string $error the error message or '' (the empty string) if no
*
* @throws InternalServerErrorException when HTTP code of the CURL response is missing
*/
public function __construct($url, $result, $info, $errorNumber = 0, $error = '')
public function __construct(string $url, string $result, array $info, int $errorNumber = 0, string $error = '')
{
if (!array_key_exists('http_code', $info)) {
throw new InternalServerErrorException('CURL response doesn\'t contains a response HTTP code');
}
$this->returnCode = $info['http_code'];
$this->url = $url;
$this->info = $info;
$this->returnCode = $info['http_code'];
$this->url = $url;
$this->info = $info;
$this->errorNumber = $errorNumber;
$this->error = $error;
$this->error = $error;
Logger::debug('construct', ['url' => $url, 'returncode' => $this->returnCode, 'result' => $result]);
@ -145,15 +146,15 @@ class CurlResult implements IHTTPResult
// allow for HTTP/2.x without fixing code
$header = '';
$base = $result;
$base = $result;
while (preg_match('/^HTTP\/.+? \d+/', $base)) {
$chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
$header .= $chunk;
$base = substr($base, strlen($chunk));
}
$this->body = substr($result, strlen($header));
$this->header = $header;
$this->body = substr($result, strlen($header));
$this->header = $header;
$this->header_fields = []; // Is filled on demand
}
@ -185,7 +186,7 @@ class CurlResult implements IHTTPResult
$this->redirectUrl = $this->info['url'];
}
if ($this->returnCode == 301 || $this->returnCode == 302 || $this->returnCode == 303 || $this->returnCode== 307) {
if ($this->returnCode == 301 || $this->returnCode == 302 || $this->returnCode == 303 || $this->returnCode == 307) {
$redirect_parts = parse_url($this->info['redirect_url'] ?? '');
if (empty($redirect_parts)) {
$redirect_parts = [];
@ -229,19 +230,19 @@ class CurlResult implements IHTTPResult
}
/** {@inheritDoc} */
public function getReturnCode()
public function getReturnCode(): string
{
return $this->returnCode;
}
/** {@inheritDoc} */
public function getContentType()
public function getContentType(): string
{
return $this->contentType;
}
/** {@inheritDoc} */
public function getHeader($header)
public function getHeader(string $header): array
{
if (empty($header)) {
return [];
@ -259,13 +260,13 @@ class CurlResult implements IHTTPResult
}
/** {@inheritDoc} */
public function getHeaders()
public function getHeaders(): array
{
return $this->getHeaderArray();
}
/** {@inheritDoc} */
public function inHeader(string $field)
public function inHeader(string $field): bool
{
$field = strtolower(trim($field));
@ -275,7 +276,7 @@ class CurlResult implements IHTTPResult
}
/** {@inheritDoc} */
public function getHeaderArray()
public function getHeaderArray(): array
{
if (!empty($this->header_fields)) {
return $this->header_fields;
@ -285,9 +286,9 @@ class CurlResult implements IHTTPResult
$lines = explode("\n", trim($this->header));
foreach ($lines as $line) {
$parts = explode(':', $line);
$parts = explode(':', $line);
$headerfield = strtolower(trim(array_shift($parts)));
$headerdata = trim(implode(':', $parts));
$headerdata = trim(implode(':', $parts));
if (empty($this->header_fields[$headerfield])) {
$this->header_fields[$headerfield] = [$headerdata];
} elseif (!in_array($headerdata, $this->header_fields[$headerfield])) {
@ -299,49 +300,49 @@ class CurlResult implements IHTTPResult
}
/** {@inheritDoc} */
public function isSuccess()
public function isSuccess(): bool
{
return $this->isSuccess;
}
/** {@inheritDoc} */
public function getUrl()
public function getUrl(): string
{
return $this->url;
}
/** {@inheritDoc} */
public function getRedirectUrl()
public function getRedirectUrl(): string
{
return $this->redirectUrl;
}
/** {@inheritDoc} */
public function getBody()
public function getBody(): string
{
return $this->body;
}
/** {@inheritDoc} */
public function isRedirectUrl()
public function isRedirectUrl(): bool
{
return $this->isRedirectUrl;
}
/** {@inheritDoc} */
public function getErrorNumber()
public function getErrorNumber(): int
{
return $this->errorNumber;
}
/** {@inheritDoc} */
public function getError()
public function getError(): string
{
return $this->error;
}
/** {@inheritDoc} */
public function isTimeout()
public function isTimeout(): bool
{
return $this->isTimeout;
}

View file

@ -19,10 +19,10 @@
*
*/
namespace Friendica\Network;
namespace Friendica\Network\HTTPClient\Response;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use Friendica\Network\HTTPException\NotImplementedException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
@ -30,7 +30,7 @@ use Psr\Http\Message\ResponseInterface;
/**
* A content wrapper class for Guzzle call results
*/
class GuzzleResponse extends Response implements IHTTPResult, ResponseInterface
class GuzzleResponse extends Response implements ICanHandleHttpResponses, ResponseInterface
{
/** @var string The URL */
private $url;
@ -79,68 +79,72 @@ class GuzzleResponse extends Response implements IHTTPResult, ResponseInterface
}
/** {@inheritDoc} */
public function getReturnCode()
public function getReturnCode(): string
{
return $this->getStatusCode();
}
/** {@inheritDoc} */
public function getContentType()
public function getContentType(): string
{
$contentTypes = $this->getHeader('Content-Type') ?? [];
return array_pop($contentTypes) ?? '';
}
/** {@inheritDoc} */
public function inHeader(string $field)
public function inHeader(string $field): bool
{
return $this->hasHeader($field);
}
/** {@inheritDoc} */
public function getHeaderArray()
public function getHeaderArray(): array
{
return $this->getHeaders();
}
/** {@inheritDoc} */
public function isSuccess()
public function isSuccess(): bool
{
return $this->isSuccess;
}
/** {@inheritDoc} */
public function getUrl()
public function getUrl(): string
{
return $this->url;
}
/** {@inheritDoc} */
public function getRedirectUrl()
public function getRedirectUrl(): string
{
return $this->url;
}
/** {@inheritDoc} */
public function isRedirectUrl()
/** {@inheritDoc}
*
* @throws NotImplementedException
*/
public function isRedirectUrl(): bool
{
throw new NotImplementedException();
}
/** {@inheritDoc} */
public function getErrorNumber()
public function getErrorNumber(): int
{
return $this->errorNumber;
}
/** {@inheritDoc} */
public function getError()
public function getError(): string
{
return $this->error;
}
/** {@inheritDoc} */
public function isTimeout()
public function isTimeout(): bool
{
return $this->isTimeout;
}

View file

@ -34,6 +34,7 @@ use Friendica\Model\Contact;
use Friendica\Model\GServer;
use Friendica\Model\Profile;
use Friendica\Model\User;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Protocol\ActivityNamespace;
use Friendica\Protocol\ActivityPub;
use Friendica\Protocol\Email;
@ -170,7 +171,7 @@ class Probe
Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
$xrd = null;
$curlResult = DI::httpClient()->get($ssl_url, [HTTPClientOptions::TIMEOUT => $xrd_timeout, HTTPClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
$curlResult = DI::httpClient()->get($ssl_url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
$ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
if ($curlResult->isSuccess()) {
$xml = $curlResult->getBody();
@ -187,7 +188,7 @@ class Probe
}
if (!is_object($xrd) && !empty($url)) {
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout, HTTPClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
$connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
if ($curlResult->isTimeout()) {
Logger::info('Probing timeout', ['url' => $url]);
@ -429,7 +430,7 @@ class Probe
*/
private static function getHideStatus($url)
{
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::CONTENT_LENGTH => 1000000]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
if (!$curlResult->isSuccess()) {
return false;
}
@ -950,7 +951,7 @@ class Probe
{
$xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout, HTTPClientOptions::ACCEPT_CONTENT => [$type]]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => [$type]]);
if ($curlResult->isTimeout()) {
self::$istimeout = true;
return [];

View file

@ -38,7 +38,7 @@ use Friendica\Model\ItemURI;
use Friendica\Model\Post;
use Friendica\Model\Tag;
use Friendica\Model\User;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Network\Probe;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Images;
@ -728,7 +728,7 @@ class OStatus
self::$conv_list[$conversation] = true;
$curlResult = DI::httpClient()->get($conversation, [HTTPClientOptions::ACCEPT_CONTENT => ['application/atom+xml', 'text/html']]);
$curlResult = DI::httpClient()->get($conversation, [HttpClientOptions::ACCEPT_CONTENT => ['application/atom+xml', 'text/html']]);
if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
return;
@ -922,7 +922,7 @@ class OStatus
}
$stored = false;
$curlResult = DI::httpClient()->get($related, [HTTPClientOptions::ACCEPT_CONTENT => ['application/atom+xml', 'text/html']]);
$curlResult = DI::httpClient()->get($related, [HttpClientOptions::ACCEPT_CONTENT => ['application/atom+xml', 'text/html']]);
if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
return;

View file

@ -73,7 +73,9 @@ class FileSystem
*
* @param string $url The file/url
*
* @return false|resource the open stream ressource
* @return resource the open stream rssource
*
* @throws \UnexpectedValueException
*/
public function createStream(string $url)
{

View file

@ -28,9 +28,9 @@ use Friendica\DI;
use Friendica\Model\APContact;
use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Network\CurlResult;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\IHTTPResult;
use Friendica\Network\HTTPClient\Response\CurlResult;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
/**
* Implements HTTP Signatures per draft-cavage-http-signatures-07.
@ -414,7 +414,7 @@ class HTTPSignature
* 'nobody' => only return the header
* 'cookiejar' => path to cookie jar file
*
* @return IHTTPResult CurlResult
* @return \Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses CurlResult
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function fetchRaw($request, $uid = 0, $opts = ['accept_content' => ['application/activity+json', 'application/ld+json']])
@ -450,7 +450,7 @@ class HTTPSignature
}
$curl_opts = $opts;
$curl_opts[HTTPClientOptions::HEADERS] = $header;
$curl_opts[HttpClientOptions::HEADERS] = $header;
if (!empty($opts['nobody'])) {
$curlResult = DI::httpClient()->head($request, $curl_opts);

View file

@ -1,159 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Util\Logger;
use Psr\Log\LoggerInterface;
/**
* A Logger instance to not log
*/
class VoidLogger implements LoggerInterface
{
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
return;
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
return;
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
return;
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
return;
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
return;
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
return;
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
return;
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
return;
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
return;
}
}

View file

@ -30,7 +30,7 @@ use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
/**
* Get information about a given URL
@ -214,7 +214,7 @@ class ParseUrl
return $siteinfo;
}
$curlResult = DI::httpClient()->get($url, [HTTPClientOptions::CONTENT_LENGTH => 1000000]);
$curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
return $siteinfo;
}

View file

@ -29,7 +29,7 @@ use Friendica\Model\Contact;
use Friendica\Model\Item;
use Friendica\Model\Post;
use Friendica\Model\User;
use Friendica\Network\HTTPClientOptions;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Protocol\Activity;
use Friendica\Protocol\ActivityPub;
use Friendica\Protocol\Email;
@ -153,7 +153,7 @@ class OnePoll
}
$cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
$curlResult = DI::httpClient()->get($contact['poll'], [HTTPClientOptions::COOKIEJAR => $cookiejar]);
$curlResult = DI::httpClient()->get($contact['poll'], [HttpClientOptions::COOKIEJAR => $cookiejar]);
unlink($cookiejar);
if ($curlResult->isTimeout()) {

View file

@ -141,16 +141,16 @@ return [
* and is automatically passed as an argument with the same name
*/
LoggerInterface::class => [
'instanceOf' => Factory\LoggerFactory::class,
'instanceOf' => \Friendica\Core\Logger\Factory\Logger::class,
'constructParams' => [
'index',
],
'call' => [
['create', ['index'], Dice::CHAIN_CALL],
['create', [], Dice::CHAIN_CALL],
],
],
'$devLogger' => [
'instanceOf' => Factory\LoggerFactory::class,
'instanceOf' => \Friendica\Core\Logger\Factory\Logger::class,
'constructParams' => [
'dev',
],
@ -224,8 +224,8 @@ return [
['getBackend', [], Dice::CHAIN_CALL],
],
],
Network\IHTTPClient::class => [
'instanceOf' => Factory\HTTPClientFactory::class,
Network\HTTPClient\Capability\ICanSendHttpRequests::class => [
'instanceOf' => Network\HTTPClient\Factory\HttpClient::class,
'call' => [
['createClient', [], Dice::CHAIN_CALL],
],

View file

@ -23,8 +23,8 @@ namespace Friendica\Test;
use Dice\Dice;
use Friendica\DI;
use Friendica\Factory\HTTPClientFactory;
use Friendica\Network\IHTTPClient;
use Friendica\Network\HTTPClient\Factory\HttpClient;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use GuzzleHttp\HandlerStack;
/**
@ -49,8 +49,8 @@ trait DiceHttpMockHandlerTrait
$dice = DI::getDice();
// addRule() clones the current instance and returns a new one, so no concurrency problems :-)
$newDice = $dice->addRule(IHTTPClient::class, [
'instanceOf' => HTTPClientFactory::class,
$newDice = $dice->addRule(ICanSendHttpRequests::class, [
'instanceOf' => HttpClient::class,
'call' => [
['createClient', [$this->httpRequestHandler], Dice::CHAIN_CALL],
],

View file

@ -32,11 +32,11 @@ use Friendica\Database\Database;
use Friendica\DI;
use Friendica\Test\Util\RendererMockTrait;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Logger\VoidLogger;
use Mockery;
use Mockery\MockInterface;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
use Psr\Log\NullLogger;
class AutomaticInstallationConsoleTest extends ConsoleTest
{
@ -117,7 +117,7 @@ class AutomaticInstallationConsoleTest extends ConsoleTest
});
$this->mode->shouldReceive('isInstall')->andReturn(true);
Logger::init(new VoidLogger());
Logger::init(new NullLogger());
}
/**

View file

@ -5,7 +5,7 @@ namespace Friendica\Test\src\Contact\FriendSuggest\Factory;
use Friendica\Contact\FriendSuggest\Factory\FriendSuggest;
use Friendica\Contact\FriendSuggest\Entity;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\VoidLogger;
use Psr\Log\NullLogger;
class FriendSuggestTest extends MockedTest
{
@ -91,7 +91,7 @@ class FriendSuggestTest extends MockedTest
public function testCreateNew()
{
$factory = new FriendSuggest(new VoidLogger());
$factory = new FriendSuggest(new NullLogger());
$this->assertFriendSuggest(
$factory->createNew(12, 13),
@ -106,14 +106,14 @@ class FriendSuggestTest extends MockedTest
*/
public function testCreateFromTableRow(array $input, Entity\FriendSuggest $assertion)
{
$factory = new FriendSuggest(new VoidLogger());
$factory = new FriendSuggest(new NullLogger());
$this->assertFriendSuggest($factory->createFromTableRow($input), $assertion);
}
public function testCreateEmpty()
{
$factory = new FriendSuggest(new VoidLogger());
$factory = new FriendSuggest(new NullLogger());
$this->assertFriendSuggest($factory->createEmpty(66), new Entity\FriendSuggest(0, 0, '', '', '', '', '',
new \DateTime('now', new \DateTimeZone('UTC')), 66

View file

@ -25,8 +25,8 @@ namespace Friendica\Core;
use Dice\Dice;
use Friendica\Core\Config\ValueObject\Cache;
use Friendica\DI;
use Friendica\Network\IHTTPResult;
use Friendica\Network\IHTTPClient;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\VFSTrait;
use Mockery;
@ -319,7 +319,7 @@ class InstallerTest extends MockedTest
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the CURL Response
$IHTTPResult = Mockery::mock(IHTTPResult::class);
$IHTTPResult = Mockery::mock(ICanHandleHttpResponses::class);
$IHTTPResult
->shouldReceive('getReturnCode')
->andReturn('404');
@ -331,7 +331,7 @@ class InstallerTest extends MockedTest
->andReturn('test Error');
// Mocking the CURL Request
$networkMock = Mockery::mock(IHTTPClient::class);
$networkMock = Mockery::mock(ICanSendHttpRequests::class);
$networkMock
->shouldReceive('fetchFull')
->with('https://test/install/testrewrite')
@ -342,7 +342,7 @@ class InstallerTest extends MockedTest
->andReturn($IHTTPResult);
$this->dice->shouldReceive('create')
->with(IHTTPClient::class)
->with(ICanSendHttpRequests::class)
->andReturn($networkMock);
DI::init($this->dice);
@ -366,19 +366,19 @@ class InstallerTest extends MockedTest
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the failed CURL Response
$IHTTPResultF = Mockery::mock(IHTTPResult::class);
$IHTTPResultF = Mockery::mock(ICanHandleHttpResponses::class);
$IHTTPResultF
->shouldReceive('getReturnCode')
->andReturn('404');
// Mocking the working CURL Response
$IHTTPResultW = Mockery::mock(IHTTPResult::class);
$IHTTPResultW = Mockery::mock(ICanHandleHttpResponses::class);
$IHTTPResultW
->shouldReceive('getReturnCode')
->andReturn('204');
// Mocking the CURL Request
$networkMock = Mockery::mock(IHTTPClient::class);
$networkMock = Mockery::mock(ICanSendHttpRequests::class);
$networkMock
->shouldReceive('fetchFull')
->with('https://test/install/testrewrite')
@ -389,7 +389,7 @@ class InstallerTest extends MockedTest
->andReturn($IHTTPResultW);
$this->dice->shouldReceive('create')
->with(IHTTPClient::class)
->with(ICanSendHttpRequests::class)
->andReturn($networkMock);
DI::init($this->dice);

View file

@ -19,10 +19,10 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Introspection;
use Friendica\Core\Logger\Util\Introspection;
use Mockery\MockInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

View file

@ -19,7 +19,7 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
trait LoggerDataTrait
{

View file

@ -19,10 +19,10 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\ProfilerLogger;
use Friendica\Core\Logger\Type\ProfilerLogger;
use Friendica\Util\Profiler;
use Mockery\MockInterface;
use Psr\Log\LoggerInterface;

View file

@ -19,11 +19,14 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Core\Logger\Exception\LoggerArgumentException;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core\Logger\Exception\LogLevelException;
use Friendica\Util\FileSystem;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Logger\StreamLogger;
use Friendica\Core\Logger\Type\StreamLogger;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
use Psr\Log\LogLevel;
@ -82,7 +85,7 @@ class StreamLoggerTest extends AbstractLoggerTest
$filehandler = fopen($logfile->url(), 'ab');
$logger = new StreamLogger('test', $filehandler, $this->introspection, $this->fileSystem);
$logger = new \Friendica\Core\Logger\Type\StreamLogger('test', $filehandler, $this->introspection, $this->fileSystem);
$logger->emergency('working');
$text = $logfile->getContent();
@ -114,7 +117,7 @@ class StreamLoggerTest extends AbstractLoggerTest
*/
public function testNoUrl()
{
$this->expectException(\LogicException::class);
$this->expectException(LoggerArgumentException::class);
$this->expectExceptionMessage("Missing stream URL.");
$logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem);
@ -127,8 +130,8 @@ class StreamLoggerTest extends AbstractLoggerTest
*/
public function testWrongUrl()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageMatches("/The stream or file .* could not be opened: .* /");
$this->expectException(LoggerException::class);
$this->expectExceptionMessage("Cannot create stream.");
$logfile = vfsStream::newFile('friendica.log')
->at($this->root)->chmod(0);
@ -158,7 +161,7 @@ class StreamLoggerTest extends AbstractLoggerTest
*/
public function testWrongMinimumLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(LogLevelException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new StreamLogger('test', 'file.text', $this->introspection, $this->fileSystem, 'NOPE');
@ -169,7 +172,7 @@ class StreamLoggerTest extends AbstractLoggerTest
*/
public function testWrongLogLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(LogLevelException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logfile = vfsStream::newFile('friendica.log')
@ -185,7 +188,7 @@ class StreamLoggerTest extends AbstractLoggerTest
*/
public function testWrongFile()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(LoggerArgumentException::class);
$this->expectExceptionMessage("A stream must either be a resource or a string.");
$logger = new StreamLogger('test', null, $this->introspection, $this->fileSystem);

View file

@ -19,9 +19,12 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Util\Logger\SyslogLogger;
use Friendica\Core\Logger\Exception\LoggerArgumentException;
use Friendica\Core\Logger\Exception\LoggerException;
use Friendica\Core\Logger\Exception\LogLevelException;
use Friendica\Core\Logger\Type\SyslogLogger;
use Psr\Log\LogLevel;
class SyslogLoggerTest extends AbstractLoggerTest
@ -62,7 +65,7 @@ class SyslogLoggerTest extends AbstractLoggerTest
*/
public function testWrongMinimumLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(LogLevelException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection, 'NOPE');
@ -73,7 +76,7 @@ class SyslogLoggerTest extends AbstractLoggerTest
*/
public function testWrongLogLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(LogLevelException::class);
$this->expectExceptionMessageMatches("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection);
@ -81,23 +84,6 @@ class SyslogLoggerTest extends AbstractLoggerTest
$logger->log('NOPE', 'a test');
}
/**
* Test when the logfacility is wrong (string)
*/
public function testServerException()
{
if (PHP_MAJOR_VERSION < 8) {
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageMatches("/Can\'t open syslog for ident \".*\" and facility \".*\": .* /");
} else {
$this->expectException(\TypeError::class);
$this->expectExceptionMessage("openlog(): Argument #3 (\$facility) must be of type int, string given");
}
$logger = new SyslogLoggerWrapper('test', $this->introspection, LogLevel::DEBUG, null, 'a string');
$logger->emergency('not working');
}
/**
* Test the close() method
* @doesNotPerformAssertions

View file

@ -19,10 +19,10 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Util\Introspection;
use Friendica\Util\Logger\SyslogLogger;
use Friendica\Core\Logger\Type\SyslogLogger;
use Friendica\Core\Logger\Util\Introspection;
use Psr\Log\LogLevel;
/**
@ -53,7 +53,7 @@ class SyslogLoggerWrapper extends SyslogLogger
* {@inheritdoc}
* @noinspection PhpMissingParentCallCommonInspection
*/
protected function syslogWrapper($level, $entry)
protected function syslogWrapper(int $level, string $entry)
{
$this->content .= $entry . PHP_EOL;
}

View file

@ -19,10 +19,10 @@
*
*/
namespace Friendica\Test\src\Util\Logger;
namespace Friendica\Test\src\Core\Logger;
use Friendica\Core\Logger\Type\WorkerLogger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\WorkerLogger;
use Psr\Log\LoggerInterface;
class WorkerLoggerTest extends MockedTest

View file

@ -40,7 +40,7 @@ use Friendica\DI;
use Friendica\Core\Config\Factory\Config;
use Friendica\Core\Config\Repository;
use Friendica\Core\Storage\Type;
use Friendica\Network\HTTPClient;
use Friendica\Network\HTTPClient\Client\HttpClient;
use Friendica\Test\DatabaseTest;
use Friendica\Test\Util\Database\StaticDatabase;
use Friendica\Test\Util\VFSTrait;
@ -61,7 +61,7 @@ class StorageManagerTest extends DatabaseTest
private $logger;
/** @var L10n */
private $l10n;
/** @var HTTPClient */
/** @var HttpClient */
private $httpRequest;
protected function setUp(): void
@ -93,7 +93,7 @@ class StorageManagerTest extends DatabaseTest
$this->l10n = \Mockery::mock(L10n::class);
$this->httpRequest = \Mockery::mock(HTTPClient::class);
$this->httpRequest = \Mockery::mock(HttpClient::class);
}
protected function tearDown(): void

View file

@ -1,6 +1,6 @@
<?php
namespace Friendica\Test\src\Network;
namespace Friendica\Test\src\Network\HTTPClient\Client;
use Friendica\DI;
use Friendica\Test\DiceHttpMockHandlerTrait;

View file

@ -19,11 +19,11 @@
*
*/
namespace Friendica\Test\src\Network;
namespace Friendica\Test\src\Network\HTTPClient\Response;
use Dice\Dice;
use Friendica\DI;
use Friendica\Network\CurlResult;
use Friendica\Network\HTTPClient\Response\CurlResult;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
@ -37,7 +37,7 @@ class CurlResultTest extends TestCase
/** @var Dice|MockInterface $dice */
$dice = \Mockery::mock(Dice::class)->makePartial();
$dice = $dice->addRules(include __DIR__ . '/../../../static/dependencies.config.php');
$dice = $dice->addRules(include __DIR__ . '/../../../../../static/dependencies.config.php');
$logger = new NullLogger();
$dice->shouldReceive('create')
@ -52,12 +52,12 @@ class CurlResultTest extends TestCase
*/
public function testNormal()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local', $header . $body, [
$curlResult = new \Friendica\Network\HTTPClient\Response\CurlResult('https://test.local', $header . $body, [
'http_code' => 200,
'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local'
@ -80,12 +80,12 @@ class CurlResultTest extends TestCase
*/
public function testRedirect()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local/test/it', $header . $body, [
$curlResult = new \Friendica\Network\HTTPClient\Response\CurlResult('https://test.local/test/it', $header . $body, [
'http_code' => 301,
'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local/test/it',
@ -107,12 +107,12 @@ class CurlResultTest extends TestCase
*/
public function testTimeout()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$headerArray = include(__DIR__ . '/../../../../datasets/curl/about.head.php');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local/test/it', $header . $body, [
$curlResult = new \Friendica\Network\HTTPClient\Response\CurlResult('https://test.local/test/it', $header . $body, [
'http_code' => 500,
'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local/test/it',
@ -136,9 +136,9 @@ class CurlResultTest extends TestCase
*/
public function testRedirectHeader()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.redirect');
$headerArray = include(__DIR__ . '/../../datasets/curl/about.redirect.php');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.redirect');
$headerArray = include(__DIR__ . '/../../../../datasets/curl/about.redirect.php');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local/test/it?key=value', $header . $body, [
@ -162,10 +162,10 @@ class CurlResultTest extends TestCase
*/
public function testInHeader()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local', $header . $body, [
$curlResult = new \Friendica\Network\HTTPClient\Response\CurlResult('https://test.local', $header . $body, [
'http_code' => 200,
'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local'
@ -179,10 +179,10 @@ class CurlResultTest extends TestCase
*/
public function testGetHeaderArray()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local', $header . $body, [
$curlResult = new \Friendica\Network\HTTPClient\Response\CurlResult('https://test.local', $header . $body, [
'http_code' => 200,
'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local'
@ -199,8 +199,8 @@ class CurlResultTest extends TestCase
*/
public function testGetHeaderWithParam()
{
$header = file_get_contents(__DIR__ . '/../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../datasets/curl/about.body');
$header = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.head');
$body = file_get_contents(__DIR__ . '/../../../../datasets/curl/about.body');
$curlResult = new CurlResult('https://test.local', $header . $body, [
'http_code' => 200,

View file

@ -11,8 +11,8 @@ use Friendica\Security\PermissionSet\Factory\PermissionSet as PermissionSetFacto
use Friendica\Test\MockedTest;
use Friendica\Util\ACLFormatter;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Logger\VoidLogger;
use Mockery\MockInterface;
use Psr\Log\NullLogger;
class ProfileFieldTest extends MockedTest
{
@ -28,8 +28,8 @@ class ProfileFieldTest extends MockedTest
parent::setUp();
$this->permissionSetRepository = \Mockery::mock(PermissionSetRepository::class);
$this->permissionSetFactory = new PermissionSetFactory(new VoidLogger(), new ACLFormatter());
$this->profileFieldFactory = new ProfileFieldFactory(new VoidLogger(), $this->permissionSetFactory);
$this->permissionSetFactory = new PermissionSetFactory(new NullLogger(), new ACLFormatter());
$this->profileFieldFactory = new ProfileFieldFactory(new NullLogger(), $this->permissionSetFactory);
}
public function dataEntity()

View file

@ -5,14 +5,14 @@ namespace Friendica\Test\src\Security\TwoFactor\Factory;
use Friendica\Security\TwoFactor\Factory\TrustedBrowser;
use Friendica\Test\MockedTest;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Logger\VoidLogger;
use Friendica\Util\Strings;
use Psr\Log\NullLogger;
class TrustedBrowserTest extends MockedTest
{
public function testCreateFromTableRowSuccess()
{
$factory = new TrustedBrowser(new VoidLogger());
$factory = new TrustedBrowser(new NullLogger());
$row = [
'cookie_hash' => Strings::getRandomHex(),
@ -31,7 +31,7 @@ class TrustedBrowserTest extends MockedTest
{
$this->expectException(\TypeError::class);
$factory = new TrustedBrowser(new VoidLogger());
$factory = new TrustedBrowser(new NullLogger());
$row = [
'cookie_hash' => null,
@ -48,7 +48,7 @@ class TrustedBrowserTest extends MockedTest
public function testCreateForUserWithUserAgent()
{
$factory = new TrustedBrowser(new VoidLogger());
$factory = new TrustedBrowser(new NullLogger());
$uid = 42;
$userAgent = 'PHPUnit';

View file

@ -1,52 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Util\Logger;
use Friendica\Test\MockedTest;
use Friendica\Util\Logger\VoidLogger;
use Psr\Log\LogLevel;
class VoidLoggerTest extends MockedTest
{
use LoggerDataTrait;
/**
* Test if the profiler is profiling data
* @dataProvider dataTests
* @doesNotPerformAssertions
*/
public function testNormal($function, $message, array $context)
{
$logger = new VoidLogger();
$logger->$function($message, $context);
}
/**
* Test the log() function
* @doesNotPerformAssertions
*/
public function testProfilingLog()
{
$logger = new VoidLogger();
$logger->log(LogLevel::WARNING, 'test', ['a' => 'context']);
}
}