Skip to content

Instantly share code, notes, and snippets.

@su-narthur
Created July 12, 2018 14:51
Show Gist options
  • Select an option

  • Save su-narthur/df23a647739d4bae9416414fb8694fba to your computer and use it in GitHub Desktop.

Select an option

Save su-narthur/df23a647739d4bae9416414fb8694fba to your computer and use it in GitHub Desktop.

Revisions

  1. su-narthur created this gist Jul 12, 2018.
    40 changes: 40 additions & 0 deletions less_php_contrast_port.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    <?php


    use Mexitek\PHPColors\Color;

    class SF_static_color
    {
    public static function contrast( $color, $dark = "black", $light = "white", $threshold = 0.43 ) {
    # https://github.com/oyejorge/less.php/blob/master/lib/Less/Functions.php#L438-L475

    $colorLuma = self::getLuminosity( $color );
    $darkLuma = self::getLuminosity( $dark );
    $lightLuma = self::getLuminosity( $light );

    if ($darkLuma > $lightLuma) {
    $t = $light;
    $light = $dark;
    $dark = $t;
    }

    return ($colorLuma < $threshold) ? $light : $dark;
    }

    private static function getLuminosity( $color ) {
    # https://github.com/oyejorge/less.php/blob/master/lib/Less/Tree/Color.php#L43-L53

    $color = new Color( $color );
    $rgb = $color->getRgb();

    $r = $rgb["R"] / 255;
    $g = $rgb["G"] / 255;
    $b = $rgb["B"] / 255;

    $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
    $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
    $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);

    return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
    }
    }