Test Failed
Push — main ( 31a78f...703d27 )
by Rafael
10:23
created

MathUtils   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 46
rs 10
c 1
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A howManyBytes() 0 26 5
1
<?php
2
/**
3
 * Alxarafe. Development of PHP applications in a flash!
4
 * Copyright (C) 2018-2020 Alxarafe <[email protected]>
5
 */
6
7
namespace Alxarafe\Core\Utils;
8
9
use Alxarafe\Core\Singletons\Debug;
10
use Alxarafe\Database\Schema;
11
12
class MathUtils
13
{
14
    /**
15
     * Retorna el número de bytes que son necesarios para almacenar un número que
16
     * vaya entre $min y $max, considerando si hay o no signo.
17
     *
18
     * Téngase en cuenta que min y unsigned son casi excluyentes, pero que unsigned
19
     * sí que afecta al tamaño máximo positivo.
20
     *
21
     * Esta función pretende determinar el tipo de entero necesario. Las
22
     * inconsistencias (que no son tales), las tendrá que contemplar quién lo invoque.
23
     *
24
     * @author Rafael San José Tovar <[email protected]>
25
     *
26
     * @param int  $max
27
     * @param int  $min
28
     * @param bool $unsigned
29
     *
30
     * @return int
31
     */
32
    public static function howManyBytes(int $max, int $min = 0, bool $unsigned = Schema::DEFAULT_INTEGER_UNSIGNED): int
33
    {
34
        if ($min > $max) {
35
            Debug::message('Se ha invocado a howManyBytes con el mínimo y máximo cambiados');
36
            $tmp = $min;
37
            $min = $max;
38
            $max = $tmp;
39
        }
40
41
        $bits = log($max + 1, 2);
42
        if (!$unsigned) {
43
            $bits++;
44
        }
45
        $bytes = ceil($bits / 8);
46
47
        if ($min >= 0) {
48
            return $bytes;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $bytes returns the type double which is incompatible with the type-hinted return integer.
Loading history...
49
        }
50
51
        $bits = log(abs($min), 2);
52
        $bytesForMin = ceil(($bits + 1) / 8);
53
        if ($bytesForMin > $bytes) {
54
            return $bytesForMin;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $bytesForMin returns the type double which is incompatible with the type-hinted return integer.
Loading history...
55
        }
56
57
        return $bytes;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $bytes returns the type double which is incompatible with the type-hinted return integer.
Loading history...
58
    }
59
}
60