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

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