Code sniffer for for converting snake_case to camelCase - coding-style

I need a code sniffer for converting all the variables in all of my PHP file from snake_case to camelCase.
I don't need the functions which do it in php on a string, I want to convert the variables in my PHP files to camelCase.
I appreciate you in advanced.

I found a way to do it.
I integrate the code for cakePHP (There is the file with ctp extension and the variable passed to view by set function).
Save the below code as tocamelcase.php
php tocamelcase.php the/path/of/your/app
file content:
<?php
function snakeToCamel($val) {
preg_match('#^_*#', $val, $underscores);
$underscores = current($underscores);
$camel = str_replace('||||', '', ucwords(str_replace('_', '||||', $val), '||||'));
$camel = strtolower(substr($camel, 0, 1)).substr($camel, 1);
return $underscores.$camel;
}
function convert($str) {
global $j;
$name = '/(\$[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
'(->[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
'(::[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
'(\sfunction\s+[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
'(\$this->set\(\'[a-zA-Z0-9]+_[a-zA-Z0-9_]+\'\,)|'.
'(\$this->set\(\"[a-zA-Z0-9]+_[a-zA-Z0-9_]+\"\,)'.
'/i';
$str = preg_replace_callback($name, function($matches){
return snakeToCamel($matches[0]);
},$str);
return $str;
}
$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$i=1;
foreach($Iterator as $file){
if(substr($file,-4) !== '.php' && substr($file,-4) !== '.ctp')
continue;
echo($i.": ".$file."\n");
$i++;
$out = convert(file_get_contents($file));
file_put_contents($file, $out);
}

Related

php: laravel Storage / File append vs file_put_contents

I'm trying to merge a file chunked in parts and in Laravel Framework 7.30.4 is not working the append method of Storage/File Facade
foreach($files as $file)
{
$content = Storage::get($file);
Storage::append($tmp_file, $content);
}
When I do it with vanilla php works fine:
foreach($files as $file)
{
$content = Storage::get($file);
file_put_contents(storage_path("app/{$tmp_file}"), $content, FILE_APPEND);
}
the md5 hash results is only correct with the vanilla style, what I'm doing wrong in laravel style?
I'm watching with vbindiff tool and the all the file is equal except the last part.
thank you
I see this code in laravel code:
public function append($path, $data, $separator = PHP_EOL)
{
if ($this->exists($path)) {
return $this->put($path, $this->get($path).$separator.$data);
}
return $this->put($path, $data);
}
Solved using NULL as separator:
foreach($files as $file)
{
$content = Storage::get($file);
Storage::append($tmp_file, $content, NULL);
}

How to concatenate variables comes from model in controller

I need to concatenate variables come from model.I send the role_id from controller to model and get the role name according to its id.
controller:
function get_role_name(){
$data['rec']=$this->amodel->get_section();
foreach($data['rec'] as $i)
{
$name['x']=$this->amodel->get_name($i->role_id);
}
$this->load->view('sections',array_merge($data,$name));
}
I write $name['x'].=$this->amodel->get_name($i->role_id); but it shows the error which undefined index:x.How can I concatenate the role name in cotroller to send it to view?
you probably didnt define $name
$name = array();
// your foreach
foreach ()
btw, the concatenating was ok
$var = "foo";
$var .= "foo"
// will result in "foofoo"
If you want to append something using the .= syntax you need to make sure the variable or array exists first.
Try this:
function get_role_name(){
$data['rec']=$this->amodel->get_section();
$name = array();
foreach($data['rec'] as $i) {
if (isset($name['x'])) {
$name['x'] .= $this->amodel->get_name($i->role_id);
} else {
$name['x'] = $this->amodel->get_name($i->role_id);
}
}
$this->load->view('sections',array_merge($data,$name));
}

codeigniter export csv in windows platform

function export_csv(){
$this->load->helper('csv');
if(isset($_POST['term_val'])&&$_POST['term_val']<>'0'){
$term = $this->Search_model->get_term($_POST['term_val']);
$term = json_decode($term);
}else{
$term=array();
}
$orders = $this->Order_model->get_orders_export($term,'place_order');
if(count($orders)>0){
foreach($orders as $order){
$sublist['order_id']= $order->order_number;
$sublist['ship_to']= $order->ship_firstname.' '.$order->ship_lastname;
$sublist['order_date']= date('d-m-Y H:i:s',strtotime($order->ordered_on));
$sublist['email_to']= $order->ship_email;
$sublist['city']= $order->ship_city;
$sublist['pincode']= $order->ship_zip;
$sublist['ship_address']= $order->ship_address1.' , '.$order->ship_address2;
$sublist['phone']= $order->ship_phone;
$sublist['product_name']= $order->name;
$sublist['product_id']= $order->product_id;
$sublist['status']= $order->status;
$sublist1[]= $sublist;
}
$delimiter = ";";
$newline = "\r\n";
$heading[]=array('order_id'=>'Order Id','ship_to'=>'Ship To','order_date'=>'Order Date','email_to'=>'Email To',
'city'=>'City','pincode'=>'Pincode','ship_address'=>'Ship Address','phone'=>'Phone','product_name'=>'Product Name','product_id'=>'Product ID','status'=>'status');
$get_csv=array_to_csv1($sublist1,$heading,$delimiter, $newline);
ob_start();
$filename = "orders_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
// header("Content-type: text/x-csv");
//header("Content-type: text/csv");
// header("Content-type: application/csv");
// header("Content-Disposition: attachment; filename=orders".date('d-M-Y').".csv");
print_r($get_csv);
}else{
redirect($this->config->item('admin_folder').'/orders');
}
}
The above code is the controller function for export CSV and the image is the action taking place when exporting.
Problem : Actually if we export csv using codeigniter it is showing that image as shown above. If we press export csv using codeigniter it it should not show that image , it should directly export csv into excel .
if you want to generate reports in csv format it is very easy with codeigniter. Your model function
function index(){
return $query = $this->db->get('my_table');
//Here you should note i am returning
//the query object instead of
//$query->result() or $query->result_array()
}
Now in controller
function get_report(){
$this->load->model('my_model');
$this->load->dbutil();
$this->load->helper('file');
// get the object
$report = $this->my_model->index();
//pass it to db utility function
$new_report = $this->dbutil->csv_from_result($report);
//Now use it to write file. write_file helper function will do it
write_file('csv_file.csv',$new_report);
//Done
}
No externals are required everything is available in Codeigntier.
The above method will force the file to be downloaded instead of
being opening. Cheers! If you want to write xml file it is easy too.
Just use xml_from_result() method of dbutil and use write_file('xml_file.xml,$new_report)
Visit these links they will help.
Database Utility Class
And
File Helper
***> if you are trying to generate reports in csv format then it will quite
> easy with codeigniter.***
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.

codeigniter parse and replace bbcode

I use BBCode Helper.
helper code:
function parse_bbcode($str = ''){
$find = array(
"'\[v\](.*?)\[/v\]'is"
);
$replace = array(
'<video>\1</video>'
);
return preg_replace($find, $replace, $str);
}
controller:
$this->load->helper('bbcode');
$data['news'] = $this->news_model->get_news($config['per_page'], $this->uri->segment(3, 1));
foreach ($data['news'] as $key=>$val)
{
parse_bbcode($data['news'][$key]['description']);
}
for example i want to replace [v]vid[/v] to vid.
replacement does not work (nothing happens). what I did wrong?
Your regex is wrong.
This works:
$video = "[v]testvid.swf[/v]";
$re = '/\[v](.+)\[\/v\]/i';
$replace = '<video>\1</video>';
echo htmlspecialchars(preg_replace($re, $replace, $video));
Outputs:
<video>testvid.swf</video>
http://regexpal.com/ is a good resource for working out regex issues.

Codeigniter - configure enable_query_strings and form_open

I want to be able to user query strings in this fashion. Domain.com/controller/function?param=5&otherparam=10
In my config file I have
$config['base_url'] = 'http://localhost:8888/test-sites/domain.com/public_html';
$config['index_page'] = '';
$config['uri_protocol'] = 'PATH_INFO';
$config['enable_query_strings'] = TRUE;
The problem that I am getting is that form_open is automatically adding a question mark (?) to my url.
So if I say:
echo form_open('account/login');
it spits out: http://localhost:8888/test-sites/domain.com/public_html/?account/login
Notice the question mark it added right before "account".
How can I fix this?
Any help would be greatly appreciated!
The source of your problem is in the Core Config.php file where the CI_Config class resides. The method site_url() is used by the form helper when you are trying to use form_open function.
Solution would be to override this class with your own. If you are using CI < 2.0 then create your extended class in application/libraries/MY_Config.php, otherwise if CI >= 2.0 then your extended class goes to application/core/MY_Config.php.
Then you need to redefine the method site_url().
class MY_Config extends CI_Config
{
function __construct()
{
parent::CI_Config();
}
public function site_url($uri='')
{
//Copy the method from the parent class here:
if ($uri == '')
{
if ($this->item('base_url') == '')
{
return $this->item('index_page');
}
else
{
return $this->slash_item('base_url').$this->item('index_page');
}
}
if ($this->item('enable_query_strings') == FALSE)
{
//This is when query strings are disabled
}
else
{
if (is_array($uri))
{
$i = 0;
$str = '';
foreach ($uri as $key => $val)
{
$prefix = ($i == 0) ? '' : '&';
$str .= $prefix.$key.'='.$val;
$i++;
}
$uri = $str;
}
if ($this->item('base_url') == '')
{
//You need to remove the "?" from here if your $config['base_url']==''
//return $this->item('index_page').'?'.$uri;
return $this->item('index_page').$uri;
}
else
{
//Or remove it here if your $config['base_url'] != ''
//return $this->slash_item('base_url').$this->item('index_page').'?'.$uri;
return $this->slash_item('base_url').$this->item('index_page).$uri;
}
}
}
}
I hope this helps and I think you are using CI 2.0 that wasn't officially released, this was removed in the official CI 2.0 version
Simpler might be to just set follwing in your config.php
$config['enable_query_strings'] = FALSE;
Was the solution in my case.
If you want to use query string in your url structure, then you should manually type your url structure in the following order:
<domain.com>?c={controller}&m={function}&param1={val}&param2={val}
in the action of the resepective controller you should get the parameter as $_GET['param1']
your code now should look like this
form_open(c=account&m=login&param1=val)
Please let me know if it doesnt work for you.

Resources