Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Core / Batch / Percentage.php
1 <?php
2
3 namespace Drupal\Core\Batch;
4
5 /**
6  * Helper methods for the batch system.
7  */
8 class Percentage {
9
10   /**
11    * Formats the percent completion for a batch set.
12    *
13    * @param int $total
14    *   The total number of operations.
15    * @param int $current
16    *   The number of the current operation. This may be a floating point number
17    *   rather than an integer in the case of a multi-step operation that is not
18    *   yet complete; in that case, the fractional part of $current represents the
19    *   fraction of the operation that has been completed.
20    *
21    * @return string
22    *   The properly formatted percentage, as a string. We output percentages
23    *   using the correct number of decimal places so that we never print "100%"
24    *   until we are finished, but we also never print more decimal places than
25    *   are meaningful.
26    *
27    * @see _batch_process()
28    */
29   public static function format($total, $current) {
30     if (!$total || $total == $current) {
31       // If $total doesn't evaluate as true or is equal to the current set, then
32       // we're finished, and we can return "100".
33       $percentage = '100';
34     }
35     else {
36       // We add a new digit at 200, 2000, etc. (since, for example, 199/200
37       // would round up to 100% if we didn't).
38       $decimal_places = max(0, floor(log10($total / 2.0)) - 1);
39       do {
40         // Calculate the percentage to the specified number of decimal places.
41         $percentage = sprintf('%01.' . $decimal_places . 'f', round($current / $total * 100, $decimal_places));
42         // When $current is an integer, the above calculation will always be
43         // correct. However, if $current is a floating point number (in the case
44         // of a multi-step batch operation that is not yet complete), $percentage
45         // may be erroneously rounded up to 100%. To prevent that, we add one
46         // more decimal place and try again.
47         $decimal_places++;
48       } while ($percentage == '100');
49     }
50     return $percentage;
51   }
52
53 }