vendor\symfony\http-kernel\Profiler\FileProfilerStorage.php line 166

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