davide cucurnia
2024-01-30 9f6455d9b12bda65377e8501e00557982be9ff36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
 
class Base64
{
    /***
     * #Encode method
     * @param string $str una stringa da codificare in base64 o un Path di un file da codificare
     * @param bool $isFilePath
     * @param bool $requireSaving se true il risultato viene salvato in un file nella cartella /encoded_files/new_encoded_file.txt
     * @param string $destinationPath il path di destinazione del file in cui salvare il risultato essere in formato "il/tuo/path/nome_file.txt
     */
    public static function encode(string $str, $isFilePath = false, $requireSaving = true, $destinationPath = __DIR__ . "/encoded_files/new_encoded_file.txt")
    {
        if ($isFilePath) {
            $isFile = is_file($str);
            if (!$isFile) {
                echo "File non trovato!";
                die();
            }
            $str = file_get_contents($str);
        }
        $encodedData = base64_encode($str);
 
        if ($requireSaving) {
            self::fileWriter($destinationPath, $encodedData);
        } else {
            return $encodedData;
        }
    }
 
    /**
     * @param $filePath string il Path in cui andrà il file
     * @param $text string il testo da inserire nel file
     */
    public static function fileWriter(string $filePath, string $text)
    {
        $newFile = fopen($filePath, "w");
        fwrite($newFile, $text);
        fclose($newFile);
    }
 
    /***
     * #Decode method
     * @param string $str una stringa in base64 da decodificare o un Path
     * @param bool $isFilePath [mandatory(true) if $str is a Path optional otherwise] $isFile true se il primo arg è un Path
     * @param bool $requireSaving se true il risultato viene salvato in un file nella cartella /decoded_files/new_decoded_file.txt
     * @param string $destinationPath il path di destinazione del file in cui salvare il risultato essere in formato "il/tuo/path/nome_file.txt
     * @return string la stringa decodificata
     */
    public static function decode(string $str, $isFilePath = false, $requireSaving = true, $destinationPath = __DIR__ . "/decoded_files/new_decoded_file.txt")
    {
        if ($isFilePath) {
            $isFile = is_file($str);
            if (!$isFile) {
                echo "File non trovato!";
                die();
            }
            $str = file_get_contents($str);
        }
        $decodedData = base64_decode($str);
 
        if ($requireSaving) {
            self::fileWriter($destinationPath, $decodedData);
        } else {
            return $decodedData;
        }
    }
}