当前位置: 首页>>代码示例>>PHP>>正文


PHP CakeText类代码示例

本文整理汇总了PHP中CakeText的典型用法代码示例。如果您正苦于以下问题:PHP CakeText类的具体用法?PHP CakeText怎么用?PHP CakeText使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CakeText类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: set

 /**
  * Sets the views meta data, if available
  *
  * @param array $data
  * @return void
  */
 public function set($data = array())
 {
     $Model = $this->__controller->{$this->__controller->modelClass};
     // assign the meta title variable, starting with data assigned
     // directly to MetaData, falling back next to the Model displayField
     // variable before falling again to the Model displayName variable
     if (!empty($data['MetaData']['title'])) {
         $metaTitle = $data['MetaData']['title'];
     } elseif (!empty($data[$Model->alias][$Model->displayField])) {
         $metaTitle = $data[$Model->alias][$Model->displayField];
     } else {
         $metaTitle = Inflector::pluralize($data[$Model->alias][$Model->displayName]);
     }
     if (!empty($metaTitle)) {
         $this->Controller->set(compact('metaTitle'));
     }
     // assign the meta description variable, starting with data
     // assigned directly to MetaData, falling back to content
     // and then body fields from within the supplied data
     if (!empty($data['MetaData']['description'])) {
         $metaDescription = $data['MetaData']['description'];
     } elseif (!empty($data[$Model->alias]['body'])) {
         // truncate the content variable to a max of 160 characters
         // ref: https://moz.com/learn/seo/meta-description
         $metaDescription = CakeText::truncate($data['MetaData']['description'], 160, array('html' => false));
     } elseif (!empty($data[$Model->alias]['content'])) {
         // truncate the content variable to a max of 160 characters
         // ref: https://moz.com/learn/seo/meta-description
         $metaDescription = CakeText::truncate($data[$Model->alias]['content'], 160, array('html' => false));
     }
     if (!empty($metaDescription)) {
         $this->Controller->set(compact('metaDescription'));
     }
     return;
 }
开发者ID:mrstu84,项目名称:metadata,代码行数:41,代码来源:MetaComponent.php

示例2: testGenerate

 public function testGenerate()
 {
     $data = ['url' => 'http://www.spiegel.de', 'start' => '2010-10-09 22:23:34', 'end' => '2010-10-09 23:23:34', 'summary' => 'xyz', 'description' => 'xyz hjdhfj dhfäöüp e', 'organizer' => 'CEO', 'class' => 'public', 'timestamp' => '2010-10-08 22:23:34', 'id' => CakeText::uuid(), 'location' => 'München'];
     $this->Ical->add($data);
     $this->Ical->add($data);
     $res = $this->Ical->generate();
     //pr($res);
 }
开发者ID:ByMyHandsOnly,项目名称:BMHO_Web,代码行数:8,代码来源:IcalHelperTest.php

示例3: _results

 /**
  * Prints calculated results
  *
  * @param array $times Array of time values
  * @return void
  */
 protected function _results($times)
 {
     $duration = array_sum($times);
     $requests = count($times);
     $this->out(CakeText::insert(__d('debug_kit', 'Total Requests made: :requests'), compact('requests')));
     $this->out(CakeText::insert(__d('debug_kit', 'Total Time elapsed: :duration (seconds)'), compact('duration')));
     $this->out("");
     $this->out(CakeText::insert(__d('debug_kit', 'Requests/Second: :rps req/sec'), array('rps' => round($requests / $duration, 3))));
     $this->out(CakeText::insert(__d('debug_kit', 'Average request time: :average-time seconds'), array('average-time' => round($duration / $requests, 3))));
     $this->out(CakeText::insert(__d('debug_kit', 'Standard deviation of average request time: :std-dev'), array('std-dev' => round($this->_deviation($times, true), 3))));
     $this->out(CakeText::insert(__d('debug_kit', 'Longest/shortest request: :longest sec/:shortest sec'), array('longest' => round(max($times), 3), 'shortest' => round(min($times), 3))));
     $this->out("");
 }
开发者ID:kameshwariv,项目名称:testexample,代码行数:19,代码来源:BenchmarkShell.php

示例4: testAddWithPreSpecifiedId

 /**
  * testAddWithPreSpecifiedId method
  *
  * @return void
  */
 public function testAddWithPreSpecifiedId()
 {
     extract($this->settings);
     $this->Tree = new $modelClass();
     $this->Tree->order = null;
     $this->Tree->initialize(2, 2);
     $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1')));
     $id = CakeText::uuid();
     $this->Tree->create();
     $result = $this->Tree->save(array($modelClass => array('id' => $id, 'name' => 'testAddMiddle', $parentField => $data[$modelClass]['id'])));
     $expected = array_merge(array($modelClass => array('id' => $id, 'name' => 'testAddMiddle', $parentField => '2')), $result);
     $this->assertSame($expected, $result);
     $this->assertTrue($this->Tree->verify());
 }
开发者ID:SebFav,项目名称:ApplicationInternet2,代码行数:19,代码来源:TreeBehaviorUuidTest.php

示例5: folder

 /**
  * Main execution function to indent a folder recursivly
  *
  * @return void
  */
 public function folder()
 {
     if (!empty($this->params['extensions'])) {
         $this->settings['files'] = CakeText::tokenize($this->params['extensions']);
     }
     if (!empty($this->params['again'])) {
         $this->settings['againWithHalf'] = true;
     }
     if (!empty($this->args)) {
         if (!empty($this->args[0]) && $this->args[0] !== 'app') {
             $folder = $this->args[0];
             if ($folder === '/') {
                 $folder = APP;
             }
             $folder = realpath($folder);
             if (!file_exists($folder)) {
                 return $this->error('folder not exists: ' . $folder . '');
             }
             $this->_paths[] = $folder;
         } elseif ($this->args[0] === 'app') {
             $this->_paths[] = APP;
         }
         if (!empty($this->params['files'])) {
             $this->settings['files'] = explode(',', $this->params['files']);
         }
         $this->out($folder);
         $this->out('searching...');
         $this->_searchFiles();
         $this->out('found: ' . count($this->_files));
         if (!empty($this->params['dry-run'])) {
             $this->out('TEST DONE');
         } else {
             $continue = $this->in('Modifying files! Continue?', ['y', 'n'], 'n');
             if (strtolower($continue) !== 'y' && strtolower($continue) !== 'yes') {
                 return $this->error('...aborted');
             }
             $this->_correctFiles();
             $this->out('DONE');
         }
     } else {
         $this->out('Usage: cake intend folder');
         $this->out('"folder" is then intended recursivly');
         $this->out('default file types are');
         $this->out('[' . implode(', ', $this->settings['files']) . ']');
         $this->out('');
         $this->out('Specify file types manually:');
         $this->out('-files php,js,css');
     }
 }
开发者ID:ByMyHandsOnly,项目名称:BMHO_Web,代码行数:54,代码来源:IndentShell.php

示例6: distanceQuery

    /**
     * @author Reed Dadoune
     * distanceQuery
     * A genral case distance query builder
     * Pass a number of options to this function and recieve a query
     * you can pass to either the find or paginate functions to get
     * objects back by distance
     *
     * Example:
     *  $query = $this->Model->distanceQuery(array(
     *    'lat' => 34.2746405,
     *    'lng' => -119.2290053
     *  ));
     *  $query['conditions']['published'] = true;
     *  $results = $this->Model->find('all', $query);
     *
     * @param array $opts Options
     *                    - lat The latitude coordinate of the center point
     *                    - lng The longitude coordinate of the center point
     *                    - alias The model name of the query this is for
     *                      defaults to the current model alias
     *                    - radius The distance to at which to find objects at
     *                      defaults to false in which case distance is calculated
     *                      only for the sort order
     * @return array A query that can be modified and passed to find or paginate
     */
    public function distanceQuery($opts = array())
    {
        $defaults = array('lat' => 0, 'lng' => 0, 'alias' => $this->alias, 'radius' => false);
        $opts = Set::merge($defaults, $opts);
        $query = array('fields' => array(CakeText::insert('3956 * 2 *
					ASIN(SQRT(
						POWER(SIN((:lat - ABS(:alias.lat)) * PI() / 180 / 2), 2) +
						COS(:lat * PI() / 180) *
						COS(ABS(:alias.lat) * PI() / 180) *
						POWER(SIN((:lng - :alias.lng) * PI() / 180 / 2), 2)
					)) AS distance', array('alias' => $opts['alias'], 'lat' => $opts['lat'], 'lng' => $opts['lng']))), 'order' => array('distance' => 'ASC'));
        if ($opts['radius']) {
            $longitudeLower = $opts['lng'] - $opts['radius'] / abs(cos(deg2rad($opts['lat'])) * 69);
            $longitudeUpper = $opts['lng'] + $opts['radius'] / abs(cos(deg2rad($opts['lat'])) * 69);
            $latitudeLower = $opts['lat'] - $opts['radius'] / 69;
            $latitudeUpper = $opts['lat'] + $opts['radius'] / 69;
            $query['conditions'] = array(String::insert(':alias.lat  BETWEEN ? AND ?', array('alias' => $opts['alias'])) => array($latitudeLower, $latitudeUpper), String::insert(':alias.lng BETWEEN ? AND ?', array('alias' => $opts['alias'])) => array($longitudeLower, $longitudeUpper));
            $query['group'] = sprintf('%s.id HAVING distance < %f', $opts['alias'], $opts['radius']);
        }
        return $query;
    }
开发者ID:priyankasingh,项目名称:Genie,代码行数:47,代码来源:Service.php

示例7: populateInfo

 protected function populateInfo($userid)
 {
     // Fetch user info
     if (is_array($userid)) {
         $userinfo = $userid;
     } else {
         $userinfo = $this->User->findById($userid);
     }
     if (empty($userinfo)) {
         throw new InternalErrorException('Unknown UserID.');
     }
     // Destroy the current session (if any)
     $this->Session->destroy();
     // Verify the account is enabled/not expired
     if ($userinfo['User']['active'] != 1) {
         $this->redirect('/?account_disabled');
     }
     // Generate logout token
     $userinfo['User']['logout_token'] = Security::hash(CakeText::uuid());
     // Clean the password (remove it from the array)
     unset($userinfo['User']['password']);
     // Set the new information
     $this->Session->write($userinfo);
     // Update our arrays
     $this->userinfo = $userinfo['User'];
     $this->groupinfo = $userinfo['Group'];
 }
开发者ID:ubnetdef,项目名称:auth_server,代码行数:27,代码来源:AppController.php

示例8: populateInfo

 protected function populateInfo($userid)
 {
     // Fetch user info
     $userinfo = $this->User->findById($userid);
     if (empty($userinfo)) {
         throw new InternalErrorException('Unknown UserID.');
     }
     // Save specific info from the current session (if exists)
     $emulating = $this->Session->read('User.emulating');
     $emulating_from = -1;
     if ($emulating) {
         $emulating_from = $this->Session->read('User.emulating_from');
     }
     // Destroy the current session (if any)
     $this->Session->destroy();
     // Verify the account is enabled/not expired
     if ($userinfo['User']['active'] != 1) {
         $this->redirect('/?account_disabled');
     }
     if ($userinfo['User']['expires'] != 0 && $userinfo['User']['expires'] <= time()) {
         $this->redirect('/?account_expired');
     }
     // Generate logout token
     $userinfo['User']['logout_token'] = Security::hash(CakeText::uuid());
     // Generate refresh interval (5 minutes)
     $userinfo['User']['refresh_info'] = time() + self::REFRESH_INTERVAL;
     // Add the emulating information
     $userinfo['User']['emulating'] = $emulating;
     $userinfo['User']['emulating_from'] = $emulating_from;
     // Fetch the team/group info
     $teaminfo = $this->Team->findById($userinfo['User']['team_id']);
     // Clean the password (remove it from the array)
     unset($userinfo['User']['password']);
     // Set the new information
     $this->Session->write($userinfo);
     $this->Session->write($teaminfo);
     // Update our arrays
     $this->userinfo = $userinfo['User'];
     $this->teaminfo = $teaminfo['Team'];
     $this->groupinfo = $teaminfo['Group'];
 }
开发者ID:ubnetdef,项目名称:injectengine,代码行数:41,代码来源:AppController.php

示例9: _generateRecords

 /**
  * Generate String representation of Records
  *
  * @param array $tableInfo Table schema array
  * @param int $recordCount The number of records to generate.
  * @return array Array of records to use in the fixture.
  */
 protected function _generateRecords($tableInfo, $recordCount = 1)
 {
     $records = array();
     for ($i = 0; $i < $recordCount; $i++) {
         $record = array();
         foreach ($tableInfo as $field => $fieldInfo) {
             if (empty($fieldInfo['type'])) {
                 continue;
             }
             $insert = '';
             switch ($fieldInfo['type']) {
                 case 'integer':
                 case 'float':
                     $insert = $i + 1;
                     break;
                 case 'string':
                 case 'binary':
                     $isPrimaryUuid = isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' && isset($fieldInfo['length']) && $fieldInfo['length'] == 36;
                     if ($isPrimaryUuid) {
                         $insert = CakeText::uuid();
                     } else {
                         $insert = "Lorem ipsum dolor sit amet";
                         if (!empty($fieldInfo['length'])) {
                             $insert = substr($insert, 0, (int) $fieldInfo['length'] - 2);
                         }
                     }
                     break;
                 case 'timestamp':
                     $insert = time();
                     break;
                 case 'datetime':
                     $insert = date('Y-m-d H:i:s');
                     break;
                 case 'date':
                     $insert = date('Y-m-d');
                     break;
                 case 'time':
                     $insert = date('H:i:s');
                     break;
                 case 'boolean':
                     $insert = 1;
                     break;
                 case 'text':
                     $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
                     $insert .= " Convallis morbi fringilla gravida,";
                     $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
                     $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
                     $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
                     $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
                     $insert .= " duis vestibulum nunc mattis convallis.";
                     break;
             }
             $record[$field] = $insert;
         }
         $records[] = $record;
     }
     return $records;
 }
开发者ID:galabyca,项目名称:nostalgames,代码行数:65,代码来源:FixtureTask.php

示例10: testWrapIndent

    /**
     * test wrap() indenting
     *
     * @return void
     */
    public function testWrapIndent()
    {
        $text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
        $result = CakeText::wrap($text, array('width' => 33, 'indent' => "\t", 'indentAt' => 1));
        $expected = <<<TEXT
This is the song that never ends.
\tThis is the song that never ends.
\tThis is the song that never ends.
TEXT;
        $this->assertTextEquals($expected, $result);
    }
开发者ID:keetamhoang,项目名称:lotdephong,代码行数:16,代码来源:CakeTextTest.php

示例11: generateAuthKey

 /**
  * Generate authorization hash.
  *
  * @return string Hash
  */
 public static function generateAuthKey()
 {
     return Security::hash(CakeText::uuid());
 }
开发者ID:hashimotoryoh,项目名称:Kinopy_SERVER,代码行数:9,代码来源:Security.php

示例12: _parseKey

 /**
  * Extracts a Model.field identifier and an SQL condition operator from a string, formats
  * and inserts values, and composes them into an SQL snippet.
  *
  * @param string $key An SQL key snippet containing a field and optional SQL operator
  * @param mixed $value The value(s) to be inserted in the string
  * @param Model $Model Model object initiating the query
  * @return string
  */
 protected function _parseKey($key, $value, Model $Model = null)
 {
     $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
     $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
     $bound = strpos($key, '?') !== false || is_array($value) && strpos($key, ':') !== false;
     $key = trim($key);
     if (strpos($key, ' ') === false) {
         $operator = '=';
     } else {
         list($key, $operator) = explode(' ', $key, 2);
         if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
             $key = $key . ' ' . $operator;
             $split = strrpos($key, ' ');
             $operator = substr($key, $split);
             $key = substr($key, 0, $split);
         }
     }
     $virtual = false;
     $type = null;
     if ($Model !== null) {
         if ($Model->isVirtualField($key)) {
             $key = $this->_quoteFields($Model->getVirtualField($key));
             $virtual = true;
         }
         $type = $Model->getColumnType($key);
     }
     $null = $value === null || is_array($value) && empty($value);
     if (strtolower($operator) === 'not') {
         $data = $this->conditionKeysToString(array($operator => array($key => $value)), true, $Model);
         return $data[0];
     }
     $value = $this->value($value, $type);
     if (!$virtual && $key !== '?') {
         $isKey = strpos($key, '(') !== false || strpos($key, ')') !== false || strpos($key, '|') !== false;
         $key = $isKey ? $this->_quoteFields($key) : $this->name($key);
     }
     if ($bound) {
         return CakeText::insert($key . ' ' . trim($operator), $value);
     }
     if (!preg_match($operatorMatch, trim($operator))) {
         $operator .= is_array($value) ? ' IN' : ' =';
     }
     $operator = trim($operator);
     if (is_array($value)) {
         $value = implode(', ', $value);
         switch ($operator) {
             case '=':
                 $operator = 'IN';
                 break;
             case '!=':
             case '<>':
                 $operator = 'NOT IN';
                 break;
         }
         $value = "({$value})";
     } elseif ($null || $value === 'NULL') {
         switch ($operator) {
             case '=':
                 $operator = 'IS';
                 break;
             case '!=':
             case '<>':
                 $operator = 'IS NOT';
                 break;
         }
     }
     if ($virtual) {
         return "({$key}) {$operator} {$value}";
     }
     return "{$key} {$operator} {$value}";
 }
开发者ID:ogontaro,项目名称:elites-output,代码行数:80,代码来源:DboSource.php

示例13: getHeaders

 /**
  * Get list of headers
  *
  * ### Includes:
  *
  * - `from`
  * - `replyTo`
  * - `readReceipt`
  * - `returnPath`
  * - `to`
  * - `cc`
  * - `bcc`
  * - `subject`
  *
  * @param array $include List of headers.
  * @return array
  */
 public function getHeaders($include = array())
 {
     if ($include == array_values($include)) {
         $include = array_fill_keys($include, true);
     }
     $defaults = array_fill_keys(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), false);
     $include += $defaults;
     $headers = array();
     $relation = array('from' => 'From', 'replyTo' => 'Reply-To', 'readReceipt' => 'Disposition-Notification-To', 'returnPath' => 'Return-Path');
     foreach ($relation as $var => $header) {
         if ($include[$var]) {
             $var = '_' . $var;
             $headers[$header] = current($this->_formatAddress($this->{$var}));
         }
     }
     if ($include['sender']) {
         if (key($this->_sender) === key($this->_from)) {
             $headers['Sender'] = '';
         } else {
             $headers['Sender'] = current($this->_formatAddress($this->_sender));
         }
     }
     foreach (array('to', 'cc', 'bcc') as $var) {
         if ($include[$var]) {
             $classVar = '_' . $var;
             $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
         }
     }
     $headers += $this->_headers;
     if (!isset($headers['X-Mailer'])) {
         $headers['X-Mailer'] = static::EMAIL_CLIENT;
     }
     if (!isset($headers['Date'])) {
         $headers['Date'] = date(DATE_RFC2822);
     }
     if ($this->_messageId !== false) {
         if ($this->_messageId === true) {
             $headers['Message-ID'] = '<' . str_replace('-', '', CakeText::UUID()) . '@' . $this->_domain . '>';
         } else {
             $headers['Message-ID'] = $this->_messageId;
         }
     }
     if ($include['subject']) {
         $headers['Subject'] = $this->_subject;
     }
     $headers['MIME-Version'] = '1.0';
     if (!empty($this->_attachments)) {
         $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
     } elseif ($this->_emailFormat === 'both') {
         $headers['Content-Type'] = 'multipart/alternative; boundary="' . $this->_boundary . '"';
     } elseif ($this->_emailFormat === 'text') {
         $headers['Content-Type'] = 'text/plain; charset=' . $this->_getContentTypeCharset();
     } elseif ($this->_emailFormat === 'html') {
         $headers['Content-Type'] = 'text/html; charset=' . $this->_getContentTypeCharset();
     }
     $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
     return $headers;
 }
开发者ID:xplico,项目名称:CapAnalysis,代码行数:75,代码来源:CakeEmail.php

示例14: classicExtract

 /**
  * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.:
  * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal,
  * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as
  * a regular expression.
  *
  * @param array $data Array from where to extract
  * @param string|array $path As an array, or as a dot-separated string.
  * @return mixed An array of matched items or the content of a single selected item or null in any of these cases: $path or $data are null, no items found.
  * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::classicExtract
  */
 public static function classicExtract($data, $path = null)
 {
     if (empty($path)) {
         return $data;
     }
     if (is_object($data)) {
         if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
             $data = get_object_vars($data);
         }
     }
     if (empty($data)) {
         return null;
     }
     if (is_string($path) && strpos($path, '{') !== false) {
         $path = CakeText::tokenize($path, '.', '{', '}');
     } elseif (is_string($path)) {
         $path = explode('.', $path);
     }
     $tmp = array();
     if (empty($path)) {
         return null;
     }
     foreach ($path as $i => $key) {
         if (is_numeric($key) && (int) $key > 0 || $key === '0') {
             if (isset($data[$key])) {
                 $data = $data[$key];
             } else {
                 return null;
             }
         } elseif ($key === '{n}') {
             foreach ($data as $j => $val) {
                 if (is_int($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif ($key === '{s}') {
             foreach ($data as $j => $val) {
                 if (is_string($j)) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[] = $val;
                     } else {
                         $tmp[] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } elseif (strpos($key, '{') !== false && strpos($key, '}') !== false) {
             $pattern = substr($key, 1, -1);
             foreach ($data as $j => $val) {
                 if (preg_match('/^' . $pattern . '/s', $j) !== 0) {
                     $tmpPath = array_slice($path, $i + 1);
                     if (empty($tmpPath)) {
                         $tmp[$j] = $val;
                     } else {
                         $tmp[$j] = Set::classicExtract($val, $tmpPath);
                     }
                 }
             }
             return $tmp;
         } else {
             if (isset($data[$key])) {
                 $data = $data[$key];
             } else {
                 return null;
             }
         }
     }
     return $data;
 }
开发者ID:angel-mendoza,项目名称:proyecto-pasantia,代码行数:87,代码来源:Set.php

示例15: extract

 /**
  * Gets the values from an array matching the $path expression.
  * The path expression is a dot separated expression, that can contain a set
  * of patterns and expressions:
  *
  * - `{n}` Matches any numeric key, or integer.
  * - `{s}` Matches any string key.
  * - `{*}` Matches any value.
  * - `Foo` Matches any key with the exact same value.
  *
  * There are a number of attribute operators:
  *
  *  - `=`, `!=` Equality.
  *  - `>`, `<`, `>=`, `<=` Value comparison.
  *  - `=/.../` Regular expression pattern match.
  *
  * Given a set of User array data, from a `$User->find('all')` call:
  *
  * - `1.User.name` Get the name of the user at index 1.
  * - `{n}.User.name` Get the name of every user in the set of users.
  * - `{n}.User[id]` Get the name of every user with an id key.
  * - `{n}.User[id>=2]` Get the name of every user with an id key greater than or equal to 2.
  * - `{n}.User[username=/^paul/]` Get User elements with username matching `^paul`.
  *
  * @param array  $data The data to extract from.
  * @param string $path The path to extract.
  *
  * @return array An array of the extracted values. Returns an empty array
  *   if there are no matches.
  * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::extract
  */
 public static function extract(array $data, $path)
 {
     if (empty($path)) {
         return $data;
     }
     // Simple paths.
     if (!preg_match('/[{\\[]/', $path)) {
         return (array) static::get($data, $path);
     }
     if (strpos($path, '[') === FALSE) {
         $tokens = explode('.', $path);
     } else {
         $tokens = CakeText::tokenize($path, '.', '[', ']');
     }
     $_key = '__set_item__';
     $context = array($_key => array($data));
     foreach ($tokens as $token) {
         $next = array();
         list($token, $conditions) = static::_splitConditions($token);
         foreach ($context[$_key] as $item) {
             foreach ((array) $item as $k => $v) {
                 if (static::_matchToken($k, $token)) {
                     $next[] = $v;
                 }
             }
         }
         // Filter for attributes.
         if ($conditions) {
             $filter = array();
             foreach ($next as $item) {
                 if (is_array($item) && static::_matches($item, $conditions)) {
                     $filter[] = $item;
                 }
             }
             $next = $filter;
         }
         $context = array($_key => $next);
     }
     return $context[$_key];
 }
开发者ID:mrbadao,项目名称:api-official,代码行数:71,代码来源:Hash.php


注:本文中的CakeText类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。