Get blocks matching specified condition.

@param string $condition
@param array  $blocks

@return array
430535
protected function filterBlocks(string $condition, array $blocks)
    {
        if (empty($condition)) {
            return $blocks;
        }

        $conditions = [];
        foreach (explode(';', $condition) as $condition) {
            if (strpos($condition, ':') === false) {
                //Invalid
                continue;
            }

            list($name, $value) = explode(":", $condition);
            $conditions[$name] = $value;
        }

        $result = $blocks;
        if (isset($conditions['prefix'])) {
            $result = [];
            foreach ($blocks as $name => $value) {
                if (strpos($name, $conditions['prefix']) === 0) {
                    //Prefix plus "-" sign
                    $result[substr($name, strlen($conditions['prefix']) + 1)] = $value;
                }
            }
        }

        if (isset($conditions['include'])) {
            $include = explode(',', $conditions['include']);

            foreach ($blocks as $name => $value) {
                if (!in_array($name, $include)) {
                    unset($result[$name]);
                }
            }
        }

        if (isset($conditions['exclude'])) {
            $exclude = explode(',', $conditions['exclude']);

            foreach ($blocks as $name => $value) {
                if (in_array($name, $exclude)) {
                    unset($result[$name]);
                }

                foreach ($exclude as $pattern) {
                    if (strpos($pattern, '*') === false) {
                        //Not pattern
                        continue;
                    }

                    $pattern = '/^' . str_replace('*', '.+', $pattern) . '/i';

                    if (preg_match($pattern, $name)) {
                        unset($result[$name]);
                    }
                }
            }
        }

        return $result;
    }
587278
public function expandBlocks($blocks){

        $decoded = array();
        foreach($blocks as $blockName=>$block){
            $bytes = new GifByteStream($block);
            if(false !== strpos($blockName, 'header')){
                $part = $bytes->bite(3);
                $decoded['signature'] = $this->_hexToAscii($part);
                $part = $bytes->bite(3);
                $decoded['version'] = $this->_hexToAscii($part);
            } else if(false !== strpos($blockName, 'logicalScreenDescriptor')){
                $part = $bytes->bite(2);
                $decoded['canvasWidth'] = hexdec($this->_switchEndian($part));
                $part = $bytes->bite(2);
                $decoded['canvasHeight'] = hexdec($this->_switchEndian($part));
                $part = $bytes->bite(1);
                $bin = $this->_fixSize($this->_hexToBin($part), 8); // Make sure len is correct
                $decoded['globalColorTableFlag'] = bindec(substr($bin, 0 ,1));
                $decoded['colorResolution'] = bindec(substr($bin, 1 ,3));
                $decoded['sortFlag'] = bindec(substr($bin, 4 ,1));
                $decoded['sizeOfGlobalColorTable'] = bindec(substr($bin, 5 ,3));
                $part = $bytes->bite(1);
                $decoded['backgroundColorIndex'] = hexdec($part);
                $part = $bytes->bite(1);
                $decoded['pixelAspectRatio'] = hexdec($part);

            } else if(false !== strpos($blockName, 'globalColorTable')){
                $decoded['globalColorTable'] = $block;
            } else if(false !== strpos($blockName, 'applicationExtension')){
                $index = explode('-', $blockName, 2);
                $index = $index[1];

                $bytes->next(2); // Skip ext intro and label: 21 ff
                $appNameSize = $bytes->bite(1); // 0x0b or 11 according to spec but we check anyways
                $appNameSize = hexdec($appNameSize);
                $appName = $this->_hexToAscii($bytes->bite($appNameSize));
                $subBlocks = array();
                while (!$bytes->isEnd()) { // loop thru all app sub blocks
                    $nextSize = $bytes->bite(1);
                    if($nextSize !== '00'){
                        $size = hexdec($nextSize);
                        $subBlocks[] = $bytes->bite($size);

                    }
                }
                if($appName==='NETSCAPE2.0'){
                    $decoded['applicationExtension'][$index]['appId'] = 'NETSCAPE';
                    $decoded['applicationExtension'][$index]['appCode'] = '2.0';
                    $decoded['applicationExtension'][$index]['subBlocks'] = $subBlocks;
                    $decoded['loopCount'] = hexdec($this->_switchEndian(substr($subBlocks[0], 2, 4)));
                } else {
                    $decoded['applicationExtension'][$index]['appId'] = substr($appName, 0, 8);
                    $decoded['applicationExtension'][$index]['appCode'] = substr($appName, 8, 3);
                    $decoded['applicationExtension'][$index]['subBlocks'] = $subBlocks;
                }
            } else if(false !== strpos($blockName, 'graphicControlExtension')) {
                $index = explode('-', $blockName, 2);
                $index = $index[1];

                $bytes->next(3); // Skip ext intro, label, and block size which is always 4: 21 f9 04
                $part = $bytes->bite(1); // packed field
                $bin = $this->_fixSize($this->_hexToBin($part), 8); // Make sure len is correct
                $decoded['frames'][$index]['disposalMethod'] = bindec(substr($bin, 3 ,3));
                $decoded['frames'][$index]['userInputFlag'] = bindec(substr($bin, 6 ,1));
                $decoded['frames'][$index]['transparentColorFlag'] = bindec(substr($bin, 7 ,1));
                $part = $bytes->bite(2);
                $decoded['frames'][$index]['delayTime'] = hexdec($this->_switchEndian($part));
                $part = $bytes->bite(1);
                $decoded['frames'][$index]['transparentColorIndex'] = hexdec($part);
            } else if(false !== strpos($blockName, 'imageDescriptor')) {
                $index = explode('-', $blockName, 2);
                $index = $index[1];

                $bytes->next(1); // skip separator: 2c
                $part                                               = $bytes->bite(2);
                $decoded['frames'][$index]['imageLeft']             = hexdec($this->_switchEndian($part));
                $part                                               = $bytes->bite(2);
                $decoded['frames'][$index]['imageTop']              = hexdec($this->_switchEndian($part));
                $part                                               = $bytes->bite(2);
                $decoded['frames'][$index]['imageWidth']            = hexdec($this->_switchEndian($part));
                $part                                               = $bytes->bite(2);
                $decoded['frames'][$index]['imageHeight']           = hexdec($this->_switchEndian($part));
                $part                                               = $bytes->bite(1); // packed field
                $bin                                                = $this->_fixSize($this->_hexToBin($part),
                    8);
                $decoded['frames'][$index]['localColorTableFlag']   = bindec(substr($bin, 0, 1));
                $decoded['frames'][$index]['interlaceFlag']         = bindec(substr($bin, 1, 1));
                $decoded['frames'][$index]['sortFlag']              = bindec(substr($bin, 2, 1));
                $decoded['frames'][$index]['sizeOfLocalColorTable'] = bindec(substr($bin, 5, 3));
            } else if(false !== strpos($blockName, 'localColorTable')){
                $index = explode('-', $blockName, 2);
                $index = $index[1];
                $decoded['frames'][$index]['localColorTable'] = $block;
            } else if(false !== strpos($blockName, 'imageData')) {
                $index = explode('-', $blockName, 2);
                $index = $index[1];

                $decoded['frames'][$index]['imageData'] = $block;
            } else if($blockName === 'trailer') {
                $decoded['trailer'] = $block;
            }
            unset($bytes);
        }

        return $decoded;
    }
993334
protected function loadBlocks(array $blocks, ContainerBuilder $container)
    {
        foreach ($blocks as $blockName => $block) {
            $container
                ->register(
                    'elcodi.sitemap_element_provider.entity_' . $blockName,
                    'Elcodi\Component\Sitemap\Element\EntitySitemapElementProvider'
                )
                ->addArgument(new Reference($block['repository_service']))
                ->addArgument($block['method'])
                ->addArgument($block['arguments'])
                ->setPublic(false);

            $container
                ->register(
                    'elcodi.sitemap_element_generator.entity_' . $blockName,
                    'Elcodi\Component\Sitemap\Element\EntitySitemapElementGenerator'
                )
                ->addArgument(new Reference('elcodi.factory.sitemap_element'))
                ->addArgument(new Reference($block['transformer']))
                ->addArgument(new Reference('elcodi.sitemap_element_provider.entity_' . $blockName))
                ->addArgument($block['changeFrequency'])
                ->addArgument($block['priority'])
                ->setPublic(false);
        }

        return $this;
    }
598140
public function fetchRow($condition = array())
    {
        $query = self::getInstance($this, $condition);

        return $this->getRepository()->fetch($query, AnDomain::FETCH_ROW);
    }
536219
public function findByBlock($block)
    {
        if ($block instanceof Block) {
            $block = $block->getBlockID();
        } elseif ($block instanceof BlockController) {
            $block = $block->getBlockObject()->getBlockID();
        }

        return $this->findBy([
            'block_id' => $block
        ]);
    }
1125913
public function sortBlocks(array $blocks)
    {
        // Perform a simple sort first
        usort($blocks, function ($a, $b)  {
            if ($a->getSort() == $b->getSort()) {
                return 0;
            }
            return ($a->getSort() < $b->getSort()) ? -1 : 1;
        });

        // Determine hierarchy of ownership first
        $ownerIds = array();
        foreach ($blocks as $block) {
            $superKey = ($block->getOwner()->getSuper()) ? array_search($block->getOwner()->getSuper()->getId(), $ownerIds) : false;
            if ($superKey === false) {
                array_unshift($ownerIds, $block->getOwner()->getId());
            } else {
                $ownerIds = array_merge(array_slice($ownerIds, 0, $superKey+1), array($block->getOwner()->getId()), array_slice($ownerIds, $superKey+1));
            }
        }
        $ownerIds = array_flip($ownerIds); // Flip it for easier lookup by parentId as key.
        asort($ownerIds);

        $sorted = array();
        $parentOwnerId = null;
        $parentSize = null;
        foreach ($ownerIds as $ownerId => $ownerPos) {
            // Get blocks in level/segment
            $segment = array_values(array_filter($blocks, function ($block) use ($ownerId) {
                return ($block->getOwner() && $block->getOwner()->getId() == $ownerId);
            }));

            if (! count($segment)) {
                $parentOwnerId = $ownerId;
                continue; // nothing to do for this owner
            }

            // now inject at correct positions
            if (count($segment) && $parentOwnerId === null) {
                $sorted = $segment;
            } else if (count($segment)) {
                $positioned = array_filter($segment, function ($block) {
                   return ($block->getSortParent() !== null && $block->getSortParent() >= 0);
                });

                // if nothing is positioned throw them on top
                if (! count($positioned)) {
                    $sorted = array_merge($segment, $sorted);
                } else {
                    // first part
                    $keys = array_keys($positioned);
                    if ($keys[0] > 0) {
                        $sorted = array_merge(array_slice($segment, 0, array_shift($keys)), $sorted);
                    } elseif ($keys[0] == 0) {
                        unset($keys[0]);
                    }

                    foreach ($positioned as $key => $block) {
                        $endIdx = (count($keys)) ? array_shift($keys) : null;
                        $insert = array_slice($segment, $key, ($endIdx) ? ($endIdx-$key) : null);

                        foreach ($sorted as $insertIdx => $item) {
                            // Check if we inherit from this block
                            if ($item->getOwner()->getId() == $parentOwnerId && $item->getSort() == $block->getSortParent() &&
                                // And check if we're in the same parent block on same position
                                (($item->isInRoot() && $block->isInRoot() || ($item->getParent() && $block->getParent() && $item->getParent()->getId() == $block->getParent()->getId())) && $item->getPosition() == $block->getPosition())) {
                                break;
                            }
                        }
                        $sorted = array_merge(array_slice($sorted, 0, $insertIdx+1), $insert, array_slice($sorted, $insertIdx+1));
                    }
                }
            }

            $parentOwnerId = $ownerId;
        }

        return $sorted;
    }
393868
private function extractField($blocks)
    {
        $fieldData = array();

        $pattern = "/([a-zA-Z]+) *(.+)/";

        foreach ($blocks as $block) {
            $match = preg_match($pattern, $block, $matches);

            // A full double string match found
            if (count($matches) == 3) {
                $docLabel = trim(strtolower($matches[1]));
                $docValue = trim($matches[2]);

                if (in_array($docLabel, self::$VALID_EXPRESSIONS)) {
                    $fieldData[self::$VALID_EXPRESSIONS_NAMES[$docLabel]] = $docValue;
                }
            }
        }

        return $fieldData;
    }
1305444
public function writeBlocks( $blocks )
	{
		foreach( $blocks as $name => $content )
		{
			$list[]	= str_replace( "{#name#}", $name, $this->patternSection );
			$list[]	= $content;
			$list[]	= "";
		}
		$file	= new FS_File_Writer( $this->fileName );
		return $file->writeArray( $list );
	}
159248
public function get($block)
    {
        if ($this->enabled) {
            if (!array_key_exists($block, $this->blocks)) {
                throw new \Exception('Block '.$block.' not defined');
            }

            $this->finishBlock($block);

            return $this->blocks[$block];
        }
    }
18257
public static function findAllArray($condition = [],$orderBy = []) {
        return self::find()->where($condition)->asArray()->orderBy($orderBy)->all(static::getDb());
    }
1154258
private function get_tags(string $block){
    preg_match_all($this->pattern['tag'], $block, $tags, PREG_OFFSET_CAPTURE);
    if ( !empty($tags[0]) ){
      return $tags[0];
    }
    return [];
  }
281762
private function seedBlock($blockTypes, $languages, $users, $contents)
    {
        $blocks = [];
        for ($x = 0; $x < self::RANDOM_BLOCKS; $x++) {
            $block    = $this->seedRandomBlock(
                $blockTypes->random(),
                $languages,
                $users,
                $contents
            );
            $blocks[] = $block;
        }

        return $blocks;
    }
892648
public function fetchRows($condition = array())
    {
        $query = self::getInstance($this, $condition);

        return $this->getRepository()->fetch($query, AnDomain::FETCH_ROW_LIST);
    }
432814
public function getVariablesInBlock(array $variables)
    {
        $blockVariableNames = array_map(function (Variable $variable) {
            return $variable->getName();
        }, $this->variables);

        return array_filter($variables, function (Variable $variable) use ($blockVariableNames) {
            return in_array($variable->getName(), $blockVariableNames);
        });
    }
1142958
public function route(array $condition)
    {
        if (!in_array($condition['operator'], array('=', '!='))) {
            return false;
        }

        $route = $this->route->get();
        return $this->compare($route['pattern'], $condition['value'], $condition['operator']);
    }
993870
public function getHlblocks($filter = array()) {
        $dbres = HL\HighloadBlockTable::getList(
            array(
                'select' => array('*'),
                'filter' => $filter,
            )
        );

        $result = [];
        while ($hlblock = $dbres->fetch()) {
            $hlblock['LANG'] = $this->getHblockLangs($hlblock['ID']);
            $result[] = $hlblock;
        }

        return $result;
    }
966055
private function serializeRules(array $rules): array
    {
        $serializer = new BlockSerializer();

        $indexMap = [];
        foreach ($rules as $name => $rule) {
            $indexMap[$name] = $serializer->addBlock($rule->setName($name)->enableCapture()->toBlock());
        }

        return [$indexMap, $serializer->get()];
    }