<?php

declare(strict_types=1);
class BEncode
{
   // Sort dictionary keys
   private function makeSorted(array $array): array
   {
       ksort($array);
       return $array;
   }

   // Encode a single entry
   private function encodeEntry($entry, string &$fd): void
   {
       if (is_int($entry) || is_float($entry)) {
           $fd .= "i{$entry}e";
       } elseif (is_string($entry)) {
           $fd .= strlen($entry) . ":{$entry}";
       } else {
           throw new InvalidArgumentException("Unsupported entry type.");
       }
   }

   // Encode a list
   private function encodeList(array $list, string &$fd): void
   {
       $fd .= "l";
       foreach ($list as $item) {
           $this->decideEncode($item, $fd);
       }
       $fd .= "e";
   }

   // Encode a dictionary
   private function encodeDict(array $dict, string &$fd): void
   {
       $fd .= "d";
       $sortedDict = $this->makeSorted($dict);
       foreach ($sortedDict as $key => $value) {
           $this->encodeEntry($key, $fd);
           $this->decideEncode($value, $fd);
       }
       $fd .= "e";
   }

   // Decide what to encode
   private function decideEncode($data, string &$fd): void
   {
       if (is_array($data)) {
           if (array_keys($data) === range(0, count($data) - 1)) {
               $this->encodeList($data, $fd);
           } else {
               $this->encodeDict($data, $fd);
           }
       } else {
           $this->encodeEntry($data, $fd);
       }
   }

   // Public method to encode data
   public function encode($data): string
   {
       $fd = "";
       $this->decideEncode($data, $fd);
       return $fd;
   }
}

// Usage example:
function BEncode($data): string
{
   return (new BEncode())->encode($data);
}


?>