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

Open in your IDE?
  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.      * @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($ip$url$limit$method$start null$end null$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($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.      * @param string $token
  166.      *
  167.      * @return string The profile filename
  168.      */
  169.     protected function getFilename($token)
  170.     {
  171.         // Uses 4 last characters, because first are mostly the same.
  172.         $folderA substr($token, -22);
  173.         $folderB substr($token, -42);
  174.         return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
  175.     }
  176.     /**
  177.      * Gets the index filename.
  178.      *
  179.      * @return string The index filename
  180.      */
  181.     protected function getIndexFilename()
  182.     {
  183.         return $this->folder.'/index.csv';
  184.     }
  185.     /**
  186.      * Reads a line in the file, backward.
  187.      *
  188.      * This function automatically skips the empty lines and do not include the line return in result value.
  189.      *
  190.      * @param resource $file The file resource, with the pointer placed at the end of the line to read
  191.      *
  192.      * @return mixed A string representing the line or null if beginning of file is reached
  193.      */
  194.     protected function readLineFromFile($file)
  195.     {
  196.         $line '';
  197.         $position ftell($file);
  198.         if (=== $position) {
  199.             return null;
  200.         }
  201.         while (true) {
  202.             $chunkSize min($position1024);
  203.             $position -= $chunkSize;
  204.             fseek($file$position);
  205.             if (=== $chunkSize) {
  206.                 // bof reached
  207.                 break;
  208.             }
  209.             $buffer fread($file$chunkSize);
  210.             if (false === ($upTo strrpos($buffer"\n"))) {
  211.                 $line $buffer.$line;
  212.                 continue;
  213.             }
  214.             $position += $upTo;
  215.             $line substr($buffer$upTo 1).$line;
  216.             fseek($filemax(0$position), \SEEK_SET);
  217.             if ('' !== $line) {
  218.                 break;
  219.             }
  220.         }
  221.         return '' === $line null $line;
  222.     }
  223.     protected function createProfileFromData($token$data$parent null)
  224.     {
  225.         $profile = new Profile($token);
  226.         $profile->setIp($data['ip']);
  227.         $profile->setMethod($data['method']);
  228.         $profile->setUrl($data['url']);
  229.         $profile->setTime($data['time']);
  230.         $profile->setStatusCode($data['status_code']);
  231.         $profile->setCollectors($data['data']);
  232.         if (!$parent && $data['parent']) {
  233.             $parent $this->read($data['parent']);
  234.         }
  235.         if ($parent) {
  236.             $profile->setParent($parent);
  237.         }
  238.         foreach ($data['children'] as $token) {
  239.             if (null !== $childProfile $this->doRead($token$profile)) {
  240.                 $profile->addChild($childProfile);
  241.             }
  242.         }
  243.         return $profile;
  244.     }
  245.     private function doRead($tokenProfile $profile null): ?Profile
  246.     {
  247.         if (!$token || !file_exists($file $this->getFilename($token))) {
  248.             return null;
  249.         }
  250.         $h fopen($file'r');
  251.         flock($h, \LOCK_SH);
  252.         $data stream_get_contents($h);
  253.         flock($h, \LOCK_UN);
  254.         fclose($h);
  255.         if (\function_exists('gzdecode')) {
  256.             $data = @gzdecode($data) ?: $data;
  257.         }
  258.         if (!$data unserialize($data)) {
  259.             return null;
  260.         }
  261.         return $this->createProfileFromData($token$data$profile);
  262.     }
  263. }