public function test_irregular() { foreach (require __DIR__ . '/cases/fr/irregular.php' as $singular => $plural) { $this->assertEquals($singular, singularize($plural, 'fr')); $this->assertEquals($plural, pluralize($singular, 'fr')); } }
/** * @param $tblname * e.g. persons * @return string e.g. Person */ function tbl2cls($tblname) { $clasname = ucwords(singularize($tblname)); if ($clasname == 'Class') { $clasname = 'Clas'; } return $clasname; }
function delete_search($name) { $results = array(); $name = singularize($name); $class_suffix = 'Search'; $search_path = FCPATH . 'application/searches/' . ucfirst(camelize($name . $class_suffix)) . EXT; if (delete_file($search_path)) { array_push($results, $search_path); } return $results; }
function create_demo() { $db_line = color(str_repeat('=', 80), 'N') . "\n"; $line = color(str_repeat('-', 80), 'w') . "\n"; echo $db_line; $results = array(); $migrations = array('event' => array(), 'attendee' => array(), 'tag' => array(), 'tag_event_map' => array()); array_walk($migrations, function ($value, $key) use(&$results) { array_push($results, implode("\n", array_map(function ($result) { $count = 1; return color(' Create: ', 'g') . str_replace(FCPATH, '', $result, $count); }, create_migration(BASEPATH . 'cmd/templates/demo/' . $key . '/', $key, 'add')))); }); echo implode("\n", $results) . "\n" . $line; $results = array(); $models = array('event' => array('-p' => array('cover')), 'attendee' => array(), 'tag' => array(), 'tag_event_map' => array()); array_walk($models, function ($value, $key) use(&$results) { array_push($results, implode("\n", array_map(function ($result) { $count = 1; return color(' Create: ', 'g') . str_replace(FCPATH, '', $result, $count); }, create_model(BASEPATH . 'cmd/templates/demo/' . $key . '/', $key, isset($value['-p']) ? $value['-p'] : array(), isset($value['-f']) ? $value['-f'] : array())))); }); echo implode("\n", $results) . "\n" . $line; $results = array(); $cells = array('demo' => array('main_menu')); array_walk($cells, function ($value, $key) use(&$results) { array_push($results, implode("\n", array_map(function ($result) { $count = 1; return color(' Create: ', 'g') . str_replace(FCPATH, '', $result, $count); }, create_cell(BASEPATH . 'cmd/templates/demo/cell/', $key, $value)))); }); echo implode("\n", $results) . "\n" . $line; $results = array(); $controllers = array('events' => array(), 'tags' => array()); array_walk($controllers, function ($value, $key) use(&$results) { array_push($results, implode("\n", array_map(function ($result) { $count = 1; return color(' Create: ', 'g') . str_replace(FCPATH, '', $result, $count); }, create_controller(BASEPATH . 'cmd/templates/demo/' . singularize($key) . '/', $key, 'site', array('index', 'show', 'add', 'create', 'edit', 'update', 'destroy'))))); }); echo implode("\n", $results) . "\n" . $line; $results = run_migration(null); echo color('注意! ', 'r'); echo implode("\n", $results) . "\n"; $results = array(); array_push($results, "migrations(" . implode(', ', array_keys($migrations)) . ")"); array_push($results, "models(" . implode(', ', array_keys($models)) . ")"); array_push($results, "cells(" . implode(', ', array_keys($cells)) . ")"); array_push($results, "controllers(" . implode(', ', array_keys($controllers)) . ")"); return $results; }
function create_model($temp_path, $name, $images, $files) { $results = array(); $name = singularize($name); $image_uploader_class_suffix = 'ImageUploader'; $file_uploader_class_suffix = 'FileUploader'; $uploaders_path = FCPATH . 'application/third_party/orm_uploaders/'; $models_path = FCPATH . 'application/models/'; $models = array_map(function ($t) { return basename($t, EXT); }, directory_map($models_path, 1)); if ($models && in_array(ucfirst($name), $models)) { console_error("名稱重複!"); } if (!is_writable($models_path)) { console_error("無法有寫入的權限!"); } $uploaders = array_map(function ($t) { return basename($t, EXT); }, directory_map($uploaders_path, 1)); if (!is_writable($uploaders_path)) { console_error("Uploader 無法有寫入的權限!"); } $images = array_filter(array_map(function ($image) use($name, $uploaders_path, $uploaders, $image_uploader_class_suffix, $temp_path, &$results) { $image = strtolower($image); $uploader = ucfirst(camelize($name)) . ucfirst($image) . $image_uploader_class_suffix; if (!in_array($uploader, $uploaders) && write_file($uploader_path = $uploaders_path . $uploader . EXT, load_view($temp_path . 'image_uploader.php', array('name' => $uploader))) && array_push($results, $uploader_path)) { return $image; } return null; }, $images)); $files = array_filter(array_map(function ($file) use($name, $uploaders_path, $uploaders, $file_uploader_class_suffix, $temp_path, &$results) { $file = strtolower($file); $uploader = ucfirst(camelize($name)) . ucfirst($file) . $file_uploader_class_suffix; if (!in_array($uploader, $uploaders) && write_file($uploader_path = $uploaders_path . $uploader . EXT, load_view($temp_path . 'file_uploader.php', array('name' => $uploader))) && array_push($results, $uploader_path)) { return $file; } return null; }, $files)); $date = load_view($temp_path . 'model.php', array('name' => $name, 'images' => $images, 'files' => $files, 'image_uploader_class_suffix' => $image_uploader_class_suffix, 'file_uploader_class_suffix' => $file_uploader_class_suffix)); if (!write_file($model_path = $models_path . ucfirst(camelize($name)) . EXT, $date)) { array_map(function ($column) use($name, $uploaders_path, $uploader_class_suffix) { delete_file($uploaders_path . ucfirst(camelize($name)) . ucfirst($column) . $uploader_class_suffix . EXT); }, $columns); console_error("新增 model 失敗!"); } array_push($results, $model_path); return $results; }
/** * Pluralize a string. * Converts a word to english plural form, depending on 'if_many' value. * * Usage example: * {pluralize "{$items|count} items"} # 1 item * {pluralize "{$items|count} items"} # 10 items * {pluralize "Person"} # People * {pluralize word="Category" if_many=$categories} # Categories */ function pluralize($params) { if (is_string($params)) { $word = $params; } else { if (!($word = $params['word'])) { return false; } } // Conditional. if (isset($params['if_many'])) { $if_many = is_array($params['if_many']) ? count($params['if_many']) : $params['if_many']; } else { if (is_numeric($word[0])) { $parts = explode(' ', $word); $word = array_pop($parts); $if_many = $parts[0]; $prefix = implode(' ', $parts) . ' '; } } if (isset($if_many) && $if_many == 1) { $word = singularize($word); } else { $plural = array('/(quiz)$/i' => '\\1zes', '/^(ox)$/i' => '\\1en', '/([m|l])ouse$/i' => '\\1ice', '/(matr|vert|ind)ix|ex$/i' => '\\1ices', '/(x|ch|ss|sh)$/i' => '\\1es', '/([^aeiouy]|qu)y$/i' => '\\1ies', '/(hive)$/i' => '\\1s', '/(?:([^f])fe|([lr])f)$/i' => '\\1\\2ves', '/sis$/i' => 'ses', '/([ti])um$/i' => '\\1a', '/(buffal|tomat)o$/i' => '\\1oes', '/(bu)s$/i' => '\\1ses', '/(alias|status)/i' => '\\1es', '/(octop|vir)us$/i' => '\\1i', '/(ax|test)is$/i' => '\\1es', '/s$/i' => 's', '/$/' => 's'); $irregular = array('person' => 'people', 'man' => 'men', 'child' => 'children', 'sex' => 'sexes', 'move' => 'moves'); $ignore = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'data'); $lower_word = strtolower($word); foreach ($ignore as $ignore_word) { if (substr($lower_word, -1 * strlen($ignore_word)) == $ignore_word) { return $prefix . $word; } } foreach ($irregular as $_plural => $_singular) { if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) { return $prefix . preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word); } } foreach ($plural as $rule => $replacement) { if (preg_match($rule, $word)) { return $prefix . preg_replace($rule, $replacement, $word); } } } return $prefix . $word; }
function delete_model($name) { $results = array(); $name = singularize($name); $uploader_class_suffix = 'ImageUploader'; $image_uploader_class_suffix = 'ImageUploader'; $file_uploader_class_suffix = 'FileUploader'; $uploaders_path = FCPATH . 'application/third_party/orm_uploaders/'; $model_path = FCPATH . 'application/models/' . ucfirst(camelize($name)) . EXT; $content = read_file($model_path); preg_match_all('/OrmImageUploader::bind\\s*\\((?P<k>.*)\\);/', $content, $image_uploaders); $image_uploaders = array_map(function ($image_uploader) use($name, $image_uploader_class_suffix) { return isset($image_uploader[1]) ? $image_uploader[1] : ucfirst(camelize($name)) . $image_uploader_class_suffix; }, array_map(function ($image_uploader) { $pattern = '/(["\'])(?P<kv>(?>[^"\'\\\\]++|\\\\.|(?!\\1)["\'])*)\\1?/'; preg_match_all($pattern, $image_uploader, $image_uploaders); return $image_uploaders['kv']; }, $image_uploaders['k'])); array_map(function ($image_uploader) use($uploaders_path, &$results) { if (delete_file($uploaders_path . $image_uploader . EXT)) { array_push($results, $uploaders_path . $image_uploader . EXT); } }, $image_uploaders); preg_match_all('/OrmFileUploader::bind\\s*\\((?P<k>.*)\\);/', $content, $file_uploaders); $file_uploaders = array_map(function ($file_uploader) use($name, $file_uploader_class_suffix) { return isset($file_uploader[1]) ? $file_uploader[1] : ucfirst(camelize($name)) . $file_uploader_class_suffix; }, array_map(function ($file_uploader) { $pattern = '/(["\'])(?P<kv>(?>[^"\'\\\\]++|\\\\.|(?!\\1)["\'])*)\\1?/'; preg_match_all($pattern, $file_uploader, $file_uploaders); return $file_uploaders['kv']; }, $file_uploaders['k'])); array_map(function ($file_uploader) use($uploaders_path, &$results) { if (delete_file($uploaders_path . $file_uploader . EXT)) { array_push($results, $uploaders_path . $file_uploader . EXT); } }, $file_uploaders); if (delete_file($model_path)) { array_push($results, $model_path); } return $results; }
/** * @short Loads the child the receiver in a one-to-one relationship. * @param table_name The name of the child table. * @param params An array of conditions. For the semantics, see find_all * @see find_all */ public function has_one($table_name) { $childclass = table_name_to_class_name($table_name); $obj = eval("return new {$childclass}();"); $fkey = $this->get_foreign_key_name(); $children = $obj->find_all(array('where_clause' => "`{$fkey}` = {$this->values[$this->primary_key]}", 'limit' => 1)); if (count($children) > 0) { $child = $children[0]; $child->values[singularize($this->table_name)] = $this; $this->values[singularize($table_name)] = $child; } }
function insertLanguage($ruta, $name, $tabla, $campos) { $aux = 'COM_' . strtoupper($name) . '_TITLE_' . strtoupper($tabla) . '="' . $tabla . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_TITLE_LIST_VIEW_' . strtoupper($tabla) . ' = "' . $tabla . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_TITLE_LIST_VIEW_' . strtoupper($tabla) . '_DESC="Show a list of ' . $tabla . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_TITLE_ITEM_VIEW_' . strtoupper(singularize($tabla)) . '= "Single ' . singularize($tabla) . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_TITLE_ITEM_VIEW_' . strtoupper(singularize($tabla)) . '_DESC = "Show a specific ' . singularize($tabla) . '"'; foreach ($campos as $v) { $aux .= "\n" . 'COM_' . strtoupper($name) . '_' . strtoupper($tabla) . '_' . strtoupper($v['field']) . '= "' . strtoupper($v['field']) . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_FORM_LBL_' . strtoupper(singularize($tabla)) . '_' . strtoupper($v['field']) . ' = "' . strtoupper($v['field']) . '"'; $aux .= "\n" . 'COM_' . strtoupper($name) . '_FORM_DESC_' . strtoupper(singularize($tabla)) . '_' . strtoupper($v['field']) . ' = " "'; } $content = file_get_contents($ruta); $content = str_replace("[language]", $aux, $content); file_put_contents($ruta, $content); }
<?php require_once 'html_components/require_comps_start.php'; if (!isset($_GET['page_id'])) { show404(); } $crud_page = getCrudPage($_GET['page_id']); if (!$crud_page) { show404(); } pr($crud_page); // default values $recordTitle = singularize($crud_page['title'], 0, -1); // e.g. Employee, Pay Record etc $url = $crud_page['url'] . "?page_id=" . $_GET['page_id']; // $url = isset( $_SERVER['HTTP_REFERER'] )? $_SERVER['HTTP_REFERER'] : $crud_page['url']."?page_id=".$crud_page['id']; // check deleting: if (isset($_GET['record_id']) && isset($_GET['delete']) && $_GET['delete'] == 'true') { $logmsg = $recordTitle . " Deleted: Record Id = " . $_GET['record_id']; deleteRecord($crud_page['table_name'], "id=" . $_GET['record_id'], $logmsg, $url); } // handle posted data if (isset($_POST['submit'])) { // prpost(); validatefft($crud_page['table_name']); if ($form->isValid()) { $condition = isset($_GET['record_id']) ? "id=" . $_GET['record_id'] : NULL; $logmsg = isset($_GET['record_id']) ? $recordTitle . " Edited: " . $recordTitle . " ID: " . $_POST['id'] : "New " . $recordTitle . " Saved"; saveFormData($crud_page['table_name'], $_POST, $condition, $logmsg, $url); } }
public function getExtras($extraName) { if (!$this->id()) { return array(); } if (!$this->hasExtra($extraName)) { throw new Exception("You have not set up Active Record Extra --" . $extraName); } $internalVar = '__' . $extraName; if (!$this->{$internalVar}) { $className = ucfirst(singularize($extraName)); if (!class_exists($className)) { return; } // if they don't have the right module installed $refObj = new ReflectionClass($className); if (!$refObj->hasMethod('findAllFor')) { throw new Exception("Your Active Record Extra *MUST* have the method ~~~~> findAllFor <~~~~~. See classes/interfaces.php"); } $findAllMethodObj = $refObj->getMethod('findAllFor'); $tableNameValue = strtolower($extra) == 'media' ? $this->mediaKey() : $this->getTableName(); $this->{$internalVar} = $findAllMethodObj->invokeArgs(NULL, array($tableNameValue, $this->id())); } return $this->{$internalVar}; }
function is_singular($word) { return singularize($word) == $word; }
/** * @param $childClass * @param array $config * @return TableObject[] | Fee_voucher_datail[] | Fee_voucher[] * possible $config keys: array('condition' => ###) */ function getChildRecs($childClass, $config = array()) { $thisClass = get_called_class(); if ($this->id->val) { $chRefColumn = static::$childRefField ? static::$childRefField : strtolower(singularize($thisClass)) . "_id"; $condition = $chRefColumn . "=" . $this->id; if (isset($config['condition'])) { $condition .= " AND " . $config['condition']; } return $childClass::findByCondition($condition); } return false; }
/** * Returns corresponding controller name for given $string. * * @param string $class_name * @return string Singularized and camelized $class_name */ function to_controller($class_name) { return camelcase(singularize($class_name)) . 'Controller'; }
/** * This is the generic way to handle ARExtras going forward * it relies on an Extra's extrasForm() method * @param string the extra's name * @param RelfectionClass if you've already got it why not pass it in */ public function extrasFormFields($currentExtraName, $currentExtraRefObj = NULL) { // legacy if ($currentExtraName == 'images') { return $this->imageFormFields(); } elseif ($currentExtraName == 'media') { return $this->mediaFormFields(); } if (is_null($currentExtraRefObj)) { $currentExtraRefObj = new ReflectionClass(ucfirst(singularize($currentExtraName))); } // if ($maxExtras = $this->obj->maxExtras($currentExtraName)) { $form .= "<h3>" . ucfirst($currentExtraName) . "</h3>"; $i = 0; $extraLimit = $this->obj->getExtrasCount($currentExtraName) ? $this->obj->getExtrasCount($currentExtraName) : 1; for ($i; $i < $maxExtras && $i < $extraLimit; $i++) { $extra = $this->obj->getExtra($currentExtraName, $i); if (!$extra) { $extra = $currentExtraRefObj->newInstance(); } $form .= $extra->extrasForm($i); } $form .= "<div class='clear'></div>"; if ($i < $maxExtras) { $form .= $this->addAJAXLink($i - 1, $maxExtras - 1, $currentExtraName); } } return $form; }
function table_name_to_foreign_key($tablename) { $fkey = singularize($tablename); $fkey .= "_id"; return $fkey; }
/** * Helper method which sets up paramaters for thru relationships. * * @param array $params */ private function _setupThruParams(&$params) { // the foreign key in the middle table for the table on the left if (!isset($params['my_join_key'])) { $prefix = singularize($this->getTable()); $params['my_join_key'] = "{$prefix}_{$params['my_key']}"; } // the key in the table on the right if (!isset($params['as_key'])) { // if its our class, we have more insight because we easily get the key name if ($params['class'] == $this->getClass()) { $params['as_key'] = $this->getPrimaryKey(); } else { $params['as_key'] = 'id'; } } // the foreign key in the middle table for the table on the right if (!isset($params['as_join_key'])) { $prefix = singularize($params['table']); $params['as_join_key'] = "{$prefix}_{$params['as_key']}"; } // the class of the thru relationship if (!isset($params['thru_class'])) { $params['thru_class'] = 'Pfw_Model_Thru'; } // the table in the middle if (!isset($params['thru_table'])) { $params['thru_table'] = pluralize($params['thru']); } // setup the fields in the thru table if (!isset($params['thru_fields'])) { $params['thru_fields'] = array($params['my_join_key'], $params['as_join_key']); } }
public function index($type = '') { $this->content = View::auto(); $contentType = new ContentType(singularize($type)); $this->content->entries = $contentType->find(); }
/** * Put resource (update or insert). */ function put($id = null, $data = null, $stack = null, $query = null) { // Trigger REST binds. $event = $this->trigger_rest_binds("PUT", func_get_args()); if ($event === false || $event instanceof ModelResource) { return $event; } elseif (is_array($event) && $event['result']) { return $event['result']; } else { $id = $event['id']; $data = $event['data']; $stack = $event['stack']; $result = $data; } if (is_array($data)) { // Delete? if ($data[':delete']) { return $this->delete($id, $data, $stack); } // Validate before post? if ($data[':validate']) { if (!$this->validate($data, 'put', $data[':validate'])) { return false; } unset($data[':validate']); } } // Put to related resource? if ($id && $stack) { $record = $this->get($id); // Internal field? if (($field = $stack[0]) && ($this->has_field($field, true) || isset($query[':internal']))) { // Collection? if (is_array($data) || $stack[1]) { // Get internal values? if ($record instanceof ModelRecord) { $record = $record->values(); } $values = $record[$field]; // Turn scalar into array? if (!is_array($values) && !empty($values)) { $values = array($values); } // Indexed? // @TODO: Chain through stack. if ($key = $stack[1]) { $values[$key] = !is_array($data) ? $data : array_merge((array) $values[$key], $data); } else { $values = array_merge((array) $values, $data); } } else { $values = $data; } if ($this->update(array("{$field}" => $values), array("{$this->pk}" => $id))) { $result = $data; } } else { // Relate to pk. if ($record && is_array($data)) { $fk = strtolower(singularize($this->name)) . '_' . $this->pk; $data[$fk] = $record[$this->pk]; } // Chain through stack. $next_uri = implode('/', $stack); return put("/{$next_uri}", $data); } } else { if ($id && is_array($data)) { // ID by pk or slug. if (is_numeric($id) || !$this->has_field($this->slug_pk)) { $data[$this->pk] = $id; $where = array("{$this->pk}" => $id); } else { if ($this->slug_pk && $this->has_field($this->slug_pk)) { $data[$this->slug_pk] = $id; $where = array("{$this->slug_pk}" => $id); } } // Merge data with existing? if ($where && $this->count($where) > 0) { $ex = $this->get($id); $data[$this->pk] = $data[$this->pk] ?: $ex[$this->pk]; $this->update($data, $where); } else { $id = $this->insert($data); } $result = $this->get($id); } } if ($result && !$this->errors) { return $this->trigger_rest_after_binds('PUT', $result, array($id, $data, $stack, null, $ex)); } }
/** * Create a new has_and_belongs_to_many relation * * @param string $table * @param string $data * @param string $relation * @return void */ public function has_and_belongs_to_many_create($table, $data, $relation) { $return = $this->exec('insert into ' . $table . ' set ' . implode(', ', $this->prepare_data($data)) . ';'); $relation_table = implode('_', s($table, $relation->table())); $local = singularize($table) . '_id'; $local_id = $this->last_id(); $foreign = singularize($relation->table()) . '_id'; $foreign_id = $relation->id; $query = "select * from `{$relation_table}` where `{$foreign}`='{$foreign_id}' and `{$local}`='{$local_id}';"; $relation_exists = $this->query($query); if ($relation_exists->rowCount() === 0) { $query = "insert into " . $relation_table . " set " . $foreign . "='" . $foreign_id . "', " . $local . "='" . $local_id . "';"; $return = $this->exec($query); } return $return; }
function create_search($temp_path, $name) { $results = array(); $name = singularize($name); $searches_path = FCPATH . 'application/searches/'; $searches = array_map(function ($t) { return basename($t, EXT); }, directory_map($searches_path, 1)); $class_suffix = 'Search'; if ($searches && in_array(ucfirst($name), $searches)) { console_error("名稱重複!"); } if (!is_writable($searches_path)) { console_error("無法有寫入的權限!"); } $data = load_view($temp_path . 'search.php', array('name' => $name, 'class_suffix' => $class_suffix)); if (!write_file($model_path = $searches_path . ucfirst(camelize($name . $class_suffix)) . EXT, $data)) { console_error("新增 search 失敗!"); } array_push($results, $model_path); return $results; }
function process($post_data, $download = true, $delete = true) { $new_view_form = ''; $edit_view_form = ''; $column_default = ''; $columns = ''; $sortable_columns = ''; $form_submit_fields = ''; $form_fields = ''; $form_single_default = ''; $form_validation = ''; $database_schema = ''; foreach ($post_data['fields'] as $key => $field) { if (!empty($field)) { $field_label = ucwords(strtolower(str_replace('_', ' ', $field))); $field_type = $post_data['fields_type'][$key]; $required = isset($post_data['fields_required'][$key]) ? "required=\"required\"" : ""; switch ($field_type) { case 'text': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="text" name="{$field}" id="{$field}" class="regular-text" value="" {$required} /> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="text" name="{$field}" id="{$field}" class="regular-text" value="<?php echo esc_attr( \$item->{$field} ); ?>" {$required} /> </td> </tr> EOD; break; case 'textarea': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <textarea name="{$field}" id="{$field}" rows="5" cols="30" {$required}></textarea> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <textarea name="{$field}" id="{$field}" rows="5" cols="30x" {$required}><?php echo esc_attr( \$item->{$field} ); ?></textarea> </td> </tr> EOD; break; case 'number': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="number" name="{$field}" id="{$field}" class="regular-text" value="" {$required} /> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="number" name="{$field}" id="{$field}" class="regular-text" value="<?php echo esc_attr( \$item->{$field} ); ?>" {$required} /> </td> </tr> EOD; break; case 'email': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="email" name="{$field}" id="{$field}" class="regular-text" value="" {$required} /> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="email" name="{$field}" id="{$field}" class="regular-text" value="<?php echo esc_attr( \$item->{$field} ); ?>" {$required} /> </td> </tr> EOD; break; case 'select': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <select name="{$field}"> <option>Your Option</option> </select> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input name="users_can_register" type="checkbox" id="users_can_register"> </td> </tr> EOD; break; case 'checkbox': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <label for="{$field}"> <input name="{$field}" type="checkbox" id="{$field}" value="1"> Confirm </label> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <label for="{$field}"> <input name="{$field}" type="checkbox" id="{$field}" value="1"> Confirm </label> </td> </tr> EOD; break; case 'radio': $new_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <label for="{$field}"> <input type="radio" name="{$field}" value="yes"> <input type="radio" name="{$field}" value="no"> Confirm </label> </td> </tr> EOD; $edit_view_form .= <<<EOD <tr class="row-{$field}"> <th scope="row"> <label for="{$field}"><?php _e( '{$field_label}', '%%textdomain%%' ); ?></label> </th> <td> <input type="text" name="{$field}" id="{$field}" class="regular-text" value="<?php echo esc_attr( \$item->{$field} ); ?>" {$required} /> </td> </tr> EOD; break; } $column_default .= "case '{$field}':\n"; $columns .= "'{$field}' => __( '{$field_label}', '%%textdomain%%' ),\n"; $sortable_columns .= "'{$field}' => array( '{$field}', true ),\n"; if ($field_type == 'textarea') { $form_submit_fields .= "\${$field} = isset( \$_POST['{$field}'] ) ? wp_kses_post( \$_POST['{$field}'] ) : '';\n"; // Database schema generate $database_schema .= "{$field} text NOT NULL,\n"; } else { $form_submit_fields .= "\${$field} = isset( \$_POST['{$field}'] ) ? sanitize_text_field( \$_POST['{$field}'] ) : '';\n"; // Database schema generate $database_schema .= "{$field} varchar(255) DEFAULT '' NOT NULL,\n"; } $form_fields .= "'{$field}' => \${$field},\n"; $form_single_default .= "'{$field}' => '',\n"; if (isset($post_data['fields_required'][$key])) { $form_validation .= "if ( ! \${$field} ) {\n \$errors[] = __( 'Error: {$field_label} is required', '%%textdomain%%' );\n }"; } } } $data['plugin_name'] = strtolower($post_data['plugin_name']); $data['plugin_name_u'] = str_replace(' ', '_', $data['plugin_name']); $data['plugin_name_dash'] = str_replace(' ', '-', $data['plugin_name']); $data['plugin_name_cap'] = ucwords($data['plugin_name']); $data['plugin_name_cap_u'] = str_replace(' ', '_', $data['plugin_name_cap']); $data['plugin_url'] = $post_data['plugin_url']; $data['plugin_description'] = $post_data['plugin_description']; $data['plugin_version'] = $post_data['plugin_version']; $data['plugin_author'] = $post_data['plugin_author']; $data['plugin_author_url'] = $post_data['plugin_author_url']; $data['crud_name'] = strtolower($post_data['crud_name']); $data['crud_name_cap'] = ucwords($data['crud_name']); $data['crud_name_singular'] = singularize($data['crud_name']); $data['crud_name_singular_cap'] = ucwords($data['crud_name_singular']); $data['plugin_page'] = strtolower($data['plugin_name_dash']); $data['textdomain'] = $post_data['textdomain']; $data['prefix'] = $post_data['prefix']; // Getting contents from stubs file $plugin_main_file = file_get_contents(dirname(__FILE__) . '/stubs/plugin-name.stub'); $plugin_uninstall_file = file_get_contents(dirname(__FILE__) . '/stubs/uninstall.stub'); $admin_menu_file = file_get_contents(dirname(__FILE__) . '/stubs/class-admin-menu.stub'); $form_handler_file = file_get_contents(dirname(__FILE__) . '/stubs/class-form-handler.stub'); $crud_functions_file = file_get_contents(dirname(__FILE__) . '/stubs/crud-name-functions.stub'); $crud_functions_file = file_get_contents(dirname(__FILE__) . '/stubs/crud-name-functions.stub'); $crud_wp_list_table_file = file_get_contents(dirname(__FILE__) . '/stubs/class-crud-name-list-table.stub'); $crud_list_view_file = file_get_contents(dirname(__FILE__) . '/stubs/views/crud-name.stub'); $crud_new_view_file = file_get_contents(dirname(__FILE__) . '/stubs/views/crud-name-singular-new.stub'); $crud_edit_view_file = file_get_contents(dirname(__FILE__) . '/stubs/views/crud-name-singular-edit.stub'); $crud_single_view_file = file_get_contents(dirname(__FILE__) . '/stubs/views/crud-name-singular-single.stub'); // Replacing database schema $plugin_main_file = str_replace("%%database_schema%%", $database_schema, $plugin_main_file); // Replacing wp_list_table file data $crud_wp_list_table_file = str_replace("%%column_default%%", $column_default, $crud_wp_list_table_file); $crud_wp_list_table_file = str_replace("%%columns%%", $columns, $crud_wp_list_table_file); $crud_wp_list_table_file = str_replace("%%sortable_columns%%", $sortable_columns, $crud_wp_list_table_file); $crud_functions_file = str_replace("%%form_single_default%%", $form_single_default, $crud_functions_file); $form_handler_file = str_replace("%%form_submit_fields%%", $form_submit_fields, $form_handler_file); $form_handler_file = str_replace("%%form_fields%%", $form_fields, $form_handler_file); // Repacing form html $crud_new_view_file = str_replace("%%new_view_form%%", $new_view_form, $crud_new_view_file); $crud_edit_view_file = str_replace("%%edit_view_form%%", $edit_view_form, $crud_edit_view_file); // Replacing user defined keyword foreach ($data as $key => $value) { $plugin_main_file = str_replace("%%{$key}%%", $value, $plugin_main_file); $plugin_uninstall_file = str_replace("%%{$key}%%", $value, $plugin_uninstall_file); $crud_functions_file = str_replace("%%{$key}%%", $value, $crud_functions_file); $admin_menu_file = str_replace("%%{$key}%%", $value, $admin_menu_file); $form_handler_file = str_replace("%%{$key}%%", $value, $form_handler_file); $crud_wp_list_table_file = str_replace("%%{$key}%%", $value, $crud_wp_list_table_file); $crud_list_view_file = str_replace("%%{$key}%%", $value, $crud_list_view_file); $crud_new_view_file = str_replace("%%{$key}%%", $value, $crud_new_view_file); $crud_edit_view_file = str_replace("%%{$key}%%", $value, $crud_edit_view_file); $crud_single_view_file = str_replace("%%{$key}%%", $value, $crud_single_view_file); } // Checking/Creating plugin directory $plugin_dir = dirname(__FILE__) . '/plugins/' . $data['plugin_name_dash'] . '/'; if (!is_dir($plugin_dir)) { mkdir($plugin_dir, 0777); } // Creating plugin main file file_put_contents($plugin_dir . $data['plugin_name_dash'] . '.php', $plugin_main_file); // Creating plugin uninstall file file_put_contents($plugin_dir . 'uninstall.php', $plugin_uninstall_file); // Creating plugin main file if (!is_dir($plugin_dir . 'includes/')) { mkdir($plugin_dir . 'includes/', 0777); } $admin_dir = $plugin_dir . 'includes/admin/'; if (!is_dir($admin_dir)) { mkdir($admin_dir, 0777); } // Creating admin menu file file_put_contents($admin_dir . 'class-admin-menu.php', $admin_menu_file); // Creating form handler file file_put_contents($admin_dir . 'class-form-handler.php', $form_handler_file); // Creating functions file file_put_contents($plugin_dir . 'includes/' . $data['crud_name'] . '-functions.php', $crud_functions_file); // Creating plugin main file file_put_contents($plugin_dir . 'includes/' . 'class-' . $data['crud_name'] . '-list-table.php', $crud_wp_list_table_file); if (!is_dir($admin_dir . 'views/')) { mkdir($admin_dir . 'views/', 0777); } // Creating plugin main file file_put_contents($admin_dir . 'views/' . $data['crud_name'] . '.php', $crud_list_view_file); // Creating plugin main file file_put_contents($admin_dir . 'views/' . $data['crud_name_singular'] . '-new.php', $crud_new_view_file); // Creating plugin main file file_put_contents($admin_dir . 'views/' . $data['crud_name_singular'] . '-edit.php', $crud_edit_view_file); // Creating plugin main file file_put_contents($admin_dir . 'views/' . $data['crud_name_singular'] . '-single.php', $crud_single_view_file); zipDir($plugin_dir, $data['plugin_name_dash'] . '.zip', $download); // Deleting existing plugin or module files if (file_exists($data['plugin_name_dash'] . '.zip')) { unlink($data['plugin_name_dash'] . '.zip'); } $dir = dirname(__FILE__) . '/plugins/'; $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); foreach ($ri as $file) { chmod($file, 777); $file->isDir() ? rmdir($file) : unlink($file); } return true; }
/** * Saves current Model in the table * * If the Model represents a new data set, it will be added as a new row to the * table. If, on the other hand it represents an existing row, the existing row * will be updated. Upon insertion, the id, created_at and updated_at fields * get filled. Upon update, only the updated_at field gets filled. * * If insertion/update is succesfull, the exists property is set to true, and * the modified property is set to false - so you need to modify the model * again to be able to perform a save. * * @return boolean */ public function save($related_model = null) { $result = true; if ($this->validates() === true) { foreach ($this->belongs_to as $type => $relation) { if (isset($this->relational_data[$relation])) { if ($this->relational_data[$relation]->modified() === true) { if ($this->relational_data[$relation]->validates() === true) { $result = $this->relational_data[$relation]->save($this); } } } } if ($this->exists === true && $this->modified === true) { if ($this->connection->is_column_of('updated_at', $this->table)) { $this->updated_at = $this->connection->now(); } $result = $this->connection->update($this->table, $this->data, 'id=' . $this->id); } elseif ($this->modified === true) { if ($this->connection->is_column_of('created_at', $this->table)) { $this->created_at = $this->connection->now(); } if ($this->connection->is_column_of('updated_at', $this->table)) { $this->updated_at = $this->connection->now(); } if ($related_model !== null && $this->relation() === true) { $method = $this->relation_type . '_create'; $result = $this->connection->{$method}($this->table, $this->data, $related_model); } else { $result = $this->connection->create($this->table, $this->data); } $this->id = $this->connection->last_id(); } if ($related_model !== null && isset($related_model->id) && isset($this->id)) { if ($this->relation_type === 'has_and_belongs_to_many') { $relation_table = implode('_', s($related_model->table(), $this->table())); $local = singularize($this->table()) . '_id'; $local_id = $this->id; $foreign = singularize($related_model->table()) . '_id'; $foreign_id = $related_model->id; $query = "select * from `{$relation_table}` where `{$foreign}`='{$foreign_id}' and `{$local}`='{$local_id}';"; $relation_exists = $this->connection->query($query); if ($relation_exists->rowCount() === 0) { $query = "insert into `{$relation_table}` set `{$foreign}`='{$foreign_id}', `{$local}`='{$local_id}';"; $return = $this->connection->exec($query); } } } foreach (array_merge($this->has_one, $this->has_many, $this->has_and_belongs_to_many) as $type => $relation) { if (isset($this->relational_data[$relation])) { if ($this->relational_data[$relation]->modified() === true) { if ($this->relational_data[$relation]->validates() === true) { $result = $this->relational_data[$relation]->save($this); } } } } if ($result !== false) { $this->exists = true; $this->modified = false; $result = true; } } else { $result = false; } return $result; }
function replaceFront($name, $tabla, $campos) { $componentsite = 'com_' . $name . '/site/'; $rutas = array(); // creo un array con las rutas de los archivos $rutas[] = $componentsite . 'controllers/'; $rutas[] = $componentsite . 'controllers/table.php'; $rutas[] = $componentsite . 'controllers/tables.php'; $rutas[] = $componentsite . 'helpers/'; $rutas[] = $componentsite . 'helpers/component.php'; $rutas[] = $componentsite . 'language/'; $rutas[] = $componentsite . 'models/'; $rutas[] = $componentsite . 'models/fields/'; $rutas[] = $componentsite . 'models/forms/'; $rutas[] = $componentsite . 'models/table.php'; $rutas[] = $componentsite . 'models/tables.php'; $rutas[] = $componentsite . 'views/'; $rutas[] = $componentsite . 'views/table/'; $rutas[] = $componentsite . 'views/table/tmpl'; $rutas[] = $componentsite . 'views/table/tmpl/default.xml'; $rutas[] = $componentsite . 'views/table/tmpl/default.php'; $rutas[] = $componentsite . 'views/table/tmpl/index.html'; // ruta necesaria para limpiar $rutas[] = $componentsite . 'views/table/index.html'; // ruta necesaria para limpiar $rutas[] = $componentsite . 'views/table/view.html.php'; $rutas[] = $componentsite . 'views/tables/'; $rutas[] = $componentsite . 'views/tables/tmpl/'; $rutas[] = $componentsite . 'views/tables/tmpl/default.xml'; $rutas[] = $componentsite . 'views/tables/tmpl/default.php'; $rutas[] = $componentsite . 'views/tables/tmpl/index.html'; // ruta necesaria para limpiar $rutas[] = $componentsite . 'views/tables/view.html.php'; $rutas[] = $componentsite . 'views/tables/index.html'; // ruta necesaria para limpiar $rutas[] = $componentsite . 'component.php'; $rutas[] = $componentsite . 'controller.php'; $rutas[] = $componentsite . 'router.php'; $rutaOK = ""; // recorro las rutas foreach ($rutas as $r) { // condiciones para copias de archivos if (strpos($r, 'tables') !== false) { $rutaOK = str_replace('tables', $tabla, $r); echo "copiando1 {$r} --> {$rutaOK} <br />"; if (esArchivo($rutaOK)) { duplica($r, $rutaOK, $name, $tabla); replace($rutaOK, $name, $tabla, $campos); } else { if (!file_exists($rutaOK)) { full_copy($r, $rutaOK); } } } elseif (strpos($r, 'table') !== false) { $rutaOK = str_replace('table', singularize($tabla), $r); echo "copiando2 {$r} --> {$rutaOK} <br />"; if (esArchivo($rutaOK)) { duplica($r, $rutaOK, $name, $tabla); replace($rutaOK, $name, $tabla, $campos); } else { if (!file_exists($rutaOK)) { full_copy($r, $rutaOK); } } } elseif (strpos($r, 'component') !== false) { $rutaOK = str_replace('component', $name, $r); echo "copiando {$r} --> {$rutaOK} <br />"; if (esArchivo($rutaOK)) { duplica($r, $rutaOK, $name, $tabla); replace($rutaOK, $name, $tabla, $campos); } else { if (!file_exists($rutaOK)) { full_copy($r, $rutaOK); } } } else { $rutaOK = $r; if (esArchivo($rutaOK)) { echo "copiando {$r} to {$rutaOK} <br />"; // duplica($r, $rutaOK, $name, $tabla); replace($rutaOK, $name, $tabla, $campos); } } } limpiar($rutas); }
/** * @dataProvider provide_irregular */ public function test_irregular($singular, $plural) { $this->assertEquals($singular, singularize($plural, 'tr')); $this->assertEquals($plural, pluralize($singular, 'tr')); }
function class_name($string) { if (is_object($string)) { $string = get_class($string); } $string = humanize(singularize($string)); $string = str_replace(' ', '', $string); $string = preg_replace('/Obj$/', '', $string); return $string; }