/** @test */
 public function testHasNext()
 {
     $it = new CachingIterator(range(1, 5));
     $this->assertTrue($it->hasNext());
     $it = new CachingIterator(new EmptyIterator());
     $this->assertFalse($it->hasNext());
 }
Beispiel #2
0
Datei: Room.php Projekt: cwcw/cms
 /**
  * Array representation of this object (to be used in conjunction with the PLAY signal)
  *
  * @return array
  */
 public function toArray()
 {
     $filename = self::FT_ROOM;
     if (!empty($this->_roomOptions)) {
         $filename .= '/';
         $it = new CachingIterator(new ArrayIterator($this->_roomOptions));
         foreach ($it as $name => $value) {
             $filename .= $name . '=' . $value;
             if ($it->hasNext()) {
                 $filename .= ',';
             }
         }
     }
     $filename .= ':' . $this->_name;
     $ret = array(self::ARR_FILENAME => $filename, self::ARR_TYPE => $this->_channel);
     if (null !== $this->_transition) {
         $ret[self::ARR_TRANS] = $this->_transition;
     }
     return $ret;
 }
 /**
  * Parses a Zone line.
  *
  * @param $s \CachingIterator the line scanner, not null
  * @param $zoneList
  * @return true if the zone is complete
  */
 private function parseZoneLine(\CachingIterator $s, &$zoneList)
 {
     $zone = new TZDBZone();
     $zoneList[] = $zone;
     $s->next();
     $zone->standardOffset = $this->parseOffset($s->current());
     $s->next();
     $savingsRule = $this->parseOptional($s->current());
     if ($savingsRule === null) {
         $zone->fixedSavingsSecs = 0;
         $zone->savingsRule = null;
     } else {
         try {
             $zone->fixedSavingsSecs = $this->parsePeriod($savingsRule);
             $zone->savingsRule = null;
         } catch (\Exception $ex) {
             $zone->fixedSavingsSecs = null;
             $zone->savingsRule = $savingsRule;
         }
     }
     $s->next();
     $zone->text = $s->current();
     if ($s->hasNext()) {
         $s->next();
         $zone->year = intval($s->current());
         if ($s->hasNext()) {
             $this->parseMonthDayTime($s, $zone);
         }
         return false;
     } else {
         return true;
     }
 }
Beispiel #4
0
 /**
  * Detect format
  *
  * Detect which format should be used to output the data
  *
  * @return  string
  */
 protected function _detect_format()
 {
     // A format has been passed as an argument in the URL and it is supported
     if (\Input::param('format') and $this->_supported_formats[\Input::param('format')]) {
         return \Input::param('format');
     }
     // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed)
     if ($acceptable = \Input::server('HTTP_ACCEPT') and \Config::get('rest.ignore_http_accept') !== true) {
         // If anything is accepted, and we have a default, return that
         if ($acceptable == '*/*' and !empty($this->rest_format)) {
             return $this->rest_format;
         }
         // Split the Accept header and build an array of quality scores for each format
         $fragments = new \CachingIterator(new \ArrayIterator(preg_split('/[,;]/', \Input::server('HTTP_ACCEPT'))));
         $acceptable = array();
         $next_is_quality = false;
         foreach ($fragments as $fragment) {
             $quality = 1;
             // Skip the fragment if it is a quality score
             if ($next_is_quality) {
                 $next_is_quality = false;
                 continue;
             } elseif ($fragments->hasNext()) {
                 $next = $fragments->getInnerIterator()->current();
                 if (strpos($next, 'q=') === 0) {
                     list($key, $quality) = explode('=', $next);
                     $next_is_quality = true;
                 }
             }
             $acceptable[$fragment] = $quality;
         }
         // Sort the formats by score in descending order
         uasort($acceptable, function ($a, $b) {
             $a = (double) $a;
             $b = (double) $b;
             return $a > $b ? -1 : 1;
         });
         // Check each of the acceptable formats against the supported formats
         foreach ($acceptable as $pattern => $quality) {
             // The Accept header can contain wildcards in the format
             $find = array('*', '/');
             $replace = array('.*', '\\/');
             $pattern = '/^' . str_replace($find, $replace, $pattern) . '$/';
             foreach ($this->_supported_formats as $format => $mime) {
                 if (preg_match($pattern, $mime)) {
                     return $format;
                 }
             }
         }
     }
     // End HTTP_ACCEPT checking
     // Well, none of that has worked! Let's see if the controller has a default
     if (!empty($this->rest_format)) {
         return $this->rest_format;
     }
     // Just use the default format
     return \Config::get('rest.default_format');
 }
Beispiel #5
0
 /**
  * Add wildcards to the given URI.
  *
  * @param  string  $uri
  * @return string
  */
 public function addUriWildcards($uri, $reflection, $method)
 {
     $refAction = $reflection->getReflectionClass()->getMethod($method);
     $app = Application::instance();
     $parameter = '';
     $patterns = $app->router->getPattern();
     $arguments = new \CachingIterator(new \ArrayIterator($refAction->getParameters()));
     foreach ($arguments as $key => $param) {
         if (!$param->isOptional()) {
             if (array_key_exists('{:' . $param->getName() . '}', $patterns)) {
                 $slash = $arguments->hasNext() ? '/' : '';
                 $parameter .= '{:' . $param->getName() . '}' . $slash;
             }
         }
     }
     return $uri . '/' . $parameter;
 }
<?php

/**
 * Előre tekintés
 */
$data = new ArrayObject(range(0, 9));
$iterator = new CachingIterator($data->getIterator(), CachingIterator::FULL_CACHE);
foreach ($iterator as $key => $value) {
    printf("Key %s => Value %s, Current %s, HasNext %b, Next %s\n", $key, $value, $iterator->current(), $iterator->hasNext(), $iterator->getInnerIterator()->current());
    var_dump($iterator->getCache());
}
 /**
  * @return mixed
  */
 public function getSql()
 {
     $query = 'SELECT ';
     if (!$this->select || !$this->from) {
         throw new \RuntimeException();
     }
     $ait = new \ArrayIterator($this->select);
     $cit = new \CachingIterator($ait);
     foreach ($cit as $select) {
         $query .= " " . $select;
         if ($cit->hasNext()) {
             $query .= ", ";
         }
     }
     $query .= " FROM " . $this->from . " ";
     if (!$this->ignoreJoins) {
         foreach ($this->joins as $join) {
             $query .= " " . $join;
         }
     }
     if ($this->wheres && !$this->ignoreWheres) {
         $query .= " WHERE ";
         $ait = new \ArrayIterator($this->wheres);
         $cit = new \CachingIterator($ait);
         foreach ($cit as $where) {
             $query .= " " . $where;
             if ($cit->hasNext()) {
                 $query .= " AND ";
             }
         }
     }
     if ($this->groupBy && !$this->ignoreGroupBy) {
         $query .= " GROUP BY ";
         $query .= implode(',', $this->groupBy);
     }
     if ($this->having && !$this->ignoreHaving) {
         $query .= " HAVING ";
         $query .= implode(',', $this->having);
     }
     if ($this->orders && !$this->ignoreOrderBy) {
         $query .= " ORDER BY ";
         $count = count($this->orders);
         $i = 1;
         foreach ($this->orders as $key => $order) {
             $query .= " " . $order['order'] . " " . $order['sort'];
             if ($count > $i) {
                 $query .= ", ";
             }
             $i++;
         }
     }
     if ($this->getLimit() && !$this->getIgnoreLimit()) {
         $query .= " LIMIT " . $this->getLimit();
         if ($this->getOffset() && !$this->getIgnoreOffset()) {
             $query .= " OFFSET " . $this->getOffset();
         }
     }
     return $query;
 }
Beispiel #8
0
 public function get($table, $fields, array $where = null, $order = null, $limit = null, $cache = null, array $options = null)
 {
     if (!is_array($table)) {
         $table = [$table];
     }
     if (!isset($options['prefix_tables']) || $options['prefix_tables'] === true) {
         array_walk($table, function (&$v, &$k) {
             if (strlen($v) < 7 || substr($v, 0, 7) != ':table_') {
                 $v = ':table_' . $v;
             }
         });
     }
     if (!is_array($fields)) {
         $fields = [$fields];
     }
     if (isset($order) && !is_array($order)) {
         $order = [$order];
     }
     if (isset($limit)) {
         if (is_array($limit) && count($limit) === 2 && is_numeric($limit[0]) && is_numeric($limit[1])) {
             $limit = implode(', ', $limit);
         } elseif (!is_numeric($limit)) {
             $limit = null;
         }
     }
     $statement = 'select ' . implode(', ', $fields) . ' from ' . implode(', ', $table);
     if (!isset($where) && !isset($cache)) {
         if (isset($order)) {
             $statement .= ' order by ' . implode(', ', $order);
         }
         return $this->query($statement);
     }
     if (isset($where)) {
         $statement .= ' where ';
         $counter = 0;
         $it_where = new \CachingIterator(new \ArrayIterator($where), \CachingIterator::TOSTRING_USE_CURRENT);
         foreach ($it_where as $key => $value) {
             if (is_array($value)) {
                 if (isset($value['val'])) {
                     $statement .= $key . ' ' . (isset($value['op']) ? $value['op'] : '=') . ' :cond_' . $counter;
                 }
                 if (isset($value['rel'])) {
                     if (isset($value['val'])) {
                         $statement .= ' and ';
                     }
                     if (is_array($value['rel'])) {
                         $it_rel = new \CachingIterator(new \ArrayIterator($value['rel']), \CachingIterator::TOSTRING_USE_CURRENT);
                         foreach ($it_rel as $rel) {
                             $statement .= $key . ' = ' . $rel;
                             if ($it_rel->hasNext()) {
                                 $statement .= ' and ';
                             }
                         }
                     } else {
                         $statement .= $key . ' = ' . $value['rel'];
                     }
                 }
             } else {
                 $statement .= $key . ' = :cond_' . $counter;
             }
             if ($it_where->hasNext()) {
                 $statement .= ' and ';
             }
             $counter++;
         }
     }
     if (isset($order)) {
         $statement .= ' order by ' . implode(', ', $order);
     }
     if (isset($limit)) {
         $statement .= ' limit ' . $limit;
     }
     $Q = $this->prepare($statement);
     if (isset($where)) {
         $counter = 0;
         foreach ($it_where as $value) {
             if (is_array($value)) {
                 if (isset($value['val'])) {
                     $Q->bindValue(':cond_' . $counter, $value['val']);
                 }
             } else {
                 $Q->bindValue(':cond_' . $counter, $value);
             }
             $counter++;
         }
     }
     if (isset($cache)) {
         if (!is_array($cache)) {
             $cache = [$cache];
         }
         call_user_func_array([$Q, 'setCache'], $cache);
     }
     $Q->execute();
     return $Q;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dwarves = [1 => 'Grumpy', 2 => 'Happy', 3 => 'Sleepy', 4 => 'Bashful', 5 => 'Sneezy', 6 => 'Dopey', 7 => 'Doc'];
     $output->writeln('Look ahead exampe. Build a CSV the hard way.');
     $dwarfIterator = new \ArrayIterator($dwarves);
     $cachingDwarfIterator = new \CachingIterator($dwarfIterator);
     $dwarfListOutput = '';
     foreach ($cachingDwarfIterator as $thisDwarf) {
         $dwarfListOutput .= $thisDwarf;
         if ($cachingDwarfIterator->hasNext()) {
             $dwarfListOutput .= ',';
         }
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln($dwarfListOutput);
     $output->writeln(' ');
     $dwarfIterator = null;
     $cachingDwarfIterator = null;
     $output->writeln('Set the TOSTRING_USE_KEY flag');
     $dwarfIterator = new \ArrayIterator($dwarves);
     $cachingDwarfIterator = new \CachingIterator($dwarfIterator, \CachingIterator::TOSTRING_USE_KEY);
     foreach ($cachingDwarfIterator as $key => $thisDwarf) {
         var_dump((string) $cachingDwarfIterator);
         echo "\n";
     }
     // foreach($dwarfIterator as $thisDwarf)
     $dwarfIterator = null;
     $cachingDwarfIterator = null;
     $output->writeln(' ');
     $output->writeln('Setting the TOSTRING_USE_CURRENT flag');
     $dwarfIterator = new \ArrayIterator($dwarves);
     $cachingDwarfIterator = new \CachingIterator($dwarfIterator, \CachingIterator::TOSTRING_USE_CURRENT);
     foreach ($cachingDwarfIterator as $key => $thisDwarf) {
         var_dump((string) $cachingDwarfIterator);
         echo "\n";
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln(' ');
     $output->writeln('Setting the TOSTRING_USE_INNER flag');
     $dwarfIterator = new CustomArrayIterator($dwarves);
     $cachingDwarfIterator = new \CachingIterator($dwarfIterator, \CachingIterator::TOSTRING_USE_INNER);
     foreach ($cachingDwarfIterator as $key => $thisDwarf) {
         var_dump((string) $cachingDwarfIterator);
         echo "\n";
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln(' ');
     $output->writeln('Setting the FULL_CACHE flag');
     $dwarfIterator = new \ArrayIterator($dwarves);
     $cachingDwarfIterator = new CustomCachingIterator($dwarfIterator, \CachingIterator::FULL_CACHE);
     // Load the cache;
     foreach ($cachingDwarfIterator as $thisDwarf) {
     }
     $cachingDwarfIterator->removeBashful();
     $output->writeln(' ');
     $output->writeln('  Cached');
     foreach ($cachingDwarfIterator->getCache() as $key => $thisDwarf) {
         $output->writeln($key . " : " . $thisDwarf);
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln(' ');
     $output->writeln('  This is the original iterator');
     foreach ($cachingDwarfIterator as $key => $thisDwarf) {
         $output->writeln($key . " - " . $thisDwarf);
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln(' ');
     $output->writeln("  Now that we've modified an element, \n  let's modify an element");
     $dwarfIterator = new \ArrayIterator($dwarves);
     $cachingDwarfIterator = new \CachingIterator($dwarfIterator, \CachingIterator::FULL_CACHE);
     // Load the cache;
     foreach ($cachingDwarfIterator as $thisDwarf) {
     }
     $cachingDwarfIterator[5] = 'Surley';
     $output->writeln(' ');
     $output->writeln('  Now let\'s out the inner cache');
     foreach ($cachingDwarfIterator->getCache() as $key => $thisDwarf) {
         $output->writeln($key . " : " . $thisDwarf);
     }
     // foreach($dwarfIterator as $thisDwarf)
     $output->writeln("Done");
     return;
 }
Beispiel #10
0
 /**
  * @author Damien Lasserre <*****@*****.**>
  * @param $tableName
  * @param array $update
  * @param Where $where
  * @return bool
  */
 public function update($tableName, array $update, Where $where = null)
 {
     $this->_query = 'UPDATE ' . $tableName . ' SET ';
     /** @var \CachingIterator $iterator */
     $iterator = new \CachingIterator(new \ArrayIterator($update));
     foreach ($iterator as $column => $value) {
         $this->_query .= ' ' . $column . ' = ' . $value;
         if ($iterator->hasNext()) {
             $this->_query .= ', ';
         }
     }
     if (null !== $where) {
         $this->where($where);
     }
     /** @var \PDOStatement $statement */
     $statement = $this->_db->prepare($this->_query);
     if ($statement->execute($this->_binding)) {
         /** Return */
         return true;
     }
     /** Return */
     return false;
 }
Beispiel #11
0
 public static function selectField($name, array $values, $default = null, $parameters = '', $required = false, $class = 'form-control')
 {
     $group = false;
     $field = '<select name="' . static::output($name) . '"';
     if ($required == true) {
         $field .= ' required aria-required="true"';
     }
     if (!empty($parameters)) {
         $field .= ' ' . $parameters;
     }
     if (!empty($class)) {
         $field .= ' class="' . $class . '"';
     }
     $field .= '>';
     if ($required == true) {
         $field .= '<option value="">' . OSCOM::getDef('pull_down_default') . '</option>';
     }
     if (empty($default) && (isset($_GET[$name]) && is_string($_GET[$name]) || isset($_POST[$name]) && is_string($_POST[$name]))) {
         if (isset($_GET[$name]) && is_string($_GET[$name])) {
             $default = $_GET[$name];
         } elseif (isset($_POST[$name]) && is_string($_POST[$name])) {
             $default = $_POST[$name];
         }
     }
     $ci = new \CachingIterator(new \ArrayIterator($values), \CachingIterator::TOSTRING_USE_CURRENT);
     // used for hasNext() below
     foreach ($ci as $v) {
         if (isset($v['group'])) {
             if ($group != $v['group']) {
                 $group = $v['group'];
                 $field .= '<optgroup label="' . static::output($v['group']) . '">';
             }
         }
         $field .= '<option value="' . static::output($v['id']) . '"';
         if (isset($default) && $v['id'] == $default) {
             $field .= ' selected="selected"';
         }
         if (isset($v['params'])) {
             $field .= ' ' . $v['params'];
         }
         $field .= '>' . static::output($v['text'], ['"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;']) . '</option>';
         if ($group !== false && ($group != $v['group'] || $ci->hasNext() === false)) {
             $group = false;
             $field .= '</optgroup>';
         }
     }
     $field .= '</select>';
     return $field;
 }
Beispiel #12
0
 /**
  * @update a table
  *
  * @access public
  *
  * @param string $condition
  *
  */
 public function updateWithCondition($condition, $values = NULL)
 {
     $values = is_null($values) ? $this->values : $values;
     try {
         // get the primary key/
         $pk = $this->_primary_key;
         $obj = new CachingIterator(new ArrayIterator($values));
         $sql = "UPDATE {$this->_table_name} SET \n";
         foreach ($obj as $field => $val) {
             $sql .= "{$field} = :{$field}";
             $sql .= $obj->hasNext() ? ',' : '';
             $sql .= "\n";
         }
         $sql .= " WHERE {$condition}";
         $stmt = $this->_conn->prepare($sql);
         // bind the params
         foreach ($values as $k => $v) {
             $stmt->bindParam(':' . $k, $v);
         }
         // bind the primary key and the id
         $stmt->execute($values);
         // return the affected rows
         return $stmt->rowCount();
     } catch (Exception $e) {
         $this->errors[] = $e->getMessage();
     }
 }
Beispiel #13
0
 /**
  * Array representation of this object (to be used in conjunction with the PLAY signal)
  *
  * @return array
  */
 public function toArray()
 {
     $filename = '';
     $hasPlayingOptions = !empty($this->_playingOptions);
     if ($hasPlayingOptions) {
         if (null === $this->_forcedType) {
             $filename = sprintf('file-%s/', $this->_extension);
         } else {
             $filename = sprintf('%s/', $this->_forcedType);
         }
         $it = new CachingIterator(new ArrayIterator($this->_playingOptions));
         foreach ($it as $opt => $val) {
             $filename .= sprintf('%s=%s', $opt, $val);
             if ($it->hasNext()) {
                 $filename .= ',';
             }
         }
         $filename .= ':';
     } else {
         if (null !== $this->_forcedType) {
             $filename = sprintf('%s:', $this->_forcedType);
         }
     }
     $filename .= $this->_folder . DIRECTORY_SEPARATOR . $this->_name;
     $ret = array(self::ARR_FILENAME => $filename);
     $ret[self::ARR_TYPE] = $this->_channel;
     if (null !== $this->_transition) {
         $ret[self::ARR_TRANS] = $this->_transition;
     }
     return $ret;
 }
Beispiel #14
0
    var_dump($simpleIt->xpath('animal/category/species'));
} catch (Exception $e) {
    echo $e->getMessage();
}
echo '--------------------------------- SimpleXMLIterator END-----------------------------------', '<br />';
echo '--------------------------------- CachingIterator START-----------------------------------', '<br />';
/**
 * CachingIterator 提前读取一个元素
 * 可以用于确定当前元素是否为最后一个元素
 */
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');
try {
    $cachingIt = new CachingIterator(new ArrayIterator($array));
    foreach ($cachingIt as $item) {
        echo $item;
        if ($cachingIt->hasNext()) {
            echo ',';
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
echo '----------------------------------- CachingIterator END ---------------------------------', '<br />';
echo '--------------------------------- LimitIterator END-----------------------------------', '<br />';
/**
 * LimitIterator 遍历一个Iterator的限定子集
 * 在__construct有两个可选参数:offset 和 count
 */
$array = array('apple', 'banana', 'cherry', 'damson', 'elderberry');
$fruits = new ArrayIterator($array);
$offset = 3;
Beispiel #15
0
 public function Save()
 {
     $conn = Db::getInstance();
     // Creating a new booking with all of the chosen data
     $statement = $conn->prepare("INSERT INTO tbl_booking(fk_advert_id, fk_booker_user_id, fk_renter_user_id, booking_number_spots, booking_price, booking_extra_information, booking_status) VALUES (:AdvertId, :BookerUserId, :RenterUserId, :NumberSpots, :Price, :ExtraInformation, 'pending')");
     $statement->bindValue(':AdvertId', $this->AdvertId);
     $statement->bindValue(':BookerUserId', $this->BookerUserId);
     $statement->bindValue(':RenterUserId', $this->RenterUserId);
     $statement->bindValue(':NumberSpots', $this->NumberSpots);
     $statement->bindValue(':Price', $this->Price);
     $statement->bindValue(':ExtraInformation', $this->ExtraInformation);
     $statement->execute();
     // Retrieving the last created booking_id and saving the booked date related to the newly created booking
     $last_created_booking_id = $conn->lastInsertId();
     $statement = $conn->prepare("INSERT INTO tbl_booking_date(fk_booking_id, booking_date_format) VALUES (:BookingId, :BookingDate)");
     $statement->bindValue(':BookingId', $last_created_booking_id);
     $statement->bindValue(':BookingDate', $this->Date);
     $statement->execute();
     // Saving all of chosen children related to the newly created booking
     $selected_children_query = "INSERT INTO tbl_booking_child(fk_booking_id, fk_child_id) VALUES ";
     $selected_children_iterator = new ArrayIterator($this->ChildId);
     $selected_children_cachingiterator = new CachingIterator($selected_children_iterator);
     foreach ($selected_children_cachingiterator as $value) {
         $selected_children_query .= "({$last_created_booking_id}, " . $selected_children_cachingiterator->current() . ")";
         if ($selected_children_cachingiterator->hasNext()) {
             $selected_children_query .= ", ";
         }
     }
     $statement = $conn->prepare($selected_children_query);
     $statement->execute();
     // Saving all of the chosen services related to the newly created booking
     $selected_services_query = "INSERT INTO tbl_booking_service(fk_booking_id, fk_service_id) VALUES ";
     $selected_services_iterator = new ArrayIterator($this->ServiceId);
     $selected_services_cachingiterator = new CachingIterator($selected_services_iterator);
     foreach ($selected_services_cachingiterator as $value) {
         $selected_services_query .= "({$last_created_booking_id}, " . $selected_services_cachingiterator->current() . ")";
         if ($selected_services_cachingiterator->hasNext()) {
             $selected_services_query .= ", ";
         }
     }
     $statement = $conn->prepare($selected_services_query);
     $statement->execute();
 }
Beispiel #16
0
 public function pages($config = array())
 {
     $config = new Library\ObjectConfig($config);
     $config->append(array('pages' => array(), 'active' => null, 'attribs' => array('class' => array('nav'))));
     $result = '';
     $first = true;
     $last_level = 0;
     $pages = clone $config->pages;
     // We use a CachingIterator to peek ahead to the next item so that we can properly close elements
     $collection = new \CachingIterator($pages->getIterator(), \CachingIterator::TOSTRING_USE_KEY);
     foreach ($collection as $page) {
         $next_page = null;
         if ($collection->hasNext()) {
             $next_page = $collection->getInnerIterator()->current();
         }
         $next_level = is_object($next_page) ? count(explode('/', $next_page->path)) : false;
         $level = count(explode('/', $page->path));
         // Start a new level
         if ($level > $last_level) {
             $attributes = $first ? ' ' . $this->buildAttributes($config->attribs) : '';
             $result .= "<ul{$attributes}>";
             // Used to put the title in the menu
             if ($first && $config->title) {
                 $result .= '<li class="nav-header">' . $config->title . "</li>";
             }
             $first = false;
         }
         $classes = array();
         if ($config->active) {
             if (in_array($page->id, array_merge($config->active->getParentIds(), (array) $config->active->id))) {
                 $classes[] = 'active';
             }
             if ($page->id == $config->active->id) {
                 $classes[] = 'current';
             }
             foreach ($config->pages as $value) {
                 if (strpos($value->path, $page->path . '/') === 0) {
                     $classes[] = 'parent';
                     break;
                 }
             }
         }
         if ($page->type == 'separator') {
             $classes[] = 'nav-header';
         }
         $result .= '<li' . ($classes ? ' class="' . implode(' ', $classes) . '"' : '') . ">";
         switch ($page->type) {
             case 'component':
                 $link = $this->getTemplate()->getView()->getRoute($page->getLink()->getQuery());
                 $result .= '<a href="' . (string) $link . '">';
                 $result .= $page->title;
                 $result .= '</a>';
                 break;
             case 'menulink':
                 $page_linked = $this->getObject('application.pages')->getPage($page->getLink()->query['Itemid']);
                 $result .= '<a href="' . $page_linked->getLink() . '">';
                 $result .= $page->title;
                 $result .= '</a>';
                 break;
             case 'separator':
                 $result .= '<span class="separator ' . ($config->disabled ? 'nolink' : '') . '">' . $page->title . '</span>';
                 break;
             case 'url':
                 $result .= '<a href="' . $page->getLink() . '">';
                 $result .= $page->title;
                 $result .= '</a>';
                 break;
             case 'redirect':
                 $result .= '<a href="' . $page->route . '">';
                 $result .= $page->title;
                 $result .= '</a>';
         }
         //$result .= $level;
         if ($level < $next_level) {
             // don't close <li>
         } elseif ($level === $next_level) {
             $result .= "</li>";
         } elseif ($next_level === false || $level > $next_level) {
             // Last one of the level
             $result .= "</li>";
             for ($i = 0; $i < $level - $next_level; ++$i) {
                 if ($next_level === false) {
                     $result .= "</ul>";
                 } else {
                     $result .= "</ul></li>";
                 }
             }
         }
         $last_level = $level;
     }
     return $result;
 }
$ids = json_decode($jsonids, true);
// create db connection
$access = new dbAccess();
$access->openConnection();
// begin sql statement
$sql = "insert into notify (event_id, user_id, inviter_id) values ";
// iterate through $ids array for a single batch sql query
$iter = new ArrayIterator($ids);
// a new caching iterator gives us access to hasNext()
$citer = new CachingIterator($iter);
// loop over the array
foreach ($citer as $value) {
    // add to the query
    $sql .= "('" . $ids[$citer->key()]["event_id"] . "','" . $ids[$citer->key()]["user_id"] . "','" . $ids[$citer->key()]["inviter_id"] . "')";
    // if there is another array member, add a comma
    if ($citer->hasNext()) {
        $sql .= ",";
    }
}
// run query
$result = $access->conn->query($sql);
// report success if query succeeded
if (!empty($result)) {
    $returnValue["status"] = "Success";
    $returnValue["message"] = "Users invited";
    echo json_encode($returnValue);
} else {
    $returnValue["status"] = "error";
    $returnValue["message"] = $sql;
    echo json_encode($returnValue);
}
Beispiel #18
0
 /**
  * Обновление данных
  *
  * @param string $table Имя таблицы
  * @param array  $ Массив полей и значений
  * @param string $where  Условия обновления
  */
 public function update($table, $data = array(), $where = array())
 {
     $query = 'UPDATE ' . $this->tableName($table, 'table') . ' SET ';
     $it = $data instanceof Core_ArrayObject ? $data->getInnerIterator() : new ArrayIterator($data);
     $it = new CachingIterator($it);
     foreach ($it as $key => $value) {
         $query .= $key . ' = :' . $key;
         if ($it->hasNext()) {
             $query .= ', ';
         }
     }
     if ($where) {
         $this->where($where);
         $query .= ' WHERE ' . $this->chain['WHERE'];
     }
     $this->autoclear && $this->clear();
     $PDOStatement = $this->PDO->prepare($query);
     $exec_data = array();
     foreach ($data as $key => $value) {
         $exec_data[':' . $key] = $value;
     }
     try {
         $i = $this->log(str_replace(array_keys($exec_data), array_values($exec_data), (string) $PDOStatement->queryString));
         bench('db.query.' . $i . '.start');
         if ($PDOStatement->execute($exec_data)) {
             bench('db.query.' . $i . '.end');
             return TRUE;
         } else {
             $this->setError($PDOStatement);
         }
     } catch (PDOException $e) {
         $this->error($e->getMessage());
     }
     return FALSE;
 }
Beispiel #19
0
 $query[] = sprintf('SELECT * FROM "%s"', $table);
 if (isset($id) === true) {
     $query[] = sprintf('WHERE "%s" = ? LIMIT 1', 'id');
 } else {
     if (isset($_GET['where'])) {
         $query[] = 'WHERE';
         $wheres = $_GET['where'];
         foreach ($iter = new CachingIterator(new ArrayIterator($wheres), CachingIterator::TOSTRING_USE_KEY) as $where) {
             if (count(array_diff(['col', 'op', 'val'], array_keys($where))) !== 0) {
                 error_log('Invalid where filters. All filters must define the following keys: `col`, `op`, `val`');
                 exit(ArrestDB::Reply(ArrestDB::$HTTP[400]));
             }
             $column = $where['col'];
             $operator = $where['op'];
             $data[] = $where['val'];
             $query[] = sprintf('"%s" %s ? %s', $column, $operator, $iter->hasNext() ? 'AND' : '');
         }
     }
     $countQuery = str_replace('SELECT *', 'SELECT COUNT(*)', sprintf('%s;', implode(' ', $query)));
     $count = intval(array_shift(array_values(array_shift(ArrestDB::Query($countQuery, $data)))));
     if (isset($_GET['by']) === true) {
         if (isset($_GET['order']) !== true) {
             $_GET['order'] = 'ASC';
         }
         $query[] = sprintf('ORDER BY "%s" %s', $_GET['by'], $_GET['order']);
     }
     if (isset($_GET['limit']) === true) {
         $query[] = sprintf('LIMIT %u', $_GET['limit']);
         if (isset($_GET['offset']) === true) {
             $query[] = sprintf('OFFSET %u', $_GET['offset']);
         }
Beispiel #20
0
 public function Save()
 {
     $conn = Db::getInstance();
     // Creating a new advert and updating the contact-information of the creator
     $advert_query = "INSERT INTO tbl_advert(fk_user_id, advert_description, advert_price, advert_spots, advert_school, advert_transport) VALUES ('{$this->UserId}', '{$this->Description}', '{$this->Price}', '{$this->NumberChildren}', '{$this->School}', '{$this->Transportation}');";
     $advert_query .= "UPDATE tbl_user SET user_mobile_number = '{$this->MobileNumber}', user_home_number = '{$this->HomeNumber}', user_adress = '{$this->HomeAdress}', user_city = '{$this->HomeCity}' WHERE user_id = '{$this->UserId}';";
     $statement = $conn->prepare($advert_query);
     $statement->execute();
     // Gathering the last created advert id and saving all chosen services corresponding to the newly created advert
     $last_created_id = $conn->lastInsertId();
     $services_dates_query = "";
     $services_dates_query .= "INSERT INTO tbl_service(fk_advert_id, service_name) VALUES ";
     $iterator = new ArrayIterator($this->Services);
     $cachingiterator = new CachingIterator($iterator);
     foreach ($cachingiterator as $value) {
         $services_dates_query .= "('{$last_created_id}', '" . $cachingiterator->current() . "')";
         if ($cachingiterator->hasNext()) {
             $services_dates_query .= ", ";
         }
     }
     $services_dates_query .= "; ";
     // Saving all chosen dates and timestamps corresponding to the newly created advert
     $services_dates_query .= "INSERT INTO tbl_availability(fk_advert_id, availability_date, availability_time_start, availability_time_end, availability_spots) VALUES ";
     foreach ($this->AvailableDates as $key => $d) {
         $services_dates_query .= "('{$last_created_id}', '" . $d . "', '" . $this->AvailableStartTimes[$key] . "', '" . $this->AvailableEndTimes[$key] . "', '" . $this->NumberChildren . "'), ";
     }
     $services_dates_query = rtrim($services_dates_query, ', ') . ";";
     $statement = $conn->prepare($services_dates_query);
     $statement->execute();
     // Saving all newly added children corresponding to the creator of the advert
     $children_information_query = "INSERT INTO tbl_child(child_first_name, child_last_name, child_school, child_class) VALUES ";
     $number_children_created = 0;
     foreach ($this->ChildFirstName as $key => $c) {
         $children_information_query .= "('" . $c . "', '" . $this->ChildLastName[$key] . "', '" . $this->School . "', '" . $this->ChildClass[$key] . "'), ";
         $number_children_created++;
     }
     $children_information_query = rtrim($children_information_query, ', ') . ";";
     $statement = $conn->prepare($children_information_query);
     $statement->execute();
     // Gathering all newly created children and linking them to the creator of the advert
     $child_last_created_id = $conn->lastInsertId();
     $number_children_created_array = array();
     for ($i = 0; $i < $number_children_created; ++$i) {
         $created_child_id = $child_last_created_id + $i;
         array_push($number_children_created_array, $created_child_id);
     }
     $children_link_query = "INSERT INTO tbl_user_child(fk_child_id, fk_user_id) VALUES ";
     foreach ($this->ChildFirstName as $key => $c) {
         $children_link_query .= "('" . $number_children_created_array[$key] . "', '" . $this->UserId . "'), ";
     }
     $children_link_query = rtrim($children_link_query, ', ') . ";";
     $statement = $conn->prepare($children_link_query);
     $statement->execute();
 }
 /**
  * Update statement.
  * Sample: Record::getInstance()->updates('MyTable', array('foo' => 'bar', 'foo2' => 'bar4', 'foo9' => 'bar4'))->find('fooID', 22)->execute();
  *
  * @param string $sTable
  * @param array $aValues
  * @return object this
  */
 public function updates($sTable, array $aValues)
 {
     $aValues = is_null($aValues) ? $this->_aValues : $aValues;
     $this->_sSql = 'UPDATE' . Db::prefix($sTable) . 'SET ';
     $oCachingIterator = new \CachingIterator(new \ArrayIterator($aValues));
     foreach ($oCachingIterator as $sField => $sValue) {
         $this->_sSql .= $sField . ' = ' . $this->escape($sValue);
         $this->_sSql .= $oCachingIterator->hasNext() ? ',' : '';
     }
     return $this;
 }
Beispiel #22
0
 /**
  * Transform plain array to multidimensional
  * @param	array		$data
  * @param	string	$separator
  * @return	array
  */
 public static function plainToMulti($data, $separator = '.')
 {
     $result = new Core_ArrayObject();
     foreach ($data as $key => $value) {
         $pieces = new CachingIterator(new ArrayIterator(explode($separator, $key)));
         $current =& $result;
         foreach ($pieces as $piece) {
             if ($pieces->hasNext()) {
                 if (!isset($current->{$piece})) {
                     $current->{$piece} = new Core_ArrayObject();
                 }
                 $current =& $current->{$piece};
             } else {
                 $current->{$piece} = $value;
             }
         }
     }
     return $result->toArray();
 }
 public function test_London_getTransitions()
 {
     $test = $this->europeLondon();
     $trans = $test->getTransitions();
     $first = $trans[0];
     $this->assertEquals($first->getDateTimeBefore(), LocalDateTime::of(1847, 12, 1, 0, 0));
     $this->assertEquals($first->getOffsetBefore(), ZoneOffset::ofHoursMinutesSeconds(0, -1, -15));
     $this->assertEquals($first->getOffsetAfter(), self::$OFFSET_ZERO);
     $spring1916 = $trans[1];
     $this->assertEquals($spring1916->getDateTimeBefore(), LocalDateTime::of(1916, 5, 21, 2, 0));
     $this->assertEquals($spring1916->getOffsetBefore(), self::$OFFSET_ZERO);
     $this->assertEquals($spring1916->getOffsetAfter(), self::$OFFSET_PONE);
     $autumn1916 = $trans[2];
     $this->assertEquals($autumn1916->getDateTimeBefore(), LocalDateTime::of(1916, 10, 1, 3, 0));
     $this->assertEquals($autumn1916->getOffsetBefore(), self::$OFFSET_PONE);
     $this->assertEquals($autumn1916->getOffsetAfter(), self::$OFFSET_ZERO);
     $zot = null;
     $it = new \CachingIterator(new \ArrayIterator($trans));
     while ($it->hasNext()) {
         $it->next();
         $zot = $it->current();
         if ($zot->getDateTimeBefore()->getYear() === 1990) {
             break;
         }
     }
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1990, 3, 25, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1990, 10, 28, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1991, 3, 31, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1991, 10, 27, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1992, 3, 29, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1992, 10, 25, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1993, 3, 28, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1993, 10, 24, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1994, 3, 27, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1994, 10, 23, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1995, 3, 26, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1995, 10, 22, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1996, 3, 31, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1996, 10, 27, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1997, 3, 30, 1, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_ZERO);
     $it->next();
     $zot = $it->current();
     $this->assertEquals($zot->getDateTimeBefore(), LocalDateTime::of(1997, 10, 26, 2, 0));
     $this->assertEquals($zot->getOffsetBefore(), self::$OFFSET_PONE);
     $this->assertEquals($it->hasNext(), false);
 }
Beispiel #24
0
     }
 }
 // Retrieving the selected children's names
 $selected_children_names = array();
 foreach ($_POST['advert-select-children'] as $childId) {
     $statement = $conn->prepare("SELECT child_first_name FROM tbl_child WHERE child_id = '{$childId}'");
     $statement->execute();
     $child_name = $statement->fetch(PDO::FETCH_COLUMN, 0);
     $selected_children_names[] = $child_name;
 }
 $iterator = new ArrayIterator($selected_children_names);
 $cachingiterator = new CachingIterator($iterator);
 $selected_child_name = '';
 foreach ($cachingiterator as $name) {
     $selected_child_name .= $cachingiterator->current();
     if ($cachingiterator->hasNext()) {
         $selected_child_name .= ", ";
     }
 }
 $selected_child_name = preg_replace('/(.*),/', '$1 en', $selected_child_name);
 // Processing the chosen date into a readable string
 $chosen_date_day = ltrim(date('d', strtotime($_POST['advert-book-date'])), '0');
 $chosen_date_day_string = strftime("%A", strtotime($_POST['advert-book-date']));
 $chosen_date_month_string = strftime("%B", strtotime($_POST['advert-book-date']));
 // Sending a booking-request e-mail to the creator of the advert
 $mail = new PHPMailer();
 $mail->isSMTP();
 $mail->SMTPDebug = 0;
 $mail->Debugoutput = 'html';
 $mail->Host = 'smtp.transip.email';
 $mail->Port = 465;
Beispiel #25
0
$unit = ambildata($_SESSION['iddetail'], 'user_detail', 'UNIT_ID');
$q = mysql_query("select * from selected_topic where UNIT_ID='{$unit}'");
$e = mysql_fetch_array($q);
$c = mysql_num_rows($q);
if (isset($_POST['topik'])) {
    if ($c >= 1) {
        mysql_query("delete from selected_topic where UNIT_ID='{$unit}'");
    }
    $user = $_SESSION['username'];
    $array = $_POST['topik'];
    $sql = "insert into selected_topic (GUID,UNIT_ID,MASTER_TOPIC_ID,DTMCRT,USRCRT) values ";
    $it = new ArrayIterator($array);
    $cit = new CachingIterator($it);
    foreach ($cit as $value) {
        $sql .= "(uuid(),'{$unit}','" . $cit->current() . "',now(),'{$user}')";
        if ($cit->hasNext()) {
            $sql .= ",";
        }
    }
    $a = mysql_query($sql);
    if ($a) {
        eksyen('Sukses', '?p=topics');
    } else {
        eksyen('Gagal', 'inside.php#mastersetting');
    }
}
?>
<form action="" method="post">
	<div class="row">
		<div class="col-md-12">
	<?php 
 public function insertBookCategories()
 {
     $queryStr = "INSERT INTO book_category (book_id, cat_id) VALUES ";
     $it = new ArrayIterator($this->_categoryId);
     $cit = new CachingIterator($it);
     foreach ($cit as $key => $value) {
         $queryStr .= "(" . $this->_bookId . "," . $key . ")";
         if ($cit->hasNext()) {
             $queryStr .= ",";
         }
     }
     $this->_registry->getObject('db')->execute($queryStr);
     return $this->_registry->getObject('db')->affectedRows() == count($this->_categoryId) ? true : false;
 }
Beispiel #27
0
 * in a single dimension "navigation" array so we can accurately set classes for "last".
 *
 * Please note:
 * No safety measures have been taken to sanitize the output.
 *
 * @author  Corey Ballou
 */
// example navigation array
$nav = array('Home' => '/home', 'Products' => '/products', 'Company' => '/company', 'Privacy Policy' => '/privacy-policy');
// storage of output
$output = new ArrayIterator();
try {
    // create the caching iterator of the nav array
    $it = new CachingIterator(new ArrayIterator($nav));
    foreach ($it as $name => $url) {
        if ($it->hasNext()) {
            $output->append('<li><a href="' . $url . '">' . $name . '</a></li>');
        } else {
            $output->append('<li class="last"><a href="' . $url . '">' . $name . '</a></li>');
        }
    }
    // if we have values, output the unordered list
    if ($output->count()) {
        echo '<ul id="nav">' . "\n" . implode("\n", (array) $output) . "\n" . '</ul>';
    }
} catch (Exception $e) {
    die($e->getMessage());
}
/**
 * Below is the same example, but prettified in a nice, extensible class
 * allowing you to reuse it for nav, subnav, or any time you need to
        }
    }
}
?>
# Change Log

All notable changes to this project will be documented in this file.

This projects adheres to [Semantic Versioning](http://semver.org/) and [Keep a CHANGELOG](http://keepachangelog.com/).

<?php 
foreach ($changelog as $log) {
    if ('Unreleased' === $log->version) {
        echo '## [', $log->version, '][unreleased]', "\r\n";
    } else {
        echo '## [', $log->version, '] - ', $log->date, "\r\n";
    }
    render_changes($log->changes);
    echo "\r\n";
}
$collection = new CachingIterator(new ArrayIterator($changelog), CachingIterator::TOSTRING_USE_CURRENT);
foreach ($collection as $log) {
    if ($collection->hasNext()) {
        $prev = $collection->getInnerIterator()->current();
        if ('Unreleased' === $log->version) {
            echo '[unreleased]: https://github.com/pronamic/wp-pronamic-ideal/compare/', $prev->version, '...', 'HEAD', "\r\n";
        } else {
            echo '[', $log->version, ']: https://github.com/pronamic/wp-pronamic-ideal/compare/', $prev->version, '...', $log->version, "\r\n";
        }
    }
}