Example #1
0
 /**
  * Imports data to the specified model
  */
 public static function importData($data, $model, $auto_backup = true, $lang = null)
 {
     \CMF\Doctrine\Extensions\Timestampable::disableListener();
     // Allow ourselves some room, this could take a while!
     try {
         set_time_limit(0);
         ini_set('memory_limit', '256M');
     } catch (\Exception $e) {
     }
     // Reset updated entities
     static::$_updatedEntities = array();
     // Normalise the data so we always have a collection
     if (is_array($data) && is_array(@$data['data']) && \Arr::is_assoc($data['data'])) {
         $data['data'] = array($data['data']);
     }
     try {
         // Loop through and import each external entity
         foreach ($data['data'] as $entity) {
             $entity = static::createOrUpdateEntity($entity, $model, $data, $lang);
             \D::manager()->flush();
         }
         static::processDeletions($model);
         \D::manager()->flush();
         // Try and repair any trees that may have been corrupted during the import
         static::repairTrees(array_keys(static::$_updatedEntities));
         \CMF\Doctrine\Extensions\Timestampable::enableListener();
     } catch (\Exception $e) {
         \CMF\Doctrine\Extensions\Timestampable::enableListener();
         return array('success' => false, 'message' => $e->getMessage());
     }
     return array('success' => true, 'message' => \Lang::get('admin.messages.import_success'));
 }
Example #2
0
 public function test_is_assoc()
 {
     $index = array('one', 'two');
     $assoc = array('one' => 'foo', 'two' => 'bar');
     $mixed = array('one' => 'foo', 'bar');
     $this->assert_false(Arr::is_assoc($index))->assert_true(Arr::is_assoc($assoc))->assert_true(Arr::is_assoc($mixed));
 }
Example #3
0
 /**
  * Ensures there is a choices array set.
  *
  * @param  array  $options
  */
 public function __construct($options = array())
 {
     parent::__construct($options);
     if (empty($this->choices)) {
         // Ensure we have choices to gather values from
         throw new Kohana_Exception(':class must have a `choices` property set', array(':class' => get_class($this)));
     }
     if (in_array(NULL, $this->choices)) {
         // Set allow_null to TRUE if we find a NULL value
         $this->allow_null = TRUE;
     } elseif ($this->allow_null) {
         // We're allowing NULLs but the value isn't set. Create it so validation won't fail.
         array_unshift($this->choices, NULL);
     }
     // Select the first choice
     reset($this->choices);
     if (!Arr::is_assoc($this->choices)) {
         // Convert non-associative values to associative ones
         $this->choices = array_combine($this->choices, $this->choices);
     }
     if (!array_key_exists('default', $options)) {
         // Set the default value from the first choice in the array
         $this->default = key($this->choices);
         if ($this->choices[$this->default] === NULL) {
             // Set the default to NULL instead of using the key which is an empty string for NULL values
             $this->default = NULL;
         }
     }
     // Add a rule to validate that the value is proper
     $this->rules[] = array('array_key_exists', array(':value', $this->choices));
 }
Example #4
0
 /**
  * Set a new alert.
  *
  * <code>
  * // Embed values with sprintf
  * Alert::set(Alert::INFO, 'Text: %s', array('Embed values with sprintf in text'), 'Subejct: %s');
  *
  * // Embed values with strtr
  * Alert::set(Alert::INFO, 'Text: :string', array(':string' => 'Embed values with strtr'), 'Subject: :string');
  *
  * // Render normal
  * Alert::set(Alert::INFO, 'INFO Text');
  *
  * // Render normal with subject
  * Alert::set(Alert::INFO, 'INFO Text', array(), 'INFO Subject');
  *
  * // Render as block
  * Alert::set(Alert::INFO, 'INFO Text', array(), null, true);
  *
  * // Render as block with subject
  * Alert::set(Alert::INFO, 'INFO Text Block', array(), 'INFO Subject Block', true);
  * </code>
  *
  * @param string $type    alert type (e.g. Alert::SUCCESS)
  * @param mixed  $text    alert text
  * @param array  $values  values to replace with sprintf or strtr
  * @param null   $subject subject or heading
  * @param bool   $block   render as block alert
  *
  * @uses Arr::is_assoc
  * @uses Session::instance
  * @return void
  */
 public static function set($type, $text, array $values = array(), $subject = null, $block = false)
 {
     if (empty($values) === false) {
         if (Arr::is_assoc($values)) {
             // Insert the values into the alert
             $text = strtr($text, $values);
             $subject = strtr($subject, $values);
         } else {
             $tmp_values = $values;
             // The target string goes first
             array_unshift($values, $text);
             // Insert the values into the alert
             $text = call_user_func_array('sprintf', $values);
             $values = $tmp_values;
             // The target string goes first
             array_unshift($values, $subject);
             // Insert the values into the alert
             $subject = call_user_func_array('sprintf', $values);
         }
     }
     // Load existing alerts
     $alerts = Alert::get();
     // Append a new alert
     $alerts[] = array('type' => $type, 'text' => $text, 'subject' => $subject, 'block' => $block);
     // Store the updated alerts
     Session::instance()->set(Alert::$_session_key, $alerts);
 }
Example #5
0
File: arr.php Project: netbiel/core
 /**
  * Convert an array to XML string
  *
  * @static
  * @param   array   $array
  * @param   string  $root
  * @param   SimpleXMLElement  $xml
  * @return  string
  */
 public static function xml(array $array, $root = 'data', SimpleXMLElement &$xml = null)
 {
     // Initialize
     if (is_null($xml)) {
         $xml = simplexml_load_string('<?xml version="1.0" encoding="' . Kohana::$charset . '"?><' . $root . ' />');
     }
     foreach ($array as $key => $value) {
         // No numeric keys in our xml please!
         $numeric = false;
         if (is_numeric($key)) {
             $numeric = true;
             $key = Inflector::singular($root);
         }
         // Valid XML name
         $key = preg_replace('/[^a-z0-9\\-\\_\\.\\:]/i', '', $key);
         // Recursive call required for array values
         if (is_array($value)) {
             $node = true || Arr::is_assoc($value) || $numeric ? $xml->addChild($key) : $xml;
             self::xml($value, $key, $node);
         } else {
             $xml->addChild($key, htmlspecialchars($value));
         }
     }
     return $xml->asXML();
 }
Example #6
0
 /**
  * Handles the request to execute a task.
  *
  * Responsible for parsing the tasks to execute & also any config items that
  * should be passed to the tasks
  */
 public function action_execute()
 {
     if (empty($this->_task)) {
         return $this->action_help();
     }
     $task = $this->_retrieve_task();
     $defaults = $task->get_config_options();
     if (!empty($defaults)) {
         if (Arr::is_assoc($defaults)) {
             $options = array_keys($defaults);
             $options = call_user_func_array(array('CLI', 'options'), $options);
             $config = Arr::merge($defaults, $options);
         } else {
             // Old behavior
             $config = call_user_func_array(array('CLI', 'options'), $defaults);
         }
     } else {
         $config = array();
     }
     // Validate $config
     $validation = Validation::factory($config);
     $validation = $task->build_validation($validation);
     if (!$validation->check()) {
         echo View::factory('minion/error/validation')->set('errors', $validation->errors($task->get_errors_file()));
     } else {
         // Finally, run the task
         echo $task->execute($config);
     }
 }
Example #7
0
 public final function set_global($key, $value = NULL)
 {
     if (is_array($key) and Arr::is_assoc($key)) {
         Kostache::$globals = Arr::merge(Kostache::$globals, $key);
     } else {
         Kostache::$globals[$key] = $value;
     }
 }
 public function __construct($class)
 {
     $props = $class::observers(get_class($this));
     $this->_relations = \Arr::is_assoc($props['relations']) ? array($props['relations']) : $props['relations'];
     if (!empty($props['check_changed'])) {
         $this->_check_properties = isset($props['check_changed']['check_properties']) ? $props['check_changed']['check_properties'] : array();
         $this->_ignore_properties = isset($props['check_changed']['ignore_properties']) ? $props['check_changed']['ignore_properties'] : array();
     }
 }
Example #9
0
 public static function replacer($content = '', $data = array(), $other = array())
 {
     $other = (array) $other;
     $exploder = isset($other['exploder']) ? $other['exploder'] : '.';
     $replace_null = isset($other['replace_null']) ? $other['replace_null'] : false;
     $repeater = isset($other['repeater']) ? $other['repeater'] : false;
     $brackets = isset($other['brackets']) ? $other['brackets'] : array("{", "}");
     $op = $brackets[0];
     $cl = $brackets[1];
     if (!empty($repeater)) {
         preg_match_all('/' . preg_quote($op) . $repeater . '([^' . preg_quote($cl) . ']*)' . preg_quote($cl) . '(.*?)' . preg_quote($op) . '\\/' . $repeater . preg_quote($cl) . '/is', $content, $repeater_matches);
         if (!empty($repeater_matches[0])) {
             foreach ($repeater_matches[0] as $k => $match) {
                 $path = '';
                 if (!empty($repeater_matches[1][$k])) {
                     $path = str_replace(':', '', $repeater_matches[1][$k]);
                 }
                 $sub_data = Arr::getVal($data, explode('.', $path), array());
                 if (!Arr::is_assoc($sub_data)) {
                     $sub_content = '';
                     foreach ($sub_data as $i => $sub_data_array) {
                         $sub_content .= self::replacer($repeater_matches[2][$k], $sub_data_array);
                     }
                     $content = str_replace($repeater_matches[0][$k], $sub_content, $content);
                 }
             }
         }
     }
     preg_match_all('/' . preg_quote($op) . '([^(' . $cl . '|' . $op . '| )]*?)' . preg_quote($cl) . '/i', $content, $curly_matches);
     if (isset($curly_matches[1]) && !empty($curly_matches[1])) {
         foreach ($curly_matches[1] as $match) {
             $value = Arr::getVal($data, explode($exploder, $match));
             if (is_string($value) and !empty($other['nl2br'])) {
                 $value = nl2br($value);
             }
             if (!is_null($value)) {
                 if (is_array($value)) {
                     $content = str_replace($op . $match . $cl, var_export($value, true), $content);
                 } else {
                     if (!empty($other['escape'])) {
                         $content = str_replace($op . $match . $cl, htmlspecialchars($value), $content);
                     } else {
                         $content = str_replace($op . $match . $cl, $value, $content);
                     }
                 }
             } else {
                 if ($replace_null === true) {
                     $content = str_replace($op . $match . $cl, '', $content);
                 }
             }
         }
     }
     return $content;
 }
Example #10
0
 /**
  * Choose the columns to select from, using an array.
  *
  * @param   array  list of column names or array aliases or key/value aliases array(alias => column)
  * @return  $this
  */
 public function select_array(array $columns)
 {
     if (Arr::is_assoc($columns)) {
         $columns_assoc = array();
         foreach ($columns as $alias => $column) {
             // Pass in the alias as the expected array($column, $alias) or only the string
             $columns_assoc[] = is_string($alias) ? array($column, $alias) : $column;
         }
         $columns = $columns_assoc;
     }
     $this->_select = array_merge($this->_select, $columns);
     return $this;
 }
Example #11
0
 public static function displayForm($value, &$settings, $model)
 {
     $settings = static::settings($settings);
     if ($settings['array'] !== true) {
         $field_class = 'CMF\\Field\\Object\\Object';
         return $field_class::displayForm($value, $settings, $model);
     }
     if (!is_array($value)) {
         $value = array();
     }
     if (\Arr::is_assoc($value)) {
         $value = array($value);
     }
     $form = new ObjectForm($settings, $value);
     $content = '';
     return array('content' => $form->getContent($model), 'assets' => $form->assets, 'widget' => $settings['widget'], 'merge_data' => true, 'js_data' => $form->js_field_settings);
 }
Example #12
0
 public function fill($x1, $y1, $x2, $y2, $color = array(0, 0, 0, 100))
 {
     is_string($color) and $color = $this->create_hex_color($color);
     if (is_array($color)) {
         if (\Arr::is_assoc($color)) {
             extract($color);
         } else {
             if (count($color) > 3) {
                 list($red, $green, $blue, $alpha) = $color;
             } else {
                 list($red, $green, $blue) = $color;
                 $alpha = 100;
             }
         }
         $alpha = 127 - floor($alpha * 1.27);
         $color = imagecolorallocatealpha($this->image_data, $red, $green, $blue, $alpha);
     }
     imagefilledrectangle($this->image_data, $x1, $y1, $x2, $y2, $color);
     return $this;
 }
Example #13
0
 public function fill($x1, $y1, $x2, $y2, $color = array(0, 0, 0, 100))
 {
     is_string($color) and $color = $this->create_hex_color($color);
     if (is_array($color)) {
         if (\Arr::is_assoc($color)) {
             extract($color);
         } else {
             if (count($color) > 3) {
                 list($red, $green, $blue, $alpha) = $color;
             } else {
                 list($red, $green, $blue) = $color;
                 $alpha = 100;
             }
         }
         $alpha = round($alpha / 100, 1);
         $color = new \ImagickPixel('rgba(' . $red . ', ' . $green . ', ' . $blue . ', ' . str_replace(',', '.', $alpha) . ')');
     }
     $fill = new \ImagickDraw();
     $fill->setfillcolor($color);
     $fill->rectangle($x1, $y1, $x2, $y2);
     $this->imagick->drawimage($fill);
     return $this;
 }
Example #14
0
 /**
  * Merges one or more arrays recursively and preserves all keys.
  * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
  *
  *     $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
  *     $mary = array('name' => 'mary', 'children' => array('jane'));
  *
  *     // John and Mary are married, merge them together
  *     $john = Arr::merge($john, $mary);
  *
  *     // The output of $john will now be:
  *     array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
  *
  * @param   array  initial array
  * @param   array  array to merge
  * @param   array  ...
  * @return  array
  */
 public static function merge(array $a1, array $a2)
 {
     $result = array();
     for ($i = 0, $total = func_num_args(); $i < $total; $i++) {
         // Get the next array
         $arr = func_get_arg($i);
         // Is the array associative?
         $assoc = Arr::is_assoc($arr);
         foreach ($arr as $key => $val) {
             if (isset($result[$key])) {
                 if (is_array($val) and is_array($result[$key])) {
                     if (Arr::is_assoc($val)) {
                         // Associative arrays are merged recursively
                         $result[$key] = Arr::merge($result[$key], $val);
                     } else {
                         // Find the values that are not already present
                         $diff = array_diff($val, $result[$key]);
                         // Indexed arrays are merged to prevent duplicates
                         $result[$key] = array_merge($result[$key], $diff);
                     }
                 } else {
                     if ($assoc) {
                         // Associative values are replaced
                         $result[$key] = $val;
                     } elseif (!in_array($val, $result, TRUE)) {
                         // Indexed values are added only if they do not yet exist
                         $result[] = $val;
                     }
                 }
             } else {
                 // New values are added
                 $result[$key] = $val;
             }
         }
     }
     return $result;
 }
Example #15
0
 /**
  * Get a map image from the Google Maps static image API
  */
 public static function getMapImage($options, $force = false)
 {
     if ($is_single = \Arr::is_assoc($options)) {
         $options = array($options);
     }
     // Set up the dir for storing
     $dir = DOCROOT . 'uploads/maps';
     $dir_made = is_dir($dir) ? true : @mkdir($dir, 0775, true);
     if (!$dir_made) {
         throw new \Exception("The map upload directory could not be found or created!");
     }
     foreach ($options as $num => $settings) {
         // Allow offset to be applied
         $olat = \Arr::get($settings, 'lat', 54.443);
         $olng = \Arr::get($settings, 'lng', -3.063);
         $lat = $olat + \Arr::get($settings, 'latOffset', 0);
         $lng = $olng + \Arr::get($settings, 'lngOffset', 0);
         $width = \Arr::get($settings, 'width', 200);
         $height = \Arr::get($settings, 'height', 200);
         $scale = \Arr::get($settings, 'scale', 1);
         $marker = \Arr::get($settings, 'marker', false);
         $markerColor = \Arr::get($settings, 'markerColor', 'red');
         // Build the API url
         $url = 'http://maps.googleapis.com/maps/api/staticmap' . '?center=' . $lat . ',' . $lng . ($marker ? '&markers=color:' . $markerColor . '|' . $olat . ',' . $olng : '') . '&zoom=' . \Arr::get($settings, 'zoom', 11) . '&size=' . $width . 'x' . $height . '&scale=' . $scale . '&sensor=false';
         // Download the image
         $path = $dir . '/' . md5($url) . '.png';
         if (!file_exists($path) || $force) {
             $img = file_get_contents($url);
             @file_put_contents($path, $img);
         }
         // Set info back to the options
         $options[$num]['src'] = str_replace(DOCROOT, '', $path);
         $options[$num]['width'] = $width * $scale;
         $options[$num]['height'] = $height * $scale;
     }
     return $is_single ? $options[0] : $options;
 }
Example #16
0
 /**
  * To CSV conversion
  *
  * @param mixed $data        	
  * @param mixed $delimiter        	
  * @return string
  */
 public function to_csv($data = null, $delimiter = null)
 {
     // csv format settings
     $newline = \Config::get('format.csv.export.newline', \Config::get('format.csv.newline', "\n"));
     $delimiter or $delimiter = \Config::get('format.csv.export.delimiter', \Config::get('format.csv.delimiter', ','));
     $enclosure = \Config::get('format.csv.export.enclosure', \Config::get('format.csv.enclosure', '"'));
     $escape = \Config::get('format.csv.export.escape', \Config::get('format.csv.escape', '"'));
     // escape function
     $escaper = function ($items) use($enclosure, $escape) {
         return array_map(function ($item) use($enclosure, $escape) {
             return str_replace($enclosure, $escape . $enclosure, $item);
         }, $items);
     };
     if ($data === null) {
         $data = $this->_data;
     }
     if (is_object($data) and !$data instanceof \Iterator) {
         $data = $this->to_array($data);
     }
     // Multi-dimensional array
     if (is_array($data) and \Arr::is_multi($data)) {
         $data = array_values($data);
         if (\Arr::is_assoc($data[0])) {
             $headings = array_keys($data[0]);
         } else {
             $headings = array_shift($data);
         }
     } else {
         $headings = array_keys((array) $data);
         $data = array($data);
     }
     $output = $enclosure . implode($enclosure . $delimiter . $enclosure, $escaper($headings)) . $enclosure . $newline;
     foreach ($data as $row) {
         $output .= $enclosure . implode($enclosure . $delimiter . $enclosure, $escaper((array) $row)) . $enclosure . $newline;
     }
     return rtrim($output, $newline);
 }
Example #17
0
 /**
  * Tests Arr::is_assoc()
  *
  * @test
  * @dataProvider provider_is_assoc
  * @param array   $array     Array to check
  * @param boolean $expected  Is $array assoc
  */
 public function test_is_assoc(array $array, $expected)
 {
     $this->assertSame($expected, Arr::is_assoc($array));
 }
Example #18
0
 function saveAll($data = array(), $params = array())
 {
     if (!empty($data) and is_array($data) and !Arr::is_assoc($data)) {
         //array_values($data) === $data){
         //numerically indexed list of records
         $this->ids = array();
         foreach ($data as $k => $record) {
             $this->save($record, $params);
             $this->ids[] = $this->id;
         }
         return true;
     }
     return false;
 }
Example #19
0
 /** @inheritdoc */
 public static function displayForm($value, &$settings, $model)
 {
     $settings = static::settings($settings);
     $include_label = isset($settings['label']) ? $settings['label'] : true;
     $required = isset($settings['required']) ? $settings['required'] : false;
     $errors = $model->getErrorsForField($settings['mapping']['fieldName']);
     $has_errors = count($errors) > 0;
     $input_attributes = isset($settings['input_attributes']) ? $settings['input_attributes'] : array('class' => 'input-xxlarge');
     $options = \CMF::getOptions(get_class($model), \Arr::get($settings, 'mapping.columnName'), isset($settings['options']) ? $settings['options'] : array());
     // Description?
     $description = isset($settings['description']) ? '<span class="help-block">' . $settings['description'] . '</span>' : '';
     if (!empty($options) && !\Arr::is_assoc($options) && $settings['use_key'] !== true) {
         $options = array_combine($options, $options);
     } else {
         if (!empty($options)) {
             reset($options);
             $first = current($options);
             if (is_array($first) && isset($first['value'])) {
                 $options = array_map(function ($option) {
                     return $option['value'];
                 }, $options);
             }
         }
     }
     if (@$settings['multiple']) {
         if (is_null($value) || empty($value)) {
             if (@$settings['default'] == 'all' && is_array($options)) {
                 $value = array_keys($options);
             }
         }
         if (!is_array($value)) {
             $value = explode(',', $value);
         }
         $input_attributes['multiple'] = 'multiple';
     } else {
         if (isset($settings['mapping']['nullable']) && $settings['mapping']['nullable'] && !(isset($settings['required']) && $settings['required']) && $settings['allow_empty']) {
             $options = array('' => '') + $options;
         }
     }
     // Transform the options into the right format
     foreach ($options as $key => $option) {
         if (is_array($option)) {
             $options[$key] = \Arr::get($option, 'title', $key);
         }
     }
     // Select2?
     if (is_array($settings['select2'])) {
         $settings['is_select2'] = true;
         $input_attributes['class'] .= ' input-xxlarge select2';
         $settings['select2']['placeholder'] = 'click to select an option';
         $label = !$include_label ? '' : \Form::label($settings['title'] . ($required ? ' *' : '') . ($has_errors ? ' - ' . $errors[0] : ''), $settings['mapping']['fieldName'], array('class' => 'item-label'));
         $input = \Form::select($settings['mapping']['fieldName'], $value, $options, $input_attributes);
         $content = $label . $description . $input;
         if (!(isset($settings['wrap']) && $settings['wrap'] === false)) {
             $content = html_tag('div', array('class' => 'controls control-group' . ($has_errors ? ' error' : '')), $content);
         }
         return array('content' => $content . html_tag('div', array(), ''), 'widget' => @$settings['widget'], 'assets' => array('css' => array('/admin/assets/select2/select2.css'), 'js' => array('/admin/assets/select2/select2.min.js', '/admin/assets/js/fields/select2.js')), 'js_data' => $settings['select2']);
     }
     if (!is_string($value)) {
         $value = strval($value);
     }
     $options = array_map('strip_tags', $options);
     $label = !$include_label ? '' : \Form::label($settings['title'] . ($required ? ' *' : '') . ($has_errors ? ' - ' . $errors[0] : ''), $settings['mapping']['fieldName'], array('class' => 'item-label'));
     $input = \Form::select($settings['mapping']['fieldName'], strval($value), $options, $input_attributes);
     if (isset($settings['wrap']) && $settings['wrap'] === false) {
         return $label . $input;
     }
     return html_tag('div', array('class' => 'controls control-group' . ($has_errors ? ' error' : '')), $label . $description . $input);
 }
 case 'text_small':
 case 'input':
 case 'input_small':
 case 'email':
     $field = Form::input($element->name, $element->value, $element->attributes);
     break;
 case 'password':
     $field = Form::password($element->name, $element->value, $element->attributes);
     break;
 case 'submit':
     $label = isset($element->label) ? $element->label : text('label.' . $element->key);
     $field = Form::submit($element->name, $label, $element->attributes);
     break;
 case 'select':
     // check if is assoc array
     $assoc = Arr::is_assoc($element->options);
     if ($assoc == FALSE) {
         $options = array();
         // add labels to the options
         foreach ($element->options as $option) {
             $options[$option] = text('option.' . $element->key . '.' . $option);
         }
     } else {
         $options = $element->options;
     }
     // prepend a 'select this' option if wanted
     if (isset($element->first_option)) {
         $option = $element->first_option;
         $value = is_array($option) && isset($option['value']) ? $option['value'] : $option;
         $label = is_array($option) && isset($option['label']) ? $option['label'] : text('option.' . $element->key . '.' . $value);
         $reverse = array_reverse($options, true);
 /**
  * Helper: ensure an array is created
  * 
  * @param mixed $value
  * @return
  */
 protected function force_array($value)
 {
     if ($value === NULL) {
         // empty array
         return array();
     } elseif (!is_array($value) || Arr::is_assoc($value)) {
         // value as only element in array
         $arrayValue = array();
         $arrayValue[] = $value;
         return $arrayValue;
     } else {
         // value is an array allready
         return $value;
     }
 }
Example #22
0
 /**
  * To CSV conversion
  *
  * @param   mixed   $data
  * @param   mixed   $delimiter
  * @param   mixed   $enclose_numbers
  * @param   array   $headings  Custom headings to use
  * @return  string
  */
 public function to_csv($data = null, $delimiter = null, $enclose_numbers = null, array $headings = array())
 {
     // csv format settings
     $newline = \Config::get('format.csv.newline', \Config::get('format.csv.export.newline', "\n"));
     $delimiter or $delimiter = \Config::get('format.csv.delimiter', \Config::get('format.csv.export.delimiter', ','));
     $enclosure = \Config::get('format.csv.enclosure', \Config::get('format.csv.export.enclosure', '"'));
     $escape = \Config::get('format.csv.escape', \Config::get('format.csv.export.escape', '\\'));
     is_null($enclose_numbers) and $enclose_numbers = \Config::get('format.csv.delimit_numbers', true);
     // escape, delimit and enclose function
     $escaper = function ($items, $enclose_numbers) use($enclosure, $escape, $delimiter) {
         return implode($delimiter, array_map(function ($item) use($enclosure, $escape, $delimiter, $enclose_numbers) {
             if (!is_numeric($item) or $enclose_numbers) {
                 $item = $enclosure . str_replace($enclosure, $escape . $enclosure, $item) . $enclosure;
             }
             return $item;
         }, $items));
     };
     if ($data === null) {
         $data = $this->_data;
     }
     if (is_object($data) and !$data instanceof \Iterator) {
         $data = $this->to_array($data);
     }
     // Multi-dimensional array
     if (empty($headings)) {
         if (is_array($data) and \Arr::is_multi($data)) {
             $data = array_values($data);
             if (\Arr::is_assoc($data[0])) {
                 $headings = array_keys($data[0]);
             } else {
                 $headings = array_shift($data);
             }
         } else {
             $headings = array_keys((array) $data);
             $data = array($data);
         }
     }
     $output = $escaper($headings, true) . $newline;
     foreach ($data as $row) {
         $output .= $escaper($row, $enclose_numbers) . $newline;
     }
     return rtrim($output, $newline);
 }
 /**
  * Remove __extend__ and __fix__ keys from data
  * @param array $data
  */
 protected function cleanup(&$data)
 {
     foreach ($data as $key => $val) {
         if (is_array($data[$key]) && Arr::is_assoc($data[$key])) {
             // dig deeper
             $this->cleanup($data[$key]);
         }
         if ($key === '__extend__' || $key === '__locked__') {
             unset($data[$key]);
         }
     }
 }
Example #24
0
 /**
  * To CSV conversion
  *
  * @param   mixed   $data
  * @return  string
  */
 public function to_csv($data = null)
 {
     if ($data == null) {
         $data = $this->_data;
     }
     // Multi-dimentional array
     if (is_array($data) and isset($data[0])) {
         if (\Arr::is_assoc($data[0])) {
             $headings = array_keys($data[0]);
         } else {
             $headings = array_shift($data);
         }
     } else {
         $headings = array_keys((array) $data);
         $data = array($data);
     }
     $output = implode(',', $headings) . "\n";
     foreach ($data as &$row) {
         $output .= '"' . implode('","', (array) $row) . "\"\n";
     }
     return rtrim($output, "\n");
 }
 /**
  * Render an element
  * @param object $element
  * @return string
  */
 protected function element($element)
 {
     // set id
     if (!isset($element->attributes['id'])) {
         $element->id = $this->id();
         $attributes = $element->attributes;
         $attributes['id'] = $element->id;
         $element->attributes = $attributes;
     } else {
         $element->id = $element->attributes['id'];
     }
     // set class
     if (!isset($element->attributes['class'])) {
         // set bootstap class
         $attributes['class'] = '';
     }
     // set label
     if (!$element->label) {
         if ($element->text) {
             $element->label = $this->_text->get($element->text);
         } else {
             $element->label = $this->_text->get('label.' . $element->key);
         }
     }
     // set error
     if ($error = $element->error()) {
         // create  errormessage
         $element->error = $this->_text->get('error.' . $element->key . '.' . $error);
     } else {
         $element->error = FALSE;
     }
     // set comment
     if (!isset($element->comment)) {
         if ($comment = $this->_text->get('comment.' . $element->key)) {
             $element->comment = $comment;
         } else {
             $element->comment = FALSE;
         }
     }
     // set default view
     $view = 'form/element';
     // render the element itself
     switch ($element->type) {
         case 'radio':
         case 'checkbox':
         case 'select':
             if (Arr::is_assoc($element->options) === FALSE) {
                 $options = array();
                 foreach ($element->options as $value => $label) {
                     $value = $label;
                     $label = $this->_text->get('option.' . $element->key . '.' . $value);
                     $options[$value] = $label;
                 }
                 $element->options = $options;
             }
             if ($element->type === 'radio') {
                 $view = 'form/radio';
             }
             if ($element->type === 'checkbox') {
                 $view = 'form/checkbox';
             }
             if ($element->type === 'select') {
                 if (isset($element->first_option)) {
                     $option = $element->first_option;
                     $value = is_array($option) && isset($option['value']) ? $option['value'] : $option;
                     $label = is_array($option) && isset($option['label']) ? $option['label'] : $this->_text->get('option.' . $element->key . '.' . $value);
                     // add to the beginning of options
                     $reverse = array_reverse($element->options, TRUE);
                     $reverse[$value] = $label;
                     $element->options = array_reverse($reverse, TRUE);
                 }
                 // set bootstap class
                 $attributes['class'] .= ' form-control';
                 $element->html = FormHTML::select($element->name, $element->options, $element->value, $attributes);
             }
             break;
         case 'hidden':
             $view = FALSE;
             $element->html = FormHTML::hidden($element->name, $element->value, $attributes);
             break;
         case 'submit':
             $view = FALSE;
             $label = isset($element->label) ? $element->label : $this->_text->get('label.' . $element->key);
             $element->html = FormHTML::submit($element->name, $label, $attributes);
             break;
         case 'btn':
             $view = FALSE;
             $label = isset($element->label) ? $element->label : $this->_text->get('label.' . $element->key);
             $href = isset($element->href) ? $element->href : '#';
             $element->html = HTML::anchor($href, $label, $attributes);
             break;
         case 'button':
             $view = FALSE;
             $label = isset($element->label) ? $element->label : $this->_text->get('label.' . $element->key);
             $element->html = FormHTML::button($element->name, $label, $attributes);
             break;
         case 'file':
             $element->html = FormHTML::file($element->name, $attributes);
             break;
         case 'image':
             $element->html = FormHTML::image($element->name, $element->value, $attributes, FALSE);
             break;
         case 'text':
         case 'password':
             if (!isset($attributes['placeholder'])) {
                 $attributes['placeholder'] = $this->_text->get('placeholder.' . $element->key);
             }
             // set bootstap class
             $attributes['class'] .= ' form-control';
             if ($element->type === 'text') {
                 $element->html = FormHTML::input($element->name, $element->value, $attributes);
             }
             if ($element->type === 'password') {
                 $element->html = FormHTML::password($element->name, $element->value, $attributes);
             }
             break;
         case 'textarea':
             $attributes['class'] .= ' form-control';
             $element->html = FormHTML::textarea($element->name, $element->value, $attributes, FALSE);
             break;
         default:
             $element->html = View::factory('form/' . $element->type, array('viewer' => $this, 'element' => $element))->render();
     }
     // wrap element
     if ($view) {
         $html = View::factory($view, array('element' => $element))->render();
     } else {
         $html = $element->html;
     }
     return $html;
 }
Example #26
0
 public function __construct($class)
 {
     $props = $class::observers(get_class($this));
     $this->_relations = \Arr::is_assoc($props['relations']) ? array($props['relations']) : $props['relations'];
 }
Example #27
0
 /**
  * Convert a multi-dimensional array into a single-dimensional array.
  *
  *     $array = array('set' => array('one' => 'something'), 'two' => 'other');
  *
  *     // Flatten the array
  *     $array = Arr::flatten($array);
  *
  *     // The array will now be
  *     array('one' => 'something', 'two' => 'other');
  *
  * [!!] The keys of array values will be discarded.
  *
  * @param   array   $array  array to flatten
  * @return  array
  */
 public static function flatten($array)
 {
     $is_assoc = Arr::is_assoc($array);
     $flat = array();
     foreach ($array as $key => $value) {
         if (is_array($value)) {
             $flat = array_merge($flat, Arr::flatten($value));
         } else {
             if ($is_assoc) {
                 $flat[$key] = $value;
             } else {
                 $flat[] = $value;
             }
         }
     }
     return $flat;
 }
Example #28
0
 /**
  * Parses HTTP Header values and creating an appropriate object
  * depending on type; i.e. accept-type, accept-char, cache-control etc.
  *
  *     $header_values_array = HTTP_Header::parse_header_values(array('cache-control' => 'max-age=200; public'));
  *
  * @param   array    $header_values          Values to parse
  * @param   array    $header_commas_allowed  Header values where commas are not delimiters (usually date)
  * @return  array
  */
 public static function parse_header_values(array $header_values, array $header_commas_allowed = array('user-agent', 'date', 'expires'))
 {
     /**
      * @see http://www.w3.org/Protocols/rfc2616/rfc2616.html
      *
      * HTTP header declarations should be treated as case-insensitive
      */
     $header_values = array_change_key_case($header_values, CASE_LOWER);
     // Foreach of the header values applied
     foreach ($header_values as $key => $value) {
         if (is_array($value)) {
             $values = array();
             if (Arr::is_assoc($value)) {
                 foreach ($value as $k => $v) {
                     $values[] = HTTP_Header::parse_header_values($v);
                 }
             } else {
                 // RFC 2616 allows multiple headers with same name if they can be
                 // concatinated using commas without altering the original message.
                 // This usually occurs with multiple Set-Cookie: headers
                 $array = array();
                 foreach ($value as $k => $v) {
                     // Break value into component parts
                     $v = explode(';', $v);
                     // Do some nasty parsing to flattern the array into components,
                     // parsing key values
                     $array = Arr::flatten(array_map('HTTP_Header_Value::parse_key_value', $v));
                     // Get the K/V component and extract the first element
                     $key_value_component = array_slice($array, 0, 1, TRUE);
                     array_shift($array);
                     // Create the HTTP_Header_Value component array
                     $http_header['key'] = key($key_value_component);
                     $http_header['value'] = current($key_value_component);
                     $http_header['properties'] = $array;
                     // Create the HTTP_Header_Value
                     $values[] = new HTTP_Header_Value($http_header);
                 }
             }
             // Assign HTTP_Header_Value array to the header
             $header_values[$key] = $values;
             continue;
         }
         // If the key allows commas or no commas are found
         if (in_array($key, $header_commas_allowed) or strpos($value, ',') === FALSE) {
             // If the key is user-agent, we don't want to parse the string
             if ($key === 'user-agent') {
                 $header_values[$key] = new HTTP_Header_Value($value, TRUE);
             } else {
                 $header_values[$key] = new HTTP_Header_Value($value);
             }
             // Move to next header
             continue;
         }
         // Create an array of the values and clear any whitespace
         $value = array_map('trim', explode(',', $value));
         $parsed_values = array();
         // Foreach value
         foreach ($value as $v) {
             $v = new HTTP_Header_Value($v);
             // Convert the value string into an object
             if ($v->key === NULL) {
                 $parsed_values[] = $v;
             } else {
                 $parsed_values[$v->key] = $v;
             }
         }
         // Apply parsed value to the header
         $header_values[$key] = $parsed_values;
     }
     // Return the parsed header values
     return $header_values;
 }
Example #29
0
 /**
  * Get messages.
  *
  *     $messages = Hint::get();
  *
  *     // Get error messages
  *     $error_messages = Hint::get(Hint::ERROR);
  *
  *     // Get error AND alert messages
  *     $messages = Hint::get(array(Hint::ERROR, Hint::ALERT));
  *
  *     // Get everything except error AND alert messages
  *     $messages = Hint::get(array(1 => array(Hint::ERROR, Hint::ALERT)));
  *
  *     // Customize the default value
  *     $error_messages = Hint::get(Hint::ERROR, 'my default value');
  *
  * @param   mixed  $type     message type (e.g. Hint::SUCCESS, array(Hint::ERROR, Hint::ALERT))
  * @param   mixed  $default  default value to return
  * @param   bool   $delete   delete the messages?
  * @return  mixed
  */
 public static function get($type = NULL, $default = NULL, $delete = FALSE)
 {
     // Load existing messages
     $messages = Session::instance()->get(Hint::$storage_key);
     if ($messages === NULL) {
         // No messages found
         return $default;
     }
     if ($type !== NULL) {
         // Will hold the filtered set of messages to return
         $return = array();
         // Store the remainder in case `delete` OR `get_once` is called
         $remainder = array();
         foreach ($messages as $message) {
             if ($message['type'] === $type or is_array($type) and in_array($message['type'], $type) or is_array($type) and Arr::is_assoc($type) and !in_array($message['type'], $type[1])) {
                 $return[] = $message;
             } else {
                 $remainder[] = $message;
             }
         }
         if (empty($return)) {
             // No messages of '$type' to return
             return $default;
         }
         $messages = $return;
     }
     if ($delete === TRUE) {
         if ($type === NULL or empty($remainder)) {
             // Nothing to save, delete the key from memory
             Hint::delete();
         } else {
             // Override messages with the remainder to simulate a deletion
             Session::instance()->set(Hint::$storage_key, $remainder);
         }
     }
     return $messages;
 }
Example #30
0
 /**
  * To CSV conversion
  *
  * @param   mixed   $data
  * @param   mixed   $separator
  * @return  string
  */
 public function to_csv($data = null, $separator = ',')
 {
     if ($data === null) {
         $data = $this->_data;
     }
     if (is_object($data) and !$data instanceof \Iterator) {
         $data = $this->to_array($data);
     }
     // Multi-dimensional array
     if (is_array($data) and \Arr::is_multi($data)) {
         $data = array_values($data);
         if (\Arr::is_assoc($data[0])) {
             $headings = array_keys($data[0]);
         } else {
             $headings = array_shift($data);
         }
     } else {
         $headings = array_keys((array) $data);
         $data = array($data);
     }
     $output = "\"" . implode('"' . $separator . '"', $headings) . "\"\n";
     foreach ($data as &$row) {
         $output .= '"' . implode('"' . $separator . '"', (array) $row) . "\"\n";
     }
     return rtrim($output, "\n");
 }