Parses the media rule.

@param string $ruleString
766905
protected function parseRuleString($ruleString)
    {
        if (is_string($ruleString)) {
            $charset = $this->getCharset();

            // Remove at-rule and unnecessary white-spaces
            $ruleString = preg_replace('/^[ \r\n\t\f]*@media[ \r\n\t\f]*/i', '', $ruleString);
            $ruleString = trim($ruleString, " \r\n\t\f");

            $groupsOpened = 0;
            $enclosedChar = null;

            $queries = [];
            $conditionList = "";
            $currentQueries = [];
            $currentConditions = [];

            if (preg_match('/[^\x00-\x7f]/', $ruleString)) {
                $isAscii = false;
                $strLen  = mb_strlen($ruleString, $charset);
            } else {
                $isAscii = true;
                $strLen = strlen($ruleString);
            }

            for ($i = 0, $j = $strLen; $i < $j; $i++) {
                if ($isAscii === true) {
                    $char = $ruleString[$i];
                } else {
                    $char = mb_substr($ruleString, $i, 1, $charset);
                }

                if (count($currentQueries) === 0) {
                    $currentQueries[] = "";
                }
                if ($char === "(") {
                    if ($groupsOpened > 0) {
                        $conditionList .= $char;
                    }
                    $groupsOpened++;
                } else if ($char === ")") {
                    $groupsOpened--;
                    if ($groupsOpened > 0) {
                        $conditionList .= $char;
                    } else {
                        if ($conditionList != "") {
                            $conditions = $this->parseConditionList($conditionList);
                            foreach ($conditions as $condition) {
                                $currentConditions[] = $condition;
                            }
                        }
                        $conditionList = "";
                    }
                } else if ($char === ",") {
                    if ($groupsOpened > 0) {
                        $conditionList .= $char;
                    } else {
                        foreach ($currentQueries as $currentQuery) {
                            $query = $this->getQueryInstanceFromQueryString($currentQuery);
                            if ($query !== null) {
                                if (count($currentConditions) > 0) {
                                    $query->setConditions($currentConditions);
                                }

                                $queries[] = $query;
                            }
                        }
                        $currentQueries = [];
                        $currentConditions = [];
                    }
                } else if ($char === " ") {
                    if ($groupsOpened > 0) {
                        $conditionList .= $char;
                    } else {
                        foreach (array_keys($currentQueries) as $index) {
                            $currentQueries[$index] .= $char;
                        }
                    }
                } else {
                    if ($groupsOpened > 0) {
                        $conditionList .= $char;
                    } else {
                        foreach (array_keys($currentQueries) as $index) {
                            $currentQueries[$index] .= $char;
                        }
                    }
                }
            }
            if ($groupsOpened > 0) {
                // Handle unclosed parenthesis following the spec:
                // "Because the parenthesized block is unclosed, it will contain the entire rest of the stylesheet
                // from that point (unless it happens to encounter an unmatched ')' character somewhere in the
                // stylesheet), and turn the entire thing into a not all media query."
                $this->setIsValid(false);
                $this->addValidationError("Parse error. Unclosed parenthesis at '$ruleString'.");

                $query = new MediaQuery(MediaQuery::TYPE_ALL);
                $query->setIsNot(true);
                $queries[] = $query;
            } else {
                foreach ($currentQueries as $currentQuery) {
                    $query = $this->getQueryInstanceFromQueryString($currentQuery);
                    if ($query !== null) {
                        if (count($currentConditions) > 0) {
                            $query->setConditions($currentConditions);
                        }
                        $queries[] = $query;
                    }
                }
            }

            // If not query set, default to type "all"
            if (count($queries) === 0) {
                $queries[] = new MediaQuery(MediaQuery::TYPE_ALL);
            }

            $this->setQueries($queries);
        } else {
            throw new \InvalidArgumentException(
                "Invalid type '" . gettype($ruleString). "' for argument 'ruleString' given."
            );
        }
    }
382296
public function updateRules(RuleSet $ruleSet)
    {
        $this->client->updateRules($this->uri->withPath('.settings/rules'), $ruleSet);
    }
903461
protected function parseRuleString($ruleString)
    {
        if (is_string($ruleString)) {
            $charset = $this->getCharset();

            // Remove at-rule and unnecessary white-spaces
            $ruleString = preg_replace('/^[ \r\n\t\f]*@namespace[ \r\n\t\f]+/i', '', $ruleString);
            $ruleString = trim($ruleString, " \r\n\t\f");

            // Remove trailing semicolon
            $ruleString = rtrim($ruleString, ";");

            $isEscaped  = false;
            $inFunction = false;

            $parts = [];
            $currentPart  = "";
            for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
                $char = mb_substr($ruleString, $i, 1, $charset);
                if ($char === "\\") {
                    if ($isEscaped === false) {
                        $isEscaped = true;
                    } else {
                        $isEscaped = false;
                    }
                } else {
                    if ($char === " ") {
                        if ($isEscaped === false) {
                            if ($inFunction == false) {
                                $currentPart = trim($currentPart, " \r\n\t\f");
                                if ($currentPart !== "") {
                                    $parts[] = trim($currentPart, " \r\n\t\f");
                                    $currentPart = "";
                                }
                            }
                        } else {
                            $currentPart .= $char;
                        }
                    } elseif ($isEscaped === false && $char === "(") {
                        $inFunction = true;
                        $currentPart .= $char;
                    } elseif ($isEscaped === false && $char === ")") {
                        $inFunction = false;
                        $currentPart .= $char;
                    } else {
                        $currentPart .= $char;
                    }
                }

                // Reset escaped flag
                if ($isEscaped === true && $char !== "\\") {
                    $isEscaped = false;
                }
            }
            if ($currentPart !== "") {
                $currentPart = trim($currentPart, " \r\n\t\f");
                if ($currentPart !== "") {
                    $parts[] = trim($currentPart, " \r\n\t\f");
                }
            }

            foreach ($parts as $key => $value) {
                $parts[$key] = Placeholder::replaceStringPlaceholders($value);
            }


            $countParts = count($parts);
            if ($countParts === 2) {
                $this->setPrefix($parts[0]);

                // Get URL value
                $name = Url::extractUrl($parts[1]);

                $this->setName($name);
            } elseif ($countParts === 1) {
                // Get URL value
                $name = Url::extractUrl($parts[0]);

                $this->setName($name);
            } else {
                // ERROR
            }
        } else {
            throw new \InvalidArgumentException(
                "Invalid type '" . gettype($ruleString). "' for argument 'ruleString' given."
            );
        }
    }
1178134
protected function parseRuleString($ruleString)
    {
        // Remove at-rule name and unnecessary white-spaces
        $ruleString = preg_replace('/^[ \r\n\t\f]*@supports[ \r\n\t\f]*/i', '', $ruleString);
        $ruleString = trim($ruleString, " \r\n\t\f");

        $charset = $this->getCharset();

        $conditions = [];

        foreach (Condition::splitNestedConditions($ruleString, $this->getCharset()) as $normalizedConditionList) {
            $normalizedConditions = [];
            $currentCondition = "";

            if (preg_match('/[^\x00-\x7f]/', $normalizedConditionList)) {
                $isAscii = false;
                $strLen  = mb_strlen($normalizedConditionList, $charset);
                $getAnd  = function($i) use ($normalizedConditionList){
                    return strtolower(substr($normalizedConditionList, $i, 5));
                };
            } else {
                $isAscii = true;
                $strLen = strlen($normalizedConditionList);
                $getAnd  = function($i) use ($charset, $normalizedConditionList){
                    return mb_strtolower(mb_substr($normalizedConditionList, $i, 5, $charset), $charset);
                };
            }

            for ($i = 0, $j = $strLen; $i < $j; $i++) {
                if ($isAscii === true) {
                    $char = $normalizedConditionList[$i];
                } else {
                    $char = mb_substr($normalizedConditionList, $i, 1, $charset);
                }

                if ($char === " " && $getAnd($i) === " and ") {
                    $normalizedConditions[] = new SupportsCondition(trim($currentCondition, " \r\n\t\f"));
                    $currentCondition = "";
                    $i += (5 - 1);
                } else {
                    $currentCondition .= $char;
                }
            }
            $currentCondition = trim($currentCondition, " \r\n\t\f");
            if ($currentCondition !== "") {
                $normalizedConditions[] = new SupportsCondition(trim($currentCondition, " \r\n\t\f"));
            }

            foreach ($normalizedConditions as $normalizedCondition) {
                $conditions[] = $normalizedCondition;
            }
        }

        $this->setConditions($conditions);
    }
1141391
public function validate(array $input, array $ruleset)
    {
        $this->errors = array();

        foreach ($ruleset as $field => $rules) {
            #if(!array_key_exists($field, $input))
            #{
            #   continue;
            #}

            $rules = explode('|', $rules);

            if (in_array('required', $rules) || (isset($input[$field]) && trim($input[$field]) != '')) {
                foreach ($rules as $rule) {
                    $method = null;
                    $param = null;

                    if (strstr($rule, ',') !== false) {
                        // has params

                        $rule = explode(',', $rule);
                        $method = 'validate_'.$rule[0];
                        $param = $rule[1];
                        $rule = $rule[0];
                    } else {
                        $method = 'validate_'.$rule;
                    }

                    if (is_callable(array($this, $method))) {

                        $result = $this->$method($field, $input, $param);

                        if (is_array($result)) {
                            // Validation Failed

                            $this->errors[] = $result;
                        }
                    } elseif (isset($this->validation_methods[$rule])) {
                        if (isset($input[$field])) {
                            $result = call_user_func($this->validation_methods[$rule], $field, $input, $param);


                            if (!$result) {
                                // Validation Failed

                                $this->errors[] = array(
                                    'field' => $field,
                                    'value' => $input[$field],
                                    'rule' => $method,
                                    'param' => $param,
                                );
                            }
                        }
                    } else {
                        throw new Exception("Validator method '$method' does not exist.");
                    }
                }
            }
        }

        $this->compileMessage();

        return $this;
    }
527430
protected function parseRuleString($ruleString)
    {
        if (is_string($ruleString)) {
            // Check for valid rule format
            // (with vendor prefix check to match e.g. "@-moz-document")
            if (preg_match(
                '/^[ \r\n\t\f]*@(' . self::getVendorPrefixRegExp("/") . ')?document[ \r\n\t\f]+(.*)$/i',
                $ruleString,
                $matches
            )) {
                $vendorPrefix = $matches[1];
                $ruleString = trim($matches[2], " \r\n\t\f");
                $charset = $this->getCharset();

                $inFunction = false;
                $isEscaped = false;

                $conditions = [];
                $currentCondition = "";
                $currentValue  = "";
                for ($i = 0, $j = mb_strlen($ruleString, $charset); $i < $j; $i++) {
                    $char = mb_substr($ruleString, $i, 1, $charset);
                    if ($char === "\\") {
                        if ($isEscaped === false) {
                            $isEscaped = true;
                        } else {
                            $isEscaped = false;
                        }
                    } else {
                        if ($char === "(") {
                            if ($isEscaped === false) {
                                $inFunction = true;
                                continue;
                            } else {
                                $currentValue .= $char;
                            }
                        } else if ($char === ")") {
                            if ($isEscaped === false) {
                                $conditions[$currentCondition] = trim($currentValue, " \r\n\t\f");
                                $currentCondition = "";
                                $currentValue = "";
                                $inFunction = false;
                                continue;
                            } else {
                                $currentValue .= $char;
                            }
                        } else if ($char === "," || $char === " ") {
                            if ($currentCondition === "" && $currentValue === "") {
                                continue;
                            } elseif ($currentValue !== "") {
                                $currentValue .= $char;
                            } else {
                                // something wrong here...
                            }
                        } else {
                            if ($inFunction === false) {
                                $currentCondition .= $char;
                            } else {
                                $currentValue .= $char;
                            }
                        }
                    }

                    // Reset escaped flag
                    if ($isEscaped === true && $char !== "\\") {
                        $isEscaped = false;
                    }
                }

                foreach ($conditions as $key => $value) {
                    $conditions[$key] = Placeholder::replaceStringPlaceholders($value, true);
                }

                if (isset($conditions["url"])) {
                    $this->setUrl($conditions["url"]);
                }
                if (isset($conditions["url-prefix"])) {
                    $this->setUrlPrefix($conditions["url-prefix"]);
                }
                if (isset($conditions["domain"])) {
                    $this->setDomain($conditions["domain"]);
                }
                if (isset($conditions["regexp"])) {
                    $this->setRegexp($conditions["regexp"]);
                }
                if ($vendorPrefix !== "") {
                    $this->setVendorPrefix($vendorPrefix);
                }
            } else {
                throw new \InvalidArgumentException("Invalid format for @document rule.");
            }
        } else {
            throw new \InvalidArgumentException(
                "Invalid type '" . gettype($ruleString) . "' for argument 'ruleString' given. String expected."
            );
        }
    }
1005827
private function parseStr($dataString)
    {
        $data = [];
        parse_str($dataString, $data);

        $this->setContent($dataString);
        if(is_array($data)) $this->setData($data);

        $this->emit('end');
    }
1276393
protected function parseStringRule($rules)
    {
        $parameters = [];
        // The format for specifying validation rules and parameters follows an
        // easy {rule}:{parameters} formatting convention. For instance the
        // rule "Max:3" states that the value may only be three letters.
        if (strpos($rules, ':') !== false) {
            list($rules, $parameter) = explode(':', $rules, 2);
            $parameters = $this->parseParameters($rules, $parameter);
        }
        return [Str::studly(trim($rules)), $parameters];
    }
507160
def _parseAtMedia(self, src):
        
        ctxsrc = src
        src = src[len('@media '):].lstrip()
        mediums = []
        while src and src[0] != '{':
            medium, src = self._getIdent(src)
            if medium is None:
                raise self.ParseError('@media rule expected media identifier', src, ctxsrc)
            # make "and ... {" work
            if medium == 'and':
                # strip up to curly bracket
                pattern = re.compile('.*({.*)')
                match = re.match(pattern, src)
                src = src[match.end()-1:]
                break
            mediums.append(medium)
            if src[0] == ',':
                src = src[1:].lstrip()
            else:
                src = src.lstrip()

        if not src.startswith('{'):
            raise self.ParseError('Ruleset opening \'{\' not found', src, ctxsrc)
        src = src[1:].lstrip()

        stylesheetElements = []
        #while src and not src.startswith('}'):
        #    src, ruleset = self._parseRuleset(src)
        #    stylesheetElements.append(ruleset)
        #    src = src.lstrip()

        # Containing @ where not found and parsed
        while src and not src.startswith('}'):
            if src.startswith('@'):
                # @media, @page, @font-face
                src, atResults = self._parseAtKeyword(src)
                if atResults is not None:
                    stylesheetElements.extend(atResults)
            else:
                # ruleset
                src, ruleset = self._parseRuleset(src)
                stylesheetElements.append(ruleset)
            src = src.lstrip()

        if not src.startswith('}'):
            raise self.ParseError('Ruleset closing \'}\' not found', src, ctxsrc)
        else:
            src = src[1:].lstrip()

        result = self.cssBuilder.atMedia(mediums, stylesheetElements)
        return src, result
281587
protected function parseRule($rules)
    {
        if (is_array($rules)) {
            return $this->parseArrayRule($rules);
        }
        if(is_string($rules)) {
            return $this->parseStringRule($rules);
        }
    }
454464
public function applyRules($field, $ruleset)
    {
        // Save previous values, just in case
        $acc = $this->acc;
        $crs = $this->current_ruleset;
        $this->bail_out = false;

        $this->acc = $this->get($field);
        $this->current_ruleset = $ruleset;

        while (!is_null($rule = $this->pullRule())) {
            $this->cast = false;
            $this->custom_error = null;

            if ($rule == 'required') {
                $is_required = true;
            }

            // For debugging
            $tmp = null;
            $this->consumed = array($rule);

            try {
                if ((is_object($rule) || is_array($rule)) && is_callable($rule)) {
                    $tmp = $rule($this, $this->acc, $field);
                } else {
                    // For to_XX rules
                    if (substr($rule, 0, 3) == 'to_') {
                        if (!$this->hasMethod('rule_'.$rule)) {
                            $rule = substr($rule, 3);
                        }

                        $this->cast = true;
                    }

                    if ($rule === '') {
                        if ($this->cast) {
                            $this->set($field, $this->acc);
                        }
                        continue;
                    }

                    $rule = $this->resolveRuleAlias($rule);

                    $tmp = $this->{'rule_'.$rule}($this->acc, $field);
                }

                if ($this->debug) {
                    echo "<font color=blue>rule_$rule({$this->acc},".
                    implode(',', $this->consumed).")=$tmp</font><br/>";
                }

                if (!is_null($tmp)) {
                    $this->acc = $tmp;
                }
                if ($this->cast) {
                    $this->set($field, $tmp);
                }
                if ($this->bail_out) {
                    break;
                }
            } catch (\Exception_ValidityCheck $e) {
                if ($this->debug) {
                    echo "<font color=red>rule_$rule({$this->acc},".
                        implode(',', $this->consumed).') failed</font><br/>';
                }
                $this->acc = $acc;
                $this->current_ruleset = $crs;
                throw $e
                    ->setField($field)
                    ->addMoreInfo('val', $this->acc)
                    ->addMoreInfo('rule', $rule);
            }
        }
        $this->acc = $acc;
        $this->current_ruleset = $crs;
    }
1339199
public function parseString($string)
    {
        $string = (string) $string;
        $string = preg_replace_callback("/\\$\{(.*?)\}/",
            function ($k) {
                return $this->get($k[1]);
            }, $string);

        return $string;
    }
57655
public function updateRulesetUniques($ruleset = null)
    {
        $rules = $this->getRuleset($ruleset);
        $this->setRuleset($ruleset, $this->injectUniqueIdentifierToRules($rules));
    }
596945
public function parse($value, $rule) {
        $rs = strval($this->filterByStrLen(strval($value), $rule));

        $this->filterByRegex($rs, $rule);

        return $rs;
    }
1021601
function (ruleStr) {
		var name;
		var params = '';

		ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) {
			name = _name;
			params = _params.trim();
		});

		params = params.length ? this._parseParamsString(params) : null;

		return Rule.create(name, params);
	}
972708
private function parseRule($rule, $input, $key)
    {
        $ruleExp = explode(':', $rule);
        if (count($ruleExp) > 1) {
            switch ($ruleExp[0]) {
                case 'match':
                $this->_errors[$key][] = $this->_parser->match($input, $key, $ruleExp[1], $this->_lang['match']);
                break;
                case 'min':
                $this->_errors[$key][] = $this->_parser->min($input, $key, $ruleExp[1], $this->_lang['min']);
                break;
                case 'max':
                $this->_errors[$key][] = $this->_parser->max($input, $key, $ruleExp[1], $this->_lang['max']);
                break;
                case 'from':
                $this->_errors[$key][] = $this->_parser->from($input, $key, $rule, $this->_lang['from']);
                break;
            }
        } else {
            switch ($rule) {
                case 'required':
                $this->_errors[$key][] = $this->_parser->required($input, $key, $this->_lang['required']);
                break;
                case 'email':
                $this->_errors[$key][] = $this->_parser->email($input, $key, $this->_lang['email']);
                break;
                case 'url':
                $this->_errors[$key][] = $this->_parser->url($input, $key, $this->_lang['url']);
                break;
            }
        }
    }
1216861
private function generateRule($ruleset)
    {
        $regex = '';
        $content = 'index.php';

        $count = 0;
        $total = count($ruleset);

        foreach($ruleset as $ruleChunk)
        {
            $count++;

            if($count === 1) {
                $content .= '?post_type=' . $this->postType->postType;
            }

            if(preg_match('/\{\w+\}/', $ruleChunk))
            {
                // Add to the url catcher
                $regex .= '/([^/]+)';

                // Add to the query string
                $string = preg_match('/\{(.*?)\}/', $ruleChunk, $matches);
                $index = '$matches[' . ($count - 1) . ']';
                $content .= '&' . $matches[1] . '=' . $index;
            }
            else
            {
                // Add to the url catcher
                $regex .= '/' . $ruleChunk;
            }
        }

        $regex .= '/?$';

        return array($regex, $content);
    }