vendor/symfony/http-kernel/Profiler/FileProfilerStorage.php line 122

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. /**
  12.  * Storage for profiler using files.
  13.  *
  14.  * @author Alexandre Salomé <alexandre.salome@gmail.com>
  15.  */
  16. class FileProfilerStorage implements ProfilerStorageInterface
  17. {
  18.     /**
  19.      * Folder where profiler data are stored.
  20.      */
  21.     private string $folder;
  22.     /**
  23.      * Constructs the file storage using a "dsn-like" path.
  24.      *
  25.      * Example : "file:/path/to/the/storage/folder"
  26.      *
  27.      * @throws \RuntimeException
  28.      */
  29.     public function __construct(string $dsn)
  30.     {
  31.         if (!str_starts_with($dsn, 'file:')) {
  32.             throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use FileStorage with an invalid dsn "%s". The expected format is "file:/path/to/the/storage/folder".', $dsn));
  33.         }
  34.         $this->folder = substr($dsn, 5);
  35.         if (!is_dir($this->folder) && false === @mkdir($this->folder, 0777, true) && !is_dir($this->folder)) {
  36.             throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder));
  37.         }
  38.     }
  39.     public function find(?string $ip, ?string $url, ?int $limit, ?string $method, int $start = null, int $end = null, string $statusCode = null): array
  40.     {
  41.         $file = $this->getIndexFilename();
  42.         if (!file_exists($file)) {
  43.             return [];
  44.         }
  45.         $file = fopen($file, 'r');
  46.         fseek($file, 0, \SEEK_END);
  47.         $result = [];
  48.         while (\count($result) < $limit && $line = $this->readLineFromFile($file)) {
  49.             $values = str_getcsv($line);
  50.             [$csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values;
  51.             $csvTime = (int) $csvTime;
  52.             if ($ip && !str_contains($csvIp, $ip) || $url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($csvStatusCode, $statusCode)) {
  53.                 continue;
  54.             }
  55.             if (!empty($start) && $csvTime < $start) {
  56.                 continue;
  57.             }
  58.             if (!empty($end) && $csvTime > $end) {
  59.                 continue;
  60.             }
  61.             $result[$csvToken] = [
  62.                 'token' => $csvToken,
  63.                 'ip' => $csvIp,
  64.                 'method' => $csvMethod,
  65.                 'url' => $csvUrl,
  66.                 'time' => $csvTime,
  67.                 'parent' => $csvParent,
  68.                 'status_code' => $csvStatusCode,
  69.             ];
  70.         }
  71.         fclose($file);
  72.         return array_values($result);
  73.     }
  74.     public function purge()
  75.     {
  76.         $flags = \FilesystemIterator::SKIP_DOTS;
  77.         $iterator = new \RecursiveDirectoryIterator($this->folder, $flags);
  78.         $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
  79.         foreach ($iterator as $file) {
  80.             if (is_file($file)) {
  81.                 unlink($file);
  82.             } else {
  83.                 rmdir($file);
  84.             }
  85.         }
  86.     }
  87.     public function read(string $token): ?Profile
  88.     {
  89.         return $this->doRead($token);
  90.     }
  91.     /**
  92.      * @throws \RuntimeException
  93.      */
  94.     public function write(Profile $profile): bool
  95.     {
  96.         $file = $this->getFilename($profile->getToken());
  97.         $profileIndexed = is_file($file);
  98.         if (!$profileIndexed) {
  99.             // Create directory
  100.             $dir = \dirname($file);
  101.             if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  102.                 throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));
  103.             }
  104.         }
  105.         $profileToken = $profile->getToken();
  106.         // when there are errors in sub-requests, the parent and/or children tokens
  107.         // may equal the profile token, resulting in infinite loops
  108.         $parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;
  109.         $childrenToken = array_filter(array_map(function (Profile $p) use ($profileToken) {
  110.             return $profileToken !== $p->getToken() ? $p->getToken() : null;
  111.         }, $profile->getChildren()));
  112.         // Store profile
  113.         $data = [
  114.             'token' => $profileToken,
  115.             'parent' => $parentToken,
  116.             'children' => $childrenToken,
  117.             'data' => $profile->getCollectors(),
  118.             'ip' => $profile->getIp(),
  119.             'method' => $profile->getMethod(),
  120.             'url' => $profile->getUrl(),
  121.             'time' => $profile->getTime(),
  122.             'status_code' => $profile->getStatusCode(),
  123.         ];
  124.         $data = serialize($data);
  125.         if (\function_exists('gzencode')) {
  126.             $data = gzencode($data, 3);
  127.         }
  128.         if (false === file_put_contents($file, $data, \LOCK_EX)) {
  129.             return false;
  130.         }
  131.         if (!$profileIndexed) {
  132.             // Add to index
  133.             if (false === $file = fopen($this->getIndexFilename(), 'a')) {
  134.                 return false;
  135.             }
  136.             fputcsv($file, [
  137.                 $profile->getToken(),
  138.                 $profile->getIp(),
  139.                 $profile->getMethod(),
  140.                 $profile->getUrl(),
  141.                 $profile->getTime(),
  142.                 $profile->getParentToken(),
  143.                 $profile->getStatusCode(),
  144.             ]);
  145.             fclose($file);
  146.         }
  147.         return true;
  148.     }
  149.     /**
  150.      * Gets filename to store data, associated to the token.
  151.      */
  152.     protected function getFilename(string $token): string
  153.     {
  154.         // Uses 4 last characters, because first are mostly the same.
  155.         $folderA = substr($token, -2, 2);
  156.         $folderB = substr($token, -4, 2);
  157.         return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
  158.     }
  159.     /**
  160.      * Gets the index filename.
  161.      */
  162.     protected function getIndexFilename(): string
  163.     {
  164.         return $this->folder.'/index.csv';
  165.     }
  166.     /**
  167.      * Reads a line in the file, backward.
  168.      *
  169.      * This function automatically skips the empty lines and do not include the line return in result value.
  170.      *
  171.      * @param resource $file The file resource, with the pointer placed at the end of the line to read
  172.      */
  173.     protected function readLineFromFile($file): mixed
  174.     {
  175.         $line = '';
  176.         $position = ftell($file);
  177.         if (0 === $position) {
  178.             return null;
  179.         }
  180.         while (true) {
  181.             $chunkSize = min($position, 1024);
  182.             $position -= $chunkSize;
  183.             fseek($file, $position);
  184.             if (0 === $chunkSize) {
  185.                 // bof reached
  186.                 break;
  187.             }
  188.             $buffer = fread($file, $chunkSize);
  189.             if (false === ($upTo = strrpos($buffer, "\n"))) {
  190.                 $line = $buffer.$line;
  191.                 continue;
  192.             }
  193.             $position += $upTo;
  194.             $line = substr($buffer, $upTo + 1).$line;
  195.             fseek($file, max(0, $position), \SEEK_SET);
  196.             if ('' !== $line) {
  197.                 break;
  198.             }
  199.         }
  200.         return '' === $line ? null : $line;
  201.     }
  202.     protected function createProfileFromData(string $token, array $data, Profile $parent = null)
  203.     {
  204.         $profile = new Profile($token);
  205.         $profile->setIp($data['ip']);
  206.         $profile->setMethod($data['method']);
  207.         $profile->setUrl($data['url']);
  208.         $profile->setTime($data['time']);
  209.         $profile->setStatusCode($data['status_code']);
  210.         $profile->setCollectors($data['data']);
  211.         if (!$parent && $data['parent']) {
  212.             $parent = $this->read($data['parent']);
  213.         }
  214.         if ($parent) {
  215.             $profile->setParent($parent);
  216.         }
  217.         foreach ($data['children'] as $token) {
  218.             if (null !== $childProfile = $this->doRead($token, $profile)) {
  219.                 $profile->addChild($childProfile);
  220.             }
  221.         }
  222.         return $profile;
  223.     }
  224.     private function doRead($token, Profile $profile = null): ?Profile
  225.     {
  226.         if (!$token || !file_exists($file = $this->getFilename($token))) {
  227.             return null;
  228.         }
  229.         $h = fopen($file, 'r');
  230.         flock($h, \LOCK_SH);
  231.         $data = stream_get_contents($h);
  232.         flock($h, \LOCK_UN);
  233.         fclose($h);
  234.         if (\function_exists('gzdecode')) {
  235.             $data = @gzdecode($data) ?: $data;
  236.         }
  237.         if (!$data = unserialize($data)) {
  238.             return null;
  239.         }
  240.         return $this->createProfileFromData($token, $data, $profile);
  241.     }
  242. }