.
*/
namespace App\Services\LogSystem;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Services\ElementTypeNameGenerator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class LogDataFormatter
{
private const STRING_MAX_LENGTH = 1024;
private TranslatorInterface $translator;
private EntityManagerInterface $entityManager;
private ElementTypeNameGenerator $elementTypeNameGenerator;
public function __construct(TranslatorInterface $translator, EntityManagerInterface $entityManager, ElementTypeNameGenerator $elementTypeNameGenerator)
{
$this->translator = $translator;
$this->entityManager = $entityManager;
$this->elementTypeNameGenerator = $elementTypeNameGenerator;
}
/**
* Formats the given data of a log entry as HTML
* @param mixed $data
* @param AbstractLogEntry $logEntry
* @param string $fieldName
* @return string
*/
public function formatData($data, AbstractLogEntry $logEntry, string $fieldName): string
{
if (is_string($data)) {
$tmp = '"' . mb_strimwidth(htmlspecialchars($data), 0, self::STRING_MAX_LENGTH, ) . '"';
//Show special characters and line breaks
$tmp = preg_replace('/\n/', '\\n
', $tmp);
$tmp = preg_replace('/\r/', '\\r', $tmp);
$tmp = preg_replace('/\t/', '\\t', $tmp);
return $tmp;
}
if (is_bool($data)) {
return $this->formatBool($data);
}
if (is_int($data)) {
return (string) $data;
}
if (is_float($data)) {
return (string) $data;
}
if (is_null($data)) {
return 'null';
}
if (is_array($data)) {
//If the array contains only one element with the key @id, it is a reference to another entity (foreign key)
if (isset($data['@id'])) {
return $this->formatForeignKey($data, $logEntry, $fieldName);
}
//If the array contains a "date", "timezone_type" and "timezone" key, it is a DateTime object
if (isset($data['date'], $data['timezone_type'], $data['timezone'])) {
return $this->formatDateTime($data);
}
return $this->formatJSON($data);
}
throw new \RuntimeException('Type of $data not supported (' . gettype($data) . ')');
}
private function formatJSON(array $data): string
{
$json = htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT), ENT_QUOTES | ENT_SUBSTITUTE);
return sprintf(
'