Created
September 1, 2017 02:05
-
-
Save cimmwolf/3c07da8e6f9646980b1dd1f2bfd05468 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function matches($media, $screen = []) | |
{ | |
if (strpos($media, ',') !== false) | |
$mql = explode(',', $media); | |
else | |
$mql = [$media]; | |
$mqIndex = count($mql) - 1; | |
$mqLength = $mqIndex; | |
$mq = null; | |
$exprList = null; | |
$expr = null; | |
$match = true; | |
if ($media == '') | |
return true; | |
do { | |
$mq = $mql[$mqLength - $mqIndex]; | |
$exprListStr = $mq; | |
if (strpos($exprListStr, ' and ') !== false) | |
$exprList = explode(' and ', $exprListStr); | |
else | |
$exprList = [$exprListStr]; | |
$exprIndex = count($exprList) - 1; | |
if ($match && $exprIndex >= 0 && $exprListStr !== '') { | |
do { | |
preg_match('/^\s*\(\s*(-[a-z]+-)?(min-|max-)?([a-z\-]+)\s*(:?\s*([0-9]+(\.[0-9]+)?|portrait|landscape)(px|em|dppx|dpcm|rem|%|in|cm|mm|ex|pt|pc|\/([0-9]+(\.[0-9]+)?))?)?\s*\)\s*$/', $exprList[$exprIndex], $expr); | |
if (empty($expr) || empty($screen[$expr[3]])) { | |
$match = false; | |
break; | |
} | |
$prefix = $expr[2]; | |
$length = $expr[5]; | |
$value = $length; | |
$unit = $expr[7]; | |
$feature = $screen[$expr[3]]; | |
// echo 'prefix =' . $prefix . PHP_EOL; | |
// echo 'value = ' . $value . PHP_EOL; | |
// echo 'unit = ' . $unit . PHP_EOL; | |
// echo 'feature = ' . $feature . PHP_EOL; | |
if ($unit && $unit === 'px') | |
$value = $length; | |
// Test for prefix min or max | |
// Test value against feature | |
if ($prefix === 'min-' && $value) { | |
$match = $feature >= $value; | |
} else if ($prefix === 'max-' && $value) { | |
$match = $feature <= $value; | |
} else if ($value) { | |
$match = $feature === $value; | |
} else { | |
$match = !!$feature; | |
} | |
// If 'match' is false, break loop | |
// Continue main loop through query list | |
if (!$match) { | |
break; | |
} | |
} while ($exprIndex--); | |
} | |
// If match is true, break loop | |
// Once matched, no need to check other queries | |
if ($match) { | |
break; | |
} | |
} while ($mqIndex--); | |
return $match; | |
} | |
if (matches('', ['width'=>767]) === true) | |
echo '1. Ok' . PHP_EOL; | |
if (matches('(max-width: 767px)', ['width'=>767]) === true) | |
echo '2. Ok' . PHP_EOL; | |
if (matches('(max-width: 400px)', ['width'=>767]) === false) | |
echo '3. Ok' . PHP_EOL; | |
if (matches('(min-width: 767px)', ['width'=>767]) === true) | |
echo '4. Ok' . PHP_EOL; | |
if (matches('(min-width: 768px)', ['width'=>767]) === false) | |
echo '5. Ok' . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment