<?php

/* English

	Programming info

All functions output a small array, which we'll call $return for now.

$return[0] is the data expected of the function
$return[1] is the offset over the whole bencoded data of the next
           piece of data.

numberdecode returns [0] as the integer read, and [1]-1 points to the
symbol that was interprented as the end of the interger (either "e" or
":"). 
numberdecode is used for integer decodes both for i11e and 11:hello there
so it is tolerant of the ending symbol.

decodelist returns $return[0] as an integer indexed array like you would use in C
for all the entries. $return[1]-1 is the "e" that ends the list, so [1] is the next
useful byte.

decodeDict returns $return[0] as an array of text-indexed entries. For example,
$return[0]["announce"] = "http://www.whatever.com:6969/announce";
$return[1]-1 again points to the "e" that ends the dictionary.

decodeEntry returns [0] as an integer in the case $offset points to
i12345e or a string if $offset points to 11:hello there style strings.
It also calls decodeDict or decodeList if it encounters a d or an l.


Known bugs:
- The program doesn't pay attention to the string it's working on.
  A zero-sized or truncated data block will cause string offset errors
  before they get rejected by the decoder. This is worked around by
  suppressing errors.
*/

/* French!!
Informations sur la programmation

Toutes les fonctions génèrent un petit tableau, que nous appellerons $return pour l'instant.

$return[0] est la donnée attendue de la fonction
$return[1] est le décalage sur l'ensemble des données codées en ben du prochain
morceau de données.

numberdecode renvoie [0] comme entier lu, et [1]-1 pointe vers le
symbole qui a été interprété comme la fin de l'entier (soit "e" ou "":"").

numberdecode est utilisé pour les décodages d'entiers à la fois pour i11e et 11:hello there
il est donc tolérant au symbole de fin.

decodelist renvoie $return[0] sous forme de tableau indexé d'entiers comme vous l'utiliseriez en C
pour toutes les entrées. $return[1]-1 est le "e" qui termine la liste, donc [1] est le prochain
octet utile.

decodeDict renvoie $return[0] sous forme de tableau d'entrées indexées en texte. Par exemple,
$return[0]["announce"] = "http://www.whatever.com:6969/announce";
$return[1]-1 pointe à nouveau vers le "e" qui termine le dictionnaire.

decodeEntry renvoie [0] sous forme d'entier dans le cas où $offset pointe vers
i12345e ou une chaîne si $offset pointe vers les chaînes de style 11:hello there.
Il appelle également decodeDict ou decodeList s'il rencontre un d ou un l.

Bugs connus :
- Le programme ne fait pas attention à la chaîne sur laquelle il travaille.
Un bloc de données de taille zéro ou tronqué provoquera des erreurs de décalage de chaîne
avant qu'elles ne soient rejetées par le décodeur. Cela peut être résolu en
supprimant les erreurs.
*/

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);
}



?>