Get node by node type and pattern

@param $type
@param $pattern

@return Node[]
422680
public static function findByTypeAndPattern($type = '', $pattern = '')
    {
        $where       = '1 = 1';
        $where_type  = '';
        $where_like  = '';
        $where_rlike = '';

        $placeholder = [];

        // Check type, pattern is email or phone number when passing from quick replies
        if ($type === 'payload') {
            $pattern = filter_var($pattern, FILTER_VALIDATE_EMAIL) ? 'user_email' : $pattern;
            $pattern = is_phone_number($pattern) ? 'user_phone_number' : $pattern;
        }

        if (!empty($type)) {
            $where_type           = ' AND type = :type';
            $placeholder[':type'] = $type;
        }

        if (!empty($pattern)) {
            $placeholder[':pattern'] = $pattern;
            $where_like              = ' AND :pattern LIKE pattern';
            $where_rlike             = " AND :pattern RLIKE CONCAT('^',pattern,'$')";
        }

        $columns = ['type', 'pattern', 'answers', 'wait', 'sources', 'messaging_type', 'notification_type'];

        // Where Like First
        $nodes = self::whereRaw($where . $where_type . $where_like, $placeholder)->get($columns);
        
        // If Not Found. Then Where Rlike
        if ($nodes->count() === 0) {
            $nodes = self::whereRaw($where . $where_type . $where_rlike, $placeholder)->get($columns);
        }

        // If still not found, then try NLP and find
        if ($nodes->count() === 0 && Conversation::has('nlp')) {
            $entities = Conversation::get('nlp')->getNames();

            if (! empty($entities)) {
                $entities = '#' . ltrim(implode('|#', $entities), '|');
                
                $nodes = self::whereRaw('pattern RLIKE :pattern', [
                    ':pattern' => $entities,
                ])->get($columns);

                // Enable nodes filter. Available types: first, last, any. Default: first
                $nodes = $nodes->filter(function ($node) {
                    return Conversation::get('nlp')->filter($node->pattern)->exists();
                });
            }
        }

        return $nodes;
    }
746898
protected function getForm( $types, $pattern )
    {
        $types = preg_replace( '/\s+/', '', implode( ',', (array) $types ) );

        if ( '*/*' === $types )
        {
            $types = '*';
        }

        if ( empty( $types ) )
        {
            $label = 'mime.sets.*';
        }
        else if ( strstr( $types, '*' ) || strstr( $types, ',' )  )
        {
            $label = 'mime.sets.' . $types;
        }
        else
        {
            $label = 'mime.type.' . $types;
        }

        $accept = '*' == $types ? '*/*' : $types;

        return $this->getServiceLocator()
                    ->get( 'Zork\Form\Factory' )
                    ->createForm( array(
                        'attributes'    => array(
                            'action'    => '?',
                            'method'    => 'post',
                        ),
                        'elements'      => array(
                            'types'     => array(
                                'spec'  => array(
                                    'type'  => 'Zork\Form\Element\Hidden',
                                    'name'  => 'types',
                                    'attributes' => array(
                                        'value' => $accept,
                                    ),
                                ),
                            ),
                            'pattern'   => array(
                                'spec'  => array(
                                    'type'  => 'Zork\Form\Element\Hidden',
                                    'name'  => 'pattern',
                                    'attributes' => array(
                                        'value' => $pattern,
                                    ),
                                ),
                            ),
                            'file'      => array(
                                'spec'  => array(
                                    'type'      => 'Zork\Form\Element\File',
                                    'name'      => 'file',
                                    'options'   => array(
                                        'required'      => true,
                                        'label'         => $label,
                                        'accept'        => $accept,
                                        'validators'    => $this->getValidators( $types )
                                    ),
                                ),
                            ),
                            'upload'    => array(
                                'spec'  => array(
                                    'type'      => 'Zork\Form\Element\Submit',
                                    'name'      => 'upload',
                                    'attributes'    => array(
                                        'value'     => 'default.upload',
                                    ),
                                ),
                            ),
                        ),
                    ) );
    }
40848
public static function extractHttpRoute($pattern)
    {
        $httpMethod = 'ALL';
        $routePattern = $pattern;
        if (false !== strpos($pattern, '#|#')) {
            list($httpMethod, $routePattern) = explode('#|#', $pattern, 2);
        }

        return array(strtoupper($httpMethod), $routePattern);
    }
461462
protected function findByType($pattern, $part)
    {
        if (! is_array($pattern)) {
            $pattern = [$pattern];
        }
        $needle = 0;
        foreach ($pattern as $term) {
            $needle |= $term;
        }
        $matches = [];
        foreach ($this->catalogue as $spec => $features) {
            if ($needle === ($features & $needle)) {
                $props = explode(':', $spec);
                $matches[] = $props[$part];
            }
        }
        return array_unique($matches);
    }
717908
public function find($pattern)
    {
        if (! $this->adapter->isAbsolute($pattern)) {
            $pattern = $this->rootPath . $pattern;
        }
        $list = new Collection;
        foreach ($this->adapter->glob($pattern) as $path) {
            if ($this->isFile($path, true)) {
                $list->add(new File($path, $this->adapter));
            } else {
                $list->add(new Directory($path, $this->adapter));
            }
        }
        return $list;
    }
200475
public function keys($pattern = null) {

        $keys = array();
        $stmt = $this->connection->query("SELECT `key` FROM ".$this->table." ORDER BY `key`;");
        $res  = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        if (!$pattern) {

            foreach ($res as $record) {
                $keys[] = $record["key"];
            }

        } else {

            $matcher = function_exists('fnmatch') ? 'fnmatch': function($pattern, $string){
                return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
            };

            foreach ($res as $record) {
                if($matcher($pattern, $record["key"])) {
                    $keys[] = $record["key"];
                }
            }
        }

        return $keys;
    }
1078702
protected function getTagPattern(string $pattern): string
    {
        // {...}标签左侧为{!}时不执行转换
        return '/(?<!{!})' . preg_quote($this->startTag) . $pattern . preg_quote($this->endTag) . '/s';
    }
477494
public function getPrerequisites(string $pattern = ViewInterface::pattern): array {
		
		// by default, the $pattern for this method matches the one
		// for the applyTemplate() method above, and both match the
		// public constant from the ViewInterface.  you can change the
		// pattern, but they'd better be the same, or you'll get funky
		// results.
		
		preg_match_all($pattern, $this->content, $matches);
		
		// the $matches array should have two indices.  the first is the
		// actual matched text which, by default, includes the dollar sign
		// that identifies template variables.  but, the second index is
		// the parenthetical match, which is the word following the dollar
		// sign.  so, all we want to do is send back that array but without
		// any duplicates as follows.
		
		return array_unique($matches[1]);
	}
975012
static protected function analysisPattern($pattern)
    {
        if (!($n = self::$_mbstringAvailable ? mb_strlen($pattern, APP_CHARSET) : strlen($pattern))) {
            return [];
        }
        $ps = [];
        $c0 = self::$_mbstringAvailable ? mb_substr($pattern, 0, 1, APP_CHARSET) : substr($pattern, 0, 1);

        for ($start = 0, $i = 1; $i < $n; ++$i) {
            $c = self::$_mbstringAvailable ? mb_substr($pattern, $i, 1, APP_CHARSET) : substr($pattern, $i, 1);
            if ($c !== $c0) {
                $ps[] = self::$_mbstringAvailable ? mb_substr($pattern, $start, $i - $start, APP_CHARSET) : substr($pattern, $start, $i - $start);
                $c0 = $c;
                $start = $i;
            }
        }
        $ps[] = self::$_mbstringAvailable ? mb_substr($pattern, $start, $n - $start, APP_CHARSET) : substr($pattern, $start, $n - $start);
        return $ps;
    }
1250023
public function whereKeysLike($patterns)
    {
        if (! $patterns instanceof Collection) {
            $patterns = new Collection((array) $patterns);
        }

        /* @var Collection $patterns */

        if ($patterns->filter()->isEmpty()) {
            return new static($this->all());
        }

        /**
         * Return a subset of pairs that match any of the given patterns.
         */
        return $this->pairs()->filter(function (LineInterface $line) use ($patterns) {
            return $patterns->contains(function ($index, $pattern) use ($line) {
                return fnmatch($pattern, $line->key());
            });
        });
    }
968314
public function gatherElementsFromType( $type )
	{
		if ( is_string( $type ) )
		{
			$type = $this->getType( $type );
		}

		if ( ! is_array( $type ) ) return false;

		$elements = array();

		foreach ( array( 'elements', 'sequence', 'choice', 'group' ) as $typeComponent )
		{
			if ( ! isset( $type[ $typeComponent ] ) )
			{
				continue;
			}

			foreach ( $type[ $typeComponent ] as $id => $element )
			{
				if ( $id == 'restrictionType')
				{
					continue;
				}

				if ( $id == 'elements' )
				{
					$elements += $element;
					continue;
				}

				$result = $this->gatherElementsFromType( $element );
				if ( ! $result )
				{
					$elements[ "{$element['prefix']}:{$element['name']}" ] = $element;
				}

				$elements += $result;
			}

		}

		return $elements;
	}
32731
private function getMethods($pattern = "/^action_/") {
		$methos = get_class_methods($this->class);
		$actions = array();

		foreach ($methos as $methodName) {
			if (preg_match($pattern, $methodName)) {
				array_push($actions, $methodName);
			}
		}
		return $actions;
	}
186354
public function getKeys($pattern = null)
    {
        $keys = $this->get('__stored_keys__', []);
        if (is_null($pattern)) {
            return $keys;
        }

        $matches = [];
        $pattern = $this->_normalizePattern($pattern);
        foreach ($keys as $key) {
            if (preg_match($pattern, $key)) {
                $matches[] = $key;
            }
        }

        return $matches;
    }
986450
public function getStructure(string $type = null): array
    {
        return [
            'email' => $this->makeField(trans('HCCore::users.label.email'))
                ->email()
                ->isRequired()
                ->toArray(),
        ];
    }
797679
public static function getFilter(string $type): array
    {
        return isset(self::$filters[$type]) ? self::$filters[$type] : [];
    }
579228
protected function convert(/*# string */ $pattern)/*# : array */
    {
        $ph = sprintf("\{%s(?:%s)?\}", self::MATCH_GROUP_NAME, self::MATCH_GROUP_TYPE);

        // count placeholders
        $map = $m = [];
        if (preg_match_all('~'. $ph .'~x', $pattern, $m)) {
            $map = $m[1];
        }

        $result = preg_replace(
            [
            '~' . $ph . '(*SKIP)(*FAIL) | \[~x', '~' . $ph . '(*SKIP)(*FAIL) | \]~x',
            '~\{' . self::MATCH_GROUP_NAME . '\}~x', '~' . $ph . '~x',
            ],
            ['(?:', ')?', '{\\1:' . self::MATCH_SEGMENT . '}', '(\\2)'],
            strtr('/' . trim($pattern, '/'), $this->shortcuts)
        );

        return [$result, $map];
    }
960643
public function addPattern($type, $pattern)
    {
        $this->map[$type] = $pattern;
        unset($this->compileCache[$type]);
    }