3 namespace Drupal\Core\Batch;
6 * Helper methods for the batch system.
11 * Formats the percent completion for a batch set.
14 * The total number of operations.
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.
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
27 * @see _batch_process()
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".
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);
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.
48 } while ($percentage == '100');