Esempio n. 1
0
 /**
  * Test for Str::increment()
  * 
  * @test
  */
 public function test_increment()
 {
     $values = array('valueA', 'valueB', 'valueC');
     for ($i = 0; $i < count($values); $i++) {
         $output = Str::increment($values[$i], $i);
         $expected = $values[$i] . '_' . $i;
         $this->assertEquals($expected, $output);
     }
 }
Esempio n. 2
0
    public static function migration($args, $build = true)
    {
        // Get the migration name
        $migration_name = strtolower(str_replace('-', '_', array_shift($args)));
        // Check if a migration with this name already exists
        if (count($duplicates = glob(APPPATH . "migrations/*_{$migration_name}*")) > 0) {
            // Don't override a file
            if (\Cli::option('s', \Cli::option('skip')) === true) {
                return;
            }
            // Tear up the file path and name to get the last duplicate
            $file_name = pathinfo(end($duplicates), PATHINFO_FILENAME);
            // Override the (most recent) migration with the same name by using its number
            if (\Cli::option('f', \Cli::option('force')) === true) {
                list($number) = explode('_', $file_name);
            } elseif (static::$scaffolding === false) {
                // Increment the name of this
                $migration_name = \Str::increment(substr($file_name, 4), 2);
            }
        }
        // See if the action exists
        $methods = get_class_methods(__NAMESPACE__ . '\\Generate_Migration_Actions');
        // For empty migrations that dont have actions
        $migration = array('', '');
        // Loop through the actions and act on a matching action appropriately
        foreach ($methods as $method_name) {
            // If the miration name starts with the name of the action method
            if (substr($migration_name, 0, strlen($method_name)) === $method_name) {
                /**
                 *	Create an array of the subject the migration is about
                 *
                 *	- In a migration named 'create_users' the subject is 'users' since thats what we want to create
                 *		So it would be the second object in the array
                 *			array(false, 'users')
                 *
                 *	- In a migration named 'add_name_to_users' the object is 'name' and the subject is 'users'.
                 *		So again 'users' would be the second object, but 'name' would be the first
                 *			array('name', 'users')
                 *
                 */
                $subjects = array(false, false);
                $matches = explode('_', str_replace($method_name . '_', '', $migration_name));
                // create_{table}
                if (count($matches) == 1) {
                    $subjects = array(false, $matches[0]);
                } else {
                    if (count($matches) == 3 && $matches[1] == 'to') {
                        $subjects = array($matches[0], $matches[2]);
                    } else {
                        if (count($matches) !== 0) {
                            $subjects = array(false, implode('_', $matches));
                        } else {
                            break;
                        }
                    }
                }
                // We always pass in fields to a migration, so lets sort them out here.
                $fields = array();
                foreach ($args as $field) {
                    $field_array = array();
                    // Each paramater for a field is seperated by the : character
                    $parts = explode(":", $field);
                    // We must have the 'name:type' if nothing else!
                    if (count($parts) >= 2) {
                        $field_array['name'] = array_shift($parts);
                        foreach ($parts as $part_i => $part) {
                            preg_match('/([a-z0-9_-]+)(?:\\[([a-z0-9]+)\\])?/i', $part, $part_matches);
                            array_shift($part_matches);
                            if (count($part_matches) < 1) {
                                // Move onto the next part, something is wrong here...
                                continue;
                            }
                            $option_name = '';
                            // This is the name of the option to be passed to the action in a field
                            $option = $part_matches;
                            // The first option always has to be the field type
                            if ($part_i == 0) {
                                $option_name = 'type';
                                $type = $option[0];
                                if ($type === 'string') {
                                    $type = 'varchar';
                                } else {
                                    if ($type === 'integer') {
                                        $type = 'int';
                                    }
                                }
                                if (!in_array($type, array('text', 'blob', 'datetime', 'date', 'timestamp', 'time'))) {
                                    if (!isset($option[1]) || $option[1] == NULL) {
                                        if (isset(self::$_default_constraints[$type])) {
                                            $field_array['constraint'] = self::$_default_constraints[$type];
                                        }
                                    } else {
                                        $field_array['constraint'] = (int) $option[1];
                                    }
                                }
                                $option = $type;
                            } else {
                                // This allows you to put any number of :option or :option[val] into your field and these will...
                                // ... always be passed through to the action making it really easy to add extra options for a field
                                $option_name = array_shift($option);
                                if (count($option) > 0) {
                                    $option = $option[0];
                                } else {
                                    $option = true;
                                }
                            }
                            $field_array[$option_name] = $option;
                        }
                        $fields[] = $field_array;
                    } else {
                        // Invalid field passed in
                        continue;
                    }
                }
                // Call the magic action which returns an array($up, $down) for the migration
                $migration = call_user_func(__NAMESPACE__ . "\\Generate_Migration_Actions::{$method_name}", $subjects, $fields);
            }
        }
        // Build the migration
        list($up, $down) = $migration;
        $migration_name = ucfirst(strtolower($migration_name));
        $migration = <<<MIGRATION
<?php

namespace Fuel\\Migrations;

class {$migration_name} {

\tpublic function up()
\t{
{$up}
\t}

\tpublic function down()
\t{
{$down}
\t}
}
MIGRATION;
        $number = isset($number) ? $number : static::_find_migration_number();
        $filepath = APPPATH . 'migrations/' . $number . '_' . strtolower($migration_name) . '.php';
        static::create($filepath, $migration, 'migration');
        $build and static::build();
    }
Esempio n. 3
0
 /**
  * Edit product hotspot infotab
  * This infotab has realy custom form and needs to be separated of others
  * 
  * @param $content_id	= Content ID
  * 
  */
 public function action_edit($content_id = false)
 {
     // Check for product
     if (!is_numeric($content_id)) {
         \Response::redirect('admin/application/list');
     }
     // Get news item to edit
     if (!($content = Model_Application::find_one_by_id($content_id))) {
         \Response::redirect('admin/application/list');
     }
     if (\Input::post()) {
         if (\Input::post('image', false)) {
             // Upload image and display errors if there are any
             $image = $this->upload_infotab_image();
             if (!$image['exists'] && \Config::get('infotab.image.required', false) && empty($content->hotspot_image)) {
                 // No previous images and image is not selected and it is required
                 \Messages::error('<strong>There was an error while trying to upload image</strong>');
                 \Messages::error('You have to select image');
             } elseif ($image['errors']) {
                 \Messages::error('<strong>There was an error while trying to upload image</strong>');
                 foreach ($image['errors'] as $error) {
                     \Messages::error($error);
                 }
             }
             if ($image['is_valid'] && !(!$image['exists'] && \Config::get('infotab.image.required', false) && empty($content->hotspot_image)) || \Input::post('use_cover_image', false)) {
                 // Clear previous messages if exists
                 \Messages::reset();
                 // Get POST values
                 $insert = \Input::post();
                 $item_image['hotspot_alt_text'] = \Input::post('alt_text', false) ? \Input::post('alt_text', false) : NULL;
                 // Use cover image
                 if (\Input::post('use_cover_image', false)) {
                     $cover_image = \Input::post('cover_image');
                     $old_image = \Config::get('details.image.location.root') . $cover_image;
                     $new_image = \Config::get('infotab.image.location.root') . $cover_image;
                     //						var_dump($old_image, $new_image); exit;
                     while (file_exists($new_image)) {
                         $file_name = pathinfo($new_image, PATHINFO_FILENAME);
                         $file_ext = pathinfo($new_image, PATHINFO_EXTENSION);
                         $file_name = \Str::increment($file_name);
                         $new_image = \Config::get('infotab.image.location.root') . $file_name . '.' . $file_ext;
                     }
                     if (\File::copy($old_image, $new_image)) {
                         $image = \Image::forge(array('presets' => \Config::get('infotab.image.resize', array())));
                         $image->load($new_image);
                         foreach (\Config::get('infotab.image.resize', array()) as $preset => $options) {
                             $image->preset($preset);
                         }
                         if (isset($item_image)) {
                             $insert['hotspot_alt_text'] = isset($item_image['hotspot_alt_text']) ? $item_image['hotspot_alt_text'] : NULL;
                             $insert['hotspot_image'] = basename($new_image);
                             // Delete old infotab image
                             if (\Input::post('image_db', false)) {
                                 $this->delete_infotab_image(\Input::post('image_db', ''));
                             }
                         }
                     } else {
                         \Messages::error('<strong>There was an error while trying to upload image</strong>');
                         \Messages::error('Please try again');
                     }
                     // Delete uploaded images if there is product saving error
                     if (isset($this->_infotab_image_data)) {
                         foreach ($this->_infotab_image_data as $image_data) {
                             $this->delete_infotab_image($image_data['saved_as']);
                         }
                     }
                 } else {
                     /** IMAGES **/
                     // Save images if new files are submitted
                     if (isset($this->_infotab_image_data)) {
                         foreach ($this->_infotab_image_data as $image_data) {
                             $item_image['hotspot_image'] = $image_data['saved_as'];
                             // Delete old infotab image
                             if (\Input::post('image_db', false)) {
                                 $this->delete_infotab_image(\Input::post('image_db', ''));
                             }
                         }
                     }
                     if (isset($item_image)) {
                         $insert['hotspot_alt_text'] = isset($item_image['hotspot_alt_text']) ? $item_image['hotspot_alt_text'] : NULL;
                         $insert['hotspot_image'] = isset($item_image['hotspot_image']) ? $item_image['hotspot_image'] : $content->hotspot_image;
                     }
                     /** END OF IMAGES **/
                 }
                 // Make infotab active
                 $insert['active'] = 1;
                 $content->set($insert);
                 try {
                     $content->save();
                     \Messages::success('Image successfully updated.');
                     \Response::redirect(\Uri::create('admin/application/hotspot/show/' . $content->id));
                 } catch (\Database_Exception $e) {
                     // show validation errors
                     \Messages::error('<strong>There was an error while trying to update image</strong>');
                     // Uncomment lines below to show database errors
                     //$errors = $e->getMessage();
                     //\Messages::error($errors);
                 }
             } else {
                 // Delete uploaded images if there is product saving error
                 if (isset($this->_infotab_image_data)) {
                     foreach ($this->_infotab_image_data as $image_data) {
                         $this->delete_infotab_image($image_data['saved_as']);
                     }
                 }
             }
         }
         if (\Input::post('hotspot', false)) {
         }
     }
     \Response::redirect(\Uri::create('admin/application/hotspot/show/' . $content->id));
 }
Esempio n. 4
0
    public static function migration($args, $build = true)
    {
        // Get the migration name
        $migration_name = \Str::lower(str_replace(array('-', '/'), '_', array_shift($args)));
        if (empty($migration_name) or strpos($migration_name, ':')) {
            throw new Exception("Command is invalid." . PHP_EOL . "\tphp oil g migration <migrationname> [<fieldname1>:<type1> |<fieldname2>:<type2> |..]");
        }
        $base_path = APPPATH;
        // Check if a migration with this name already exists
        if ($module = \Cli::option('module')) {
            if (!($base_path = \Module::exists($module))) {
                throw new Exception('Module ' . $module . ' was not found within any of the defined module paths');
            }
        }
        $migrations = new \GlobIterator($base_path . 'migrations/*_' . $migration_name . '*');
        try {
            $duplicates = array();
            foreach ($migrations as $migration) {
                // check if it's really a duplicate
                $part = explode('_', basename($migration->getFilename(), '.php'), 2);
                if ($part[1] != $migration_name) {
                    $part = substr($part[1], strlen($migration_name) + 1);
                    if (!is_numeric($part)) {
                        // not a numbered suffix, but the same base classname
                        continue;
                    }
                }
                $duplicates[] = $migration->getPathname();
            }
        } catch (\LogicException $e) {
            throw new Exception("Unable to read existing migrations. Path does not exist, or you may have an 'open_basedir' defined");
        }
        if (count($duplicates) > 0) {
            // Don't override a file
            if (\Cli::option('s', \Cli::option('skip')) === true) {
                return;
            }
            // Tear up the file path and name to get the last duplicate
            $file_name = pathinfo(end($duplicates), PATHINFO_FILENAME);
            // Override the (most recent) migration with the same name by using its number
            if (\Cli::option('f', \Cli::option('force')) === true) {
                list($number) = explode('_', $file_name);
            } elseif (static::$scaffolding === false) {
                // Increment the name of this
                $migration_name = \Str::increment(substr($file_name, 4), 2);
            }
        }
        // See if the action exists
        $methods = get_class_methods(__NAMESPACE__ . '\\Generate_Migration_Actions');
        // For empty migrations that dont have actions
        $migration = array('', '');
        // Loop through the actions and act on a matching action appropriately
        foreach ($methods as $method_name) {
            // If the miration name starts with the name of the action method
            if (substr($migration_name, 0, strlen($method_name)) === $method_name) {
                /**
                 *	Create an array of the subject the migration is about
                 *
                 *	- In a migration named 'create_users' the subject is 'users' since thats what we want to create
                 *		So it would be the second object in the array
                 *			array(false, 'users')
                 *
                 *	- In a migration named 'add_name_to_users' the object is 'name' and the subject is 'users'.
                 *		So again 'users' would be the second object, but 'name' would be the first
                 *			array('name', 'users')
                 *
                 */
                $subjects = array(false, false);
                $matches = explode('_', str_replace($method_name . '_', '', $migration_name));
                // create_{table}
                if (count($matches) == 1) {
                    $subjects = array(false, $matches[0]);
                } else {
                    if (count($matches) == 3 && $matches[1] == 'to') {
                        $subjects = array($matches[0], $matches[2]);
                    } else {
                        if (count($matches) == 3 && $matches[1] == 'from') {
                            $subjects = array($matches[0], $matches[2]);
                        } else {
                            if (count($matches) >= 5 && in_array('to', $matches) && in_array('in', $matches)) {
                                $subjects = array(implode('_', array_slice($matches, array_search('in', $matches) + 1)), implode('_', array_slice($matches, 0, array_search('to', $matches))), implode('_', array_slice($matches, array_search('to', $matches) + 1, array_search('in', $matches) - array_search('to', $matches) - 1)));
                            } else {
                                if ($method_name == 'rename_table') {
                                    $subjects = array(implode('_', array_slice($matches, 0, array_search('to', $matches))), implode('_', array_slice($matches, array_search('to', $matches) + 1)));
                                } else {
                                    if (count($matches) !== 0) {
                                        $name = str_replace(array('create_', 'add_', 'drop_', '_to_'), array('create-', 'add-', 'drop-', '-to-'), $migration_name);
                                        if (preg_match('/^(create|drop|add)\\-([a-z0-9\\_]*)(\\-to\\-)?([a-z0-9\\_]*)?$/i', $name, $deep_matches)) {
                                            switch ($deep_matches[1]) {
                                                case 'create':
                                                case 'drop':
                                                    $subjects = array(false, $deep_matches[2]);
                                                    break;
                                                case 'add':
                                                    $subjects = array($deep_matches[2], $deep_matches[4]);
                                                    break;
                                            }
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                // We always pass in fields to a migration, so lets sort them out here.
                $fields = array();
                foreach ($args as $field) {
                    $field_array = array();
                    // Each paramater for a field is seperated by the : character
                    $parts = explode(":", $field);
                    // We must have the 'name:type' if nothing else!
                    if (count($parts) >= 2) {
                        $field_array['name'] = array_shift($parts);
                        foreach ($parts as $part_i => $part) {
                            preg_match('/([a-z0-9_-]+)(?:\\[([0-9a-z_\\-\\,\\s]+)\\])?/i', $part, $part_matches);
                            array_shift($part_matches);
                            if (count($part_matches) < 1) {
                                // Move onto the next part, something is wrong here...
                                continue;
                            }
                            $option_name = '';
                            // This is the name of the option to be passed to the action in a field
                            $option = $part_matches;
                            // The first option always has to be the field type
                            if ($part_i == 0) {
                                $option_name = 'type';
                                $type = $option[0];
                                if ($type === 'string') {
                                    $type = 'varchar';
                                } else {
                                    if ($type === 'integer') {
                                        $type = 'int';
                                    }
                                }
                                if (!in_array($type, array('text', 'blob', 'datetime', 'date', 'timestamp', 'time'))) {
                                    if (!isset($option[1]) || $option[1] == NULL) {
                                        if (isset(self::$_default_constraints[$type])) {
                                            $field_array['constraint'] = self::$_default_constraints[$type];
                                        }
                                    } else {
                                        // should support field_name:enum[value1,value2]
                                        if ($type === 'enum') {
                                            $values = explode(',', $option[1]);
                                            $option[1] = '"' . implode('","', $values) . '"';
                                            $field_array['constraint'] = $option[1];
                                        } elseif (in_array($type, array('decimal', 'float'))) {
                                            $field_array['constraint'] = $option[1];
                                        } else {
                                            $field_array['constraint'] = (int) $option[1];
                                        }
                                    }
                                }
                                $option = $type;
                            } else {
                                // This allows you to put any number of :option or :option[val] into your field and these will...
                                // ... always be passed through to the action making it really easy to add extra options for a field
                                $option_name = array_shift($option);
                                if (count($option) > 0) {
                                    $option = $option[0];
                                } else {
                                    $option = true;
                                }
                            }
                            // deal with some special cases
                            switch ($option_name) {
                                case 'auto_increment':
                                case 'null':
                                case 'unsigned':
                                    $option = (bool) $option;
                                    break;
                            }
                            $field_array[$option_name] = $option;
                        }
                        $fields[] = $field_array;
                    } else {
                        // Invalid field passed in
                        continue;
                    }
                }
                // Call the magic action which returns an array($up, $down) for the migration
                $migration = call_user_func(__NAMESPACE__ . "\\Generate_Migration_Actions::{$method_name}", $subjects, $fields);
            }
        }
        // Build the migration
        list($up, $down) = $migration;
        // If we don't have any, bail out
        if (empty($up) and empty($down)) {
            throw new \Exception('No migration could be generated. Please verify your command syntax.');
            exit;
        }
        $migration_name = ucfirst(strtolower($migration_name));
        $migration = <<<MIGRATION
<?php

namespace Fuel\\Migrations;

class {$migration_name}
{
\tpublic function up()
\t{
{$up}
\t}

\tpublic function down()
\t{
{$down}
\t}
}
MIGRATION;
        $number = isset($number) ? $number : static::_find_migration_number();
        $filepath = $base_path . 'migrations/' . $number . '_' . strtolower($migration_name) . '.php';
        static::create($filepath, $migration, 'migration');
        $build and static::build();
    }
Esempio n. 5
0
 public function action_create()
 {
     \View::set_global('title', 'Add New');
     if (\Input::post()) {
         $val = Model_Team::validate('create');
         // Upload image and display errors if there are any
         $image = $this->upload_image();
         if (!$image['exists'] && \Config::get('details.image.required', false) && empty($item->image)) {
             // No previous images and image is not selected and it is required
             \Messages::error('<strong>There was an error while trying to upload member image</strong>');
             \Messages::error('You have to select image');
         } elseif ($image['errors']) {
             \Messages::error('<strong>There was an error while trying to upload member image</strong>');
             foreach ($image['errors'] as $error) {
                 \Messages::error($error);
             }
         }
         if ($val->run() && $image['is_valid'] && !(!$image['exists'] && \Config::get('details.image.required', false))) {
             // Get POST values
             $insert = \Input::post();
             // Prepare some values
             $insert['published_at'] = !empty($insert['published_at']) ? strtotime($insert['published_at']) : \Date::forge()->get_timestamp();
             $insert['active_from'] = !empty($insert['active_from']) ? strtotime($insert['active_from']) : NULL;
             $insert['active_to'] = !empty($insert['active_to']) ? strtotime($insert['active_to']) : NULL;
             if ($insert['status'] != 2) {
                 unset($insert['active_from']);
                 unset($insert['active_to']);
             }
             $item = Model_Team::forge($insert);
             try {
                 $item->save();
                 // Validate and insert team slug into SEO database table
                 $val_seo = Model_Seo::validate('create_seo');
                 $insert_seo = array('content_id' => $item->id, 'slug' => \Inflector::friendly_title($item->name, '-', true));
                 while (!$val_seo->run($insert_seo)) {
                     $insert_seo['slug'] = \Str::increment($insert_seo['slug'], 1, '-');
                 }
                 $item_seo = Model_Seo::forge($insert_seo);
                 $item_seo->save();
                 // END OF: SEO
                 // Insert team images
                 if ($this->_image_data) {
                     $item_image = array(array('id' => 0, 'data' => array('content_id' => $item->id, 'image' => $this->_image_data[0]['saved_as'], 'alt_text' => \Input::post('alt_text', ''), 'cover' => 1, 'sort' => 1)));
                     Model_Team::bind_images($item_image);
                 }
                 \Messages::success('Member successfully created.');
                 \Response::redirect(\Input::post('update', false) ? \Uri::create('admin/team/update/' . $item->id) : \Uri::admin('current'));
             } catch (\Database_Exception $e) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create member</strong>');
                 // Uncomment lines below to show database errors
                 $errors = $e->getMessage();
                 \Messages::error($errors);
             }
         } else {
             if ($val->error() != array()) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to create member</strong>');
                 foreach ($val->error() as $e) {
                     \Messages::error($e->get_message());
                 }
             }
         }
         // Delete uploaded image if there is team saving error
         if (isset($this->_image_data)) {
             $this->delete_image($this->_image_data[0]['saved_as']);
         }
     }
     \Theme::instance()->set_partial('content', $this->view_dir . 'create');
 }
Esempio n. 6
0
    /**
     * Writes a migration class to the filesystem
     * 
     * @param  string $up   PHP code to migrate up
     * @param  string $down PHP code to migrate down
     * @param  string $name The name of the migration, usually involving a timestamp
     * @return void
     */
    protected static function generateMigration($up = '', $down = '', $name = null)
    {
        // Get the migration name
        empty($name) and $name = 'Migration' . date('YmdHis');
        // Check if a migration with this name already exists
        if (($duplicates = glob(APPPATH . "migrations/*_{$name}*")) === false) {
            throw new \Exception("Unable to read existing migrations. Do you have an 'open_basedir' defined?");
        }
        if (count($duplicates) > 0) {
            // Don't override a file
            if (\Fuel::$is_cli && \Cli::option('s', \Cli::option('skip')) === true) {
                return;
            }
            // Tear up the file path and name to get the last duplicate
            $file_name = pathinfo(end($duplicates), PATHINFO_FILENAME);
            // Override the (most recent) migration with the same name by using its number
            if (\Fuel::$is_cli && \Cli::option('f', \Cli::option('force')) === true) {
                list($number) = explode('_', $file_name);
            } else {
                // Increment the name of this
                $name = \Str::increment(substr($file_name, 4), 2);
            }
        }
        $name = ucfirst(strtolower($name));
        $migration = <<<MIGRATION
<?php

namespace Fuel\\Migrations;

class {$name}
{
\tpublic function up()
\t{
{$up}
\t}

\tpublic function down()
\t{
{$down}
\t}
}
MIGRATION;
        $number = isset($number) ? $number : static::findMigrationNumber();
        $filepath = APPPATH . 'migrations/' . $number . '_' . strtolower($name) . '.php';
        Generate::create($filepath, $migration, 'migration');
        Generate::build();
    }