Merge branch 'uat' of bitbucket.org:venbainformationtechnology/vb_book into uat

This commit is contained in:
heama 2023-09-28 10:07:02 +05:30
commit 2c8f40a69e
3109 changed files with 5896 additions and 412724 deletions

2
.gitignore vendored
View File

@ -87,7 +87,7 @@ writable/**/*.sqlite
php_errors.log
public/uploads/*
# !public/uploads/index.html
!public/uploads/index.html
#-------------------------
# Composer

View File

@ -1 +0,0 @@
"friendsofphp/php-cs-fixer": "3.13.0",

View File

@ -97,7 +97,26 @@ define('EVENT_PRIORITY_HIGH', 10);
* Constants For Api Integration.
*/
// define('VB_APIURL', 'https://vbp.venbait.in/wp-json/wc/v3/');
// define('VB_BOOKS', VB_APIURL.'products');
// define('VB_CUSTOMERS', VB_APIURL.'customers');
define('product','books');
define('product_column', ["book_id","wp_api_product_id"]);
define('product_child','book_images');
define('product_child_column', ["book_id","wp_api_img_id","book_img_id"]);
define('customer','customers');
define('customer_column', ["customer_id","wp_api_customer_id"]);
define('customer_child','customer_addresses');
define('customer_child_column', ["customer_id","","customer_address_id"]);
define('order','invoice');
define('order_column', ["invoice_id","wp_api_order_id","invoice_child_id"]);
define('order_child','invoiceitems');
define('order_child_column', ["invoice_id","wp_api_line_items_id","customer_id"]);
define('WAAI_TOKEN', '650be030cedb3');
define('WAAI_INSTANCE', '650C383B67BC7');
define('SEND_WAAI_URL', 'https://waai.in/api/send');

View File

@ -28,24 +28,22 @@ class Email extends BaseConfig
/**
* SMTP Server Address
*/
public string $SMTPHost = 'bh-in-11.webhostbox.net';
public string $SMTPHost = 'smtp.sendgrid.net';
/**
* SMTP Username
*/
public string $SMTPUser = 'devbook@mprkv.co.in';
//public string $SMTPUser = 'venbalap08@gmail.com';
public string $SMTPUser = 'apikey';
/**
* SMTP Password
*/
public string $SMTPPass = 'DevBook@2023';
//public string $SMTPPass = 'sganobynfyouaxgs';
public string $SMTPPass = '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';
/**
* SMTP Port
*/
public int $SMTPPort = 465;
public int $SMTPPort = 587;
/**
* SMTP Timeout (in seconds)
@ -60,7 +58,7 @@ class Email extends BaseConfig
/**
* SMTP Encryption. Either tls or ssl
*/
public string $SMTPCrypto = 'ssl';
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap

View File

@ -109,17 +109,20 @@ $routes->get('print_address/(:num)', 'Invoice::print_address/$1');
# Notifications Routes
$routes->get('send_whatsapp_message/', 'Notifications::send_whatsapp_message');
$routes->post('whatsapp_custom_notifications/', 'Notifications::whatsapp_custom_notifications');
$routes->match(['post', 'get'], 'mail_custom_notifications', 'Notifications::mail_custom_notifications');
# Api integration Routes
$routes->group("api", function ($routes) {
// $routes->post("create_products/", "ApiIntegration::save_book_details");
$routes->match(['put', 'post', 'get', 'delete'], 'products', 'ApiIntegration::book_api_integration');
$routes->match(['put', 'post', 'get', 'delete'], 'customers', 'ApiIntegration::customer_api_integration');
$routes->match(['put', 'post', 'get', 'delete'], 'orders', 'ApiIntegration::sales_api_integration');
});
$routes->post('api/(:any)', 'ApiIntegration::api_integration/$1');
// $routes->group("api", function ($routes) {
// // $routes->post("create_products/", "ApiIntegration::save_book_details");
// // $routes->match(['put', 'post', 'get', 'delete'], 'products', 'ApiIntegration::book_api_integration');
// // $routes->match(['put', 'post', 'get', 'delete'], 'customers', 'ApiIntegration::customer_api_integration');
// // $routes->match(['put', 'post', 'get', 'delete'], 'orders', 'ApiIntegration::sales_api_integration');
// });
/*
* --------------------------------------------------------------------

View File

@ -11,94 +11,179 @@ class ApiIntegration extends ResourceController
{
use ResponseTrait;
public function book_api_integration()
{
$request = \Config\Services::request();
$message = "";
public function api_integration($api_request_text) {
$this->logger->info("Api Integration : Request Text = ".$api_request_text);
try {
switch ($this->request) {
case $this->request->is('put'):
$request_data = $this->request->getVar();
$this->logger->info("Api Integration : Request data type = ".gettype($request_data));
if(isset($request_data) && gettype($request_data) === 'object') {$request_data = [$request_data]; $this->logger->info("Api Integration : Request data type = ".gettype($request_data));}
if(count($request_data)>0){
$this->logger->info("Api Integration : Request data count = ".count($request_data));
$this->logger->info("Api Integration : Request data = ".json_encode($request_data));
$i = 0;
$final_response = [];
foreach($request_data as $row_data)
{
$get_response[$i] = $this->call_methods((array)$row_data, $api_request_text);
$final_response[$i] = isset($get_response[$i]['message'])?$get_response[$i]['message']:$get_response[$i];
$i++;
}
// return $this->respond(['status' => 200, 'message' => $final_response,'references'=>$get_response]);
return $this->respond(['status' => 200, 'message' => $final_response]);
}else{
$this->logger->error('Api Integration : Err = Request data Not Found.');
throw new \Exception('Api Request data Not Found.');
}
} catch (\Exception $e) {
// $this->logger->error("Api Integration : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api Integration : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ' : ' . $e->getMessage());
}
}
public function call_methods($row_data, $api_request_text)
{
$parts = explode('_', $api_request_text);
$method = $parts[0];
$table = constant($parts[1]);
$table_column = constant($parts[1].'_column');
$table_child = constant($parts[1].'_child');
// $table_child_column = constant($table.'_child_column');
$this->logger->info("Api CallMethods : method name = ".$method.", table = ".$table.", table child = ".$table_child);
$this->logger->info("Api CallMethods : table = ".$table ." and its column => " .implode(",",$table_column));
try {
switch ($method) {
case "create":
case "update":
try {
// $url = http://localhost/vb_book/api/products?id=795;
$records = (array)$this->request->getVar();
$id = $this->request->getVar('id');
if ($records['id'] == $id) {
$response = $this->save_book_details($records, $id);
} else {
$response = ['status' => 404, 'message' => "ID Mismatched"];
switch ($table) {
case "books":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_book_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Product Ref ID = ".$wordpress_book_id);
$response = $this->save_book_details($records, $wordpress_book_id);
$this->logger->info("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception} ", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case "customers":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_customer_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Customer Ref ID = ".$wordpress_customer_id);
$response = $this->save_customer_details($records, $wordpress_customer_id);
$this->logger->info("Api CallMethods : response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case "invoice":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_order_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Order Ref ID = ".$wordpress_order_id);
$response = $this->save_sales_details($records, $wordpress_order_id);
$this->logger->info("Api CallMethods : response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
default:
$this->logger->error('Api CallMethods : Err = Invaild Api Route.');
throw new \Exception('Api Route Not Available');
}
} catch (\Exception $e) {
return $this->fail('PUT request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
return $this->fail(ucwords($method).' request failed, An error occurred ' .$exception_ends_with);
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
}
break;
case $this->request->is('post'):
case 'delete':
try {
// $url = http://localhost/vb_book/api/products;
$records = (array)$this->request->getVar();
$wordpress_book_id = $records['id'];
$response = $this->save_book_details($records, $wordpress_book_id);
} catch (\Exception $e) {
return $this->fail('POST request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('get'):
try {
// $url = http://localhost/vb_book/api/products?id=795;
// $url = http://localhost/vb_book/api/products;
$id = $this->request->getVar('id');
if ($id) {
$where = ['wp_api_product_id' => (int)$id, 'isactive' => 1];
} else {
$where = ['isactive' => 1];
}
$basic_message = "";
$records = (array)$row_data;
$wordpress_refer_id = $records['id'];
$api_model = new ApiIntegrationModel();
$book_details = $api_model->setTable('books')->where($where);
$response = ['status' => 200, 'message' => "Book Details", "data" => $book_details];
} catch (\Exception $e) {
return $this->fail('GET request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('delete'):
try {
// $url = http://localhost/vb_book/api/products?id=795;
$id = $this->request->getVar('id');
$api_model = new ApiIntegrationModel();
$where = ['isactive' => 1, 'wp_api_product_id' => (int)$id];
$existing_book_data = $api_model->getData('books', $where);
if ((int)count($existing_book_data) > 0) {
$book_id = (int)$existing_book_data[0]->book_id;
$where = ['isactive' => 1, $table_column[1] => (int)$wordpress_refer_id];
$existing_data = $api_model->getData($table, $where);
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", ".$table_column[1]." Ref ID = ".$wordpress_refer_id);
if ((int)count($existing_data) > 0) {
if(isset($existing_data[0]) && gettype($existing_data[0]) === 'object') {$existing_data[0] = (array)$existing_data[0]; $this->logger->info("Api Integration : delete ".$table." array data type = ".gettype($existing_data[0]));}
$primary_key_id = (int)$existing_data[0][$table_column[0]];
$this->logger->info("Api CallMethods : ".$table." its PrimaryKey ID = ".$primary_key_id);
$inactive_data['isactive'] = 0;
$update_where = ['isactive' => 1, 'book_id' => $book_id];
$api_model->updateData('books', $inactive_data, $update_where);
$getExistingBookImageDetails = $api_model->getData('book_images', $update_where);
if ($getExistingBookImageDetails) {
// $update_where = ['book_id' => $book_id];
$api_model->updateData('book_images', $inactive_data, $update_where);
$update_where = ['isactive' => 1, $table_column[0] => $primary_key_id];
$api_model->updateData($table, $inactive_data, $update_where);
$get_existing_child_details = $api_model->getData($table_child, $update_where);
$this->logger->info("Api CallMethods : ".$table." Child Details Count = ".count($get_existing_child_details));
if ($get_existing_child_details) {
$api_model->updateData($table_child, $inactive_data, $update_where);
}
$basic_message = ucwords($table)." Details (ID = ".$primary_key_id.") and ".ucwords($table)." Child Details Are Deleted";
}else{
$basic_message = ucwords($table)." has No Details";
}
$response = ['status' => 200, 'message' => "Book Details and Book Images Details Are Inactived"];
$this->logger->info("Api CallMethods : ".$basic_message);
$response = ['status' => 200, 'message' => $basic_message];
} catch (\Exception $e) {
// Handle DELETE-specific exception
return $this->fail('DELETE request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('DELETE request failed, An error occurred' . $exception_ends_with);
}
break;
default:
throw new \Exception('Unsupported HTTP method');
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Unsupported HTTP method");
// return $this->fail('Unsupported HTTP method');
}
return $this->respond($response);
return $response;
} catch (\Exception $e) {
// Handle the exception, you can log it or return an error response
return $this->fail('An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
// return $this->fail($e->getMessage());
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text)).$exception_ends_with);
return $this->fail('An error occurred ' . $exception_ends_with);
}
}
public function save_book_details($records, $wordpress_book_id)
{
$this->logger->info("Api SaveBookDetails : records count = ".count($records).", wordpress Product Ref ID = ".$wordpress_book_id);
$api_model = new ApiIntegrationModel();
$message = "";
$extensive_correspondence = "";
$basic_message = "";
$book_id = "";
if (count($records) > 0 && !empty($wordpress_book_id)) {
$where = ['wp_api_product_id' => $wordpress_book_id, 'isactive' => 1];
@ -108,11 +193,12 @@ class ApiIntegration extends ResourceController
$where['book_id'] = $book_details['book_id'];
} // update means bookid where condition added : else no where condition added.
$countAll = $api_model->countAll('books', $where);
$this->logger->info(($countAll) ? "Api SaveBookDetails : in wordpress product ref ID = ".$wordpress_book_id." is available on Book table and its PrimaryKey = ".$book_id : "Api SaveBookDetails : in wordpress product ref ID = ".$wordpress_book_id." Not available on Book table");
$publisher = '';
$language = '';
$attributes = $records['attributes'];
if (count($attributes) > 0) {
foreach ($attributes as $att) {
if (isset($att->name) && $att->name == "Publisher") {
@ -139,24 +225,31 @@ class ApiIntegration extends ResourceController
$book_data['business_id'] = 1;
$images = $records['images'];
$i = 0;
if ((int)$countAll == 0) {
$insert_result = $api_model->insertData('books', $book_data);
$last_insert_book_id = $insert_result['info'];
$message .= $insert_result['info'] ? "Book id : " . $insert_result['info']
$extensive_correspondence .= $insert_result['info'] ? "Book id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Book id : " . $insert_result['info'] : "Book details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveBookDetails : Book id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveBookDetails : Err = ".$insert_result['err']):"";
} else {
$last_insert_book_id = $book_id;
$book_where = ['book_id' => $book_id, 'isactive' => 1, 'wp_api_product_id' => $wordpress_book_id];
$update_result = $api_model->updateData('books', $book_data, $book_where);
$message .= $update_result['info'] ? "Book id : " . $last_insert_book_id . " ( " . $update_result['info'] . ")"
$extensive_correspondence .= $update_result['info'] ? "Book id : " . $last_insert_book_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Book id : " . $last_insert_book_id;
$update_result['info'] ? $this->logger->info("Api SaveBookDetails : Book id : " . $last_insert_book_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveBookDetails : Err = ".$update_result['err']):"";
}
$book_image_data = [];
$this->logger->info("Api SaveBookDetails : Book images count : " .count($images));
if (count($images) > 0 && $last_insert_book_id != "") {
$message .= " Its have " . count($images) . " Images ,";
$extensive_correspondence .= " Its have " . count($images) . " Images ,";
$basic_message .= " Its have " . count($images) . " Images";
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
$where = ['book_id' => (int)$last_insert_book_id, 'isactive' => 1];
$existing_images = $api_model->getData('book_images', $where);
$request_images = (array)$images;
@ -174,11 +267,14 @@ class ApiIntegration extends ResourceController
}
if (!empty($filteringExistingImagesWpApiId)) {
$this->logger->info("Api SaveBookDetails : Incoming Images Wp Id " .implode(",",$filteringRequestedImagesWpApiId));
$this->logger->info("Api SaveBookDetails : Existing Images Wp Id " .implode(",",$filteringExistingImagesWpApiId));
$A = $filteringExistingImagesWpApiId;
$B = $filteringRequestedImagesWpApiId;
$missingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonElements = array_intersect($A, $B);
if (!empty($missingValues)) {
$this->logger->info("Api SaveBookDetails : Missing Images Wp Id " .implode(",",$missingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'book_id' => (int)$last_insert_book_id];
$inactive_whereIn[0] = 'wp_api_img_id';
$inactive_whereIn[1] = $missingValues;
@ -195,7 +291,9 @@ class ApiIntegration extends ResourceController
$whereIn = null;
}
$lastestActiveBookImageData = $api_model->getData('book_images', $where, $whereIn);
$this->logger->info("Api SaveBookDetails : lastest Active Book Image Data Count " .count($lastestActiveBookImageData));
$book_image_data = [];
$i = 0;
foreach ($images as $img) {
$bookImgId = null;
// Iterate through the array and find the 'book_img_id' based on 'wp_api_img_id'
@ -214,106 +312,30 @@ class ApiIntegration extends ResourceController
$book_image_data[$i]['isactive'] = 1;
$book_image_data[$i]['wp_api_img_id'] = $img->id;
$book_image_data[$i]['book_img_id'] = $bookImgId;
$this->logger->info("Api SaveBookDetails : Image Data = $i ");
$i++;
} // image loop closed
$message .= (!empty($book_image_data) ? $api_model->insertAndUpdateChildDetails($book_image_data, 'book_images', 'book_img_id') : []);
$extensive_correspondence .= (!empty($book_image_data) ? $api_model->insertAndUpdateChildDetails($book_image_data, 'book_images', 'book_img_id') : "");
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
} //image count closed
$response = ['status' => 200, 'message' => $message];
else{
$this->logger->error("Api SaveBookDetails : Err = Image Data Not Found");
}
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
} //if cond. closed
else {
$response = ['status' => 204, 'message' => 'Data No Found'];
$this->logger->error("Api SaveBookDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data Not Found'];
}
return $response;
}
public function customer_api_integration()
{
$request = \Config\Services::request();
$message = "";
try {
switch ($this->request) {
case $this->request->is('put'):
try {
// $url = http://localhost/vb_book/api/customers?id=795;
$records = (array)$this->request->getVar();
$id = $this->request->getVar('id');
if ($records['id'] == $id) {
$response = $this->save_customer_details($records, $id);
} else {
$response = ['status' => 404, 'message' => "ID Mismatched"];
}
} catch (\Exception $e) {
return $this->fail('PUT request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $this->request->is('post'):
try {
// $url = http://localhost/vb_book/api/customers;
$records = (array)$this->request->getVar();
$wordpress_customer_id = $records['id'];
$response = $this->save_customer_details($records, $wordpress_customer_id);
} catch (\Exception $e) {
return $this->fail('POST request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('get'):
try {
// $url = http://localhost/vb_book/api/customers?id=795;
// $url = http://localhost/vb_book/api/customers;
$id = $this->request->getVar('id');
if ($id) {
$where = ['wp_api_customer_id' => (int)$id, 'isactive' => 1];
} else {
$where = ['isactive' => 1];
}
$api_model = new ApiIntegrationModel();
$customer_details = $api_model->setTable('customers')->where($where);
$response = ['status' => 200, 'message' => "Customer Details", "data" => $customer_details];
} catch (\Exception $e) {
return $this->fail('GET request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('delete'):
try {
// $url = http://localhost/vb_book/api/customers?id=795;
$id = $this->request->getVar('id');
$api_model = new ApiIntegrationModel();
$where = ['isactive' => 1, 'wp_api_customer_id' => (int)$id];
$existing_customer_data = $api_model->getData('customers', $where);
if ((int)count($existing_customer_data) > 0) {
$customer_id = (int)$existing_customer_data[0]->customer_id;
$inactive_data['isactive'] = 0;
$update_where = ['isactive' => 1, 'customer_id' => $customer_id];
$api_model->updateData('customers', $inactive_data, $update_where);
$getExistingCustomerImageDetails = $api_model->getData('customer_addresses', $update_where);
if ($getExistingCustomerImageDetails) {
$api_model->updateData('customer_addresses', $inactive_data, $update_where);
}
}
$response = ['status' => 200, 'message' => "customer Details and Customer Addresses Details Are Inactived"];
} catch (\Exception $e) {
// Handle DELETE-specific exception
return $this->fail('DELETE request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
default:
throw new \Exception('Unsupported HTTP method');
// return $this->fail('Unsupported HTTP method');
}
return $this->respond($response);
} catch (\Exception $e) {
// Handle the exception, you can log it or return an error response
return $this->fail('An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
// return $this->fail($e->getMessage());
}
}
public function save_customer_details($records, $wordpress_customer_id)
{
$this->logger->info("Api SaveCustomerDetails : records count = ".count($records).", wordpress Customer Ref ID = ".$wordpress_customer_id);
$api_model = new ApiIntegrationModel();
$message = "";
$extensive_correspondence = "";
$basic_message = "";
$customer_id = "";
if (count($records) > 0 && !empty($wordpress_customer_id)) {
$where = ['wp_api_customer_id' => $wordpress_customer_id, 'isactive' => 1];
@ -322,7 +344,9 @@ class ApiIntegration extends ResourceController
$customer_id = $customer_details['customer_id'];
$where['customer_id'] = $customer_details['customer_id'];
}
$countAll = $api_model->countAll('customers', $where);
$this->logger->info(($countAll) ? "Api SaveCustomerDetails : in wordpress customer ref ID = ".$wordpress_customer_id." is available on customer table and its PrimaryKey = ".$customer_id : "Api SaveBookDetails : in wordpress Customer ref ID = ".$wordpress_customer_id." Not available on Customer table");
$customer_data['first_name'] = $records['first_name'];
$customer_data['last_name'] = $records['last_name'];
@ -339,27 +363,36 @@ class ApiIntegration extends ResourceController
if ((int)$countAll == 0) {
$insert_result = $api_model->insertData('customers', $customer_data);
$last_insert_customer_id = $insert_result['info'];
$message .= $insert_result['info'] ? "Customer id : " . $insert_result['info']
$extensive_correspondence .= $insert_result['info'] ? "Customer id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Customer id : " . $insert_result['info'] : "Customer details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveCustomerDetails : Customer id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveCustomerDetails : Err = ".$insert_result['err']):"";
} else {
$last_insert_customer_id = $customer_id;
$customer_where = ['customer_id' => $customer_id, 'isactive' => 1, 'wp_api_customer_id' => $wordpress_customer_id];
$update_result = $api_model->updateData('customers', $customer_data, $customer_where);
$message .= $update_result['info'] ? "Customer id : " . $last_insert_customer_id . " ( " . $update_result['info'] . ")"
$extensive_correspondence .= $update_result['info'] ? "Customer id : " . $last_insert_customer_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Customer id : " . $last_insert_customer_id;
$update_result['info'] ? $this->logger->info("Api SaveCustomerDetails : Customer id : " . $last_insert_customer_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveCustomerDetails : Err = ".$update_result['err']):"";
}
$i = 0; $customer_billing_address_data = [];
$j = 0; $customer_shipping_address_data = [];
if(isset($billing) && gettype($billing) === 'object') {$billing = [$billing];}
if(isset($shipping) && gettype($shipping) === 'object') {$shipping = [$shipping];}
$this->logger->info("Api SaveCustomerDetails : billing count : " .count($billing));
$this->logger->info("Api SaveCustomerDetails : shipping count : " .count($shipping));
// echo "Customer ID : ".$last_insert_customer_id." have Billing address = ".count($billing)." and Shipping address = ".count($shipping)." <br/>";
if (count($billing) > 0 && $last_insert_customer_id != "") {
$message .= " Its have " . count($billing) . " Billing address ,";
$extensive_correspondence .= " Its have " . count($billing) . " Billing address ,";
$basic_message .= " Its have " . count($billing) . " Billing address ,";
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1, 'address_type'=>1];
$existing_billing = $api_model->getData('customer_addresses', $where);
$request_billing = (array)$billing;
@ -377,11 +410,14 @@ class ApiIntegration extends ResourceController
}
if (!empty($filteringExistingBillingAddress)) {
$this->logger->info("Api SaveCustomerDetails : Incoming billing " .implode(",",$filteringExistingBillingAddress));
$this->logger->info("Api SaveCustomerDetails : Existing billing " .implode(",",$filteringRequestedBillingAddress));
$A = $filteringExistingBillingAddress;
$B = $filteringRequestedBillingAddress;
$missingBillingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonBillingElements = array_intersect($A, $B);
if (!empty($missingBillingValues)) {
$this->logger->info("Api SaveCustomerDetails : Missing billing " .implode(",",$missingBillingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'customer_id' => (int)$last_insert_customer_id,'address_type'=>1];
$inactive_whereIn[0] = 'address_1';
$inactive_whereIn[1] = $missingBillingValues;
@ -398,7 +434,7 @@ class ApiIntegration extends ResourceController
$whereIn = null;
}
$lastestActiveBillingAdressData = $api_model->getData('customer_addresses', $where, $whereIn);
$this->logger->info("Api SaveCustomerDetails : lastest Active billing Data Count " .count($lastestActiveBillingAdressData));
foreach ($billing as $bill) {
$billingAddressId = null;
if ($bill->first_name != '') {
@ -424,17 +460,21 @@ class ApiIntegration extends ResourceController
$customer_billing_address_data[$i]['email'] = isset($bill->email) ? $bill->email : '';
$customer_billing_address_data[$i]['mobile_no'] = isset($bill->phone) ? $bill->phone : '';
$customer_billing_address_data[$i]['customer_address_id'] = $billingAddressId;
$this->logger->info("Api SaveCustomerDetails : Billing address has a value and Inserted ");
$i++;
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Billing address has a value and Inserted ".$i." <br/>";
}else{
$this->logger->info("Api SaveCustomerDetails : Billing address has no value ");
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Billing address has no value; <br/>";
}
}
$message .= (!empty($customer_billing_address_data) ? $api_model->insertAndUpdateChildDetails($customer_billing_address_data, 'customer_addresses', 'customer_address_id') : []);
$extensive_correspondence .= (!empty($customer_billing_address_data) ? $api_model->insertAndUpdateChildDetails($customer_billing_address_data, 'customer_addresses', 'customer_address_id') : "");
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
}
if (count($shipping) > 0 && $last_insert_customer_id != "") {
$message .= " Its have " . count($shipping) . " Shipping address ,";
$extensive_correspondence .= " Its have " . count($shipping) . " Shipping address ,";
$basic_message .= " Its have " . count($shipping) . " Shipping address .";
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1, 'address_type'=>2];
$existing_shipping = $api_model->getData('customer_addresses', $where);
$request_shipping = (array)$shipping;
@ -452,6 +492,8 @@ class ApiIntegration extends ResourceController
}
if (!empty($filteringExistingShippingAddress)) {
$this->logger->info("Api SaveCustomerDetails : Incoming shipping " .implode(",",$filteringExistingShippingAddress));
$this->logger->info("Api SaveCustomerDetails : Existing shipping " .implode(",",$filteringExistingShippingAddress));
$A = $filteringExistingShippingAddress;
$B = $filteringRequestedShippingAddress;
$missingShippingValues = array_diff($A, $B); //Find difference element in Existing Images only
@ -461,6 +503,7 @@ class ApiIntegration extends ResourceController
$inactive_whereIn[0] = 'address_1';
$inactive_whereIn[1] = $missingShippingValues;
$api_model->inactiveMissingDetails('customer_addresses', $inactive_where, $inactive_whereIn);
$this->logger->info("Api SaveCustomerDetails : Missing Shipping " .implode(",",$missingShippingValues)." Are inactived");
}
}
}
@ -473,6 +516,7 @@ class ApiIntegration extends ResourceController
$whereIn = null;
}
$lastestActiveShippingAdressData = $api_model->getData('customer_addresses', $where, $whereIn);
$this->logger->info("Api SaveCustomerDetails : lastest Active Shipping Data Count " .count($lastestActiveShippingAdressData));
foreach ($shipping as $ship) {
$shippingAddressId = null;
@ -499,108 +543,34 @@ class ApiIntegration extends ResourceController
$customer_shipping_address_data[$j]['customer_id'] = $last_insert_customer_id;
$customer_shipping_address_data[$j]['address_type'] = 2;
$customer_shipping_address_data[$j]['customer_address_id'] = $shippingAddressId;
$this->logger->info("Api SaveCustomerDetails : Shipping address has a value and Inserted ");
$j++;
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Shipping address has a value and Inserted ".$j." <br/>";
}
else{
$this->logger->info("Api SaveCustomerDetails : Shipping address has no value ");
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Shipping address has no value <br/>";
}
}
$message .= (!empty($customer_shipping_address_data) ? $api_model->insertAndUpdateChildDetails($customer_shipping_address_data, 'customer_addresses', 'customer_address_id') : []);
$extensive_correspondence .= (!empty($customer_shipping_address_data) ? $api_model->insertAndUpdateChildDetails($customer_shipping_address_data, 'customer_addresses', 'customer_address_id') : "");
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
}else{
$this->logger->error("Api SaveCustomerDetails : Err = Address Data Not Found");
}
$response = ['status' => 200, 'message' => $message];
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
} //if cond. closed
else {
$this->logger->error("Api SaveCustomerDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data No Found'];
}
return $response;
}
public function sales_api_integration()
{
$request = \Config\Services::request();
$message = "";
try {
switch ($this->request) {
case $this->request->is('put'):
try {
// $url = http://localhost/vb_book/api/orders?id=795;
$records = (array)$this->request->getVar();
$id = $this->request->getVar('id');
if ($records['id'] == $id) {
$response = $this->save_sales_details($records, $id);
} else {
$response = ['status' => 404, 'message' => "ID Mismatched"];
}
} catch (\Exception $e) {
return $this->fail('PUT request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $this->request->is('post'):
try {
// $url = http://localhost/vb_book/api/orders;
$records = (array)$this->request->getVar();
$wordpress_order_id = $records['id'];
$response = $this->save_sales_details($records, $wordpress_order_id);
} catch (\Exception $e) {
return $this->fail('POST request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('get'):
try {
// $url = http://localhost/vb_book/api/orders?id=795;
// $url = http://localhost/vb_book/api/orders;
$id = $this->request->getVar('id');
if ($id) {
$where = ['wp_api_order_id' => (int)$id, 'isactive' => 1];
} else {
$where = ['isactive' => 1];
}
$api_model = new ApiIntegrationModel();
$invoice_details = $api_model->setTable('invoice')->where($where);
$response = ['status' => 200, 'message' => "Invoice Details", "data" => $invoice_details];
} catch (\Exception $e) {
return $this->fail('GET request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case $request->is('delete'):
try {
// $url = http://localhost/vb_book/api/orders?id=795;
$id = $this->request->getVar('id');
$api_model = new ApiIntegrationModel();
$where = ['isactive' => 1, 'wp_api_order_id' => (int)$id];
$existing_invoice_data = $api_model->getData('invoice', $where);
if ((int)count($existing_invoice_data) > 0) {
$invoice_id = (int)$existing_invoice_data[0]->invoice_id;
$inactive_data['isactive'] = 0;
$update_where = ['isactive' => 1, 'invoice_id' => $invoice_id];
$api_model->updateData('invoice', $inactive_data, $update_where);
$getExistingInvoiceItemsDetails = $api_model->getData('invoiceitems', $update_where);
if ($getExistingInvoiceItemsDetails) {
$api_model->updateData('invoiceitems', $inactive_data, $update_where);
}
}
$response = ['status' => 200, 'message' => "Invoice Details and Invoice Items Details Are Inactived"];
} catch (\Exception $e) {
// Handle DELETE-specific exception
return $this->fail('DELETE request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
default:
throw new \Exception('Unsupported HTTP method');
// return $this->fail('Unsupported HTTP method');
}
return $this->respond($response);
} catch (\Exception $e) {
// Handle the exception, you can log it or return an error response
return $this->fail('An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
// return $this->fail($e->getMessage());
}
}
public function save_sales_details($records, $wordpress_order_id){
$this->logger->info("Api SaveSalesDetails : records count = ".count($records).", wordpress Order Ref ID = ".$wordpress_order_id);
$basic_message="";
$api_model = new ApiIntegrationModel();
$message = "";
$extensive_correspondence = "";
$invoice_id = "";
if (count($records) > 0 && !empty($wordpress_order_id)) {
$where = ['wp_api_order_id' => $wordpress_order_id, 'isactive' => 1];
@ -610,6 +580,7 @@ class ApiIntegration extends ResourceController
$where['invoice_id'] = (int)$invoice_id;
}
$countAll = $api_model->countAll('invoice', $where);
$this->logger->info(($countAll) ? "Api SaveSalesDetails : in wordpress product ref ID = ".$wordpress_order_id." is available on Invoice table and its PrimaryKey = ".$invoice_id : "Api SaveSalesDetails : in wordpress order ref ID = ".$wordpress_order_id." Not available on Invoice table");
$billing_addr = "";$shipping_addr = "";
$lineitems_array = [];
$billing_array = []; $shipping_array = [];
@ -669,22 +640,31 @@ class ApiIntegration extends ResourceController
if ((int)$countAll == 0) {
$insert_result = $api_model->insertData('invoice', $invoice_data);
$last_insert_invoice_id = $insert_result['info'];
$message .= $insert_result['info'] ? "Invoice id : " . $insert_result['info']
$extensive_correspondence .= $insert_result['info'] ? "Invoice id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Invoice id : " . $insert_result['info'] : "Invoice details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$insert_result['err']):"";
} else {
$last_insert_invoice_id = $invoice_id;
$customer_where = ['invoice_id' => $invoice_id, 'isactive' => 1, 'wp_api_order_id' => $wordpress_order_id];
$update_result = $api_model->updateData('invoice', $invoice_data, $customer_where);
$message .= $update_result['info'] ? "Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"
$extensive_correspondence .= $update_result['info'] ? "Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Invoice id : " . $last_insert_invoice_id;
$update_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$update_result['err']):"";
}
$line_item_data = [];
$shipping_line_item_data = [];
$i = 0;$j=0;
$this->logger->info("Api SaveSalesDetails : Invoice items count : " .count($lineitems_array));
if (count($lineitems_array) > 0 && $last_insert_invoice_id != "") {
$message .= " Its have " . count($lineitems_array) . " LineItems ,";
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1];
$extensive_correspondence .= " Its have " . count($lineitems_array) . " LineItems ,";
$basic_message .= " Its have " . count($lineitems_array) . " LineItems";
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1, 'quantity != '=>0];
$existing_invoiceitem = $api_model->getData('invoiceitems', $where);
$request_invoiceitem = (array)$lineitems_array;
@ -701,11 +681,14 @@ class ApiIntegration extends ResourceController
}
if (!empty($filteringExistingInvoiceItemWpApiId)) {
$this->logger->info("Api SaveSalesDetails : Incoming InvoiceItem Wp Id " .implode(",",$filteringRequestedInvoiceItemWpApiId));
$this->logger->info("Api SaveSalesDetails : Existing InvoiceItem Wp Id " .implode(",",$filteringExistingInvoiceItemWpApiId));
$A = $filteringExistingInvoiceItemWpApiId;
$B = $filteringRequestedInvoiceItemWpApiId;
$missingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonElements = array_intersect($A, $B);
if (!empty($missingValues)) {
$this->logger->info("Api SaveSalesDetails : Missing InvoiceItem Wp Id " .implode(",",$missingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'invoice_id' => (int)$last_insert_invoice_id];
$inactive_whereIn[0] = 'wp_api_line_items_id';
$inactive_whereIn[1] = $missingValues;
@ -714,7 +697,7 @@ class ApiIntegration extends ResourceController
}
}
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1];
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1, 'quantity != '=>0];
if (!empty($commonElements)) {
$whereIn[0] = 'wp_api_line_items_id';
$whereIn[1] = $commonElements;
@ -722,6 +705,7 @@ class ApiIntegration extends ResourceController
$whereIn = null;
}
$lastestActiveInvoiceitemsData = $api_model->getData('invoiceitems', $where, $whereIn);
$this->logger->info("Api SaveSalesDetails : lastest Active Invoice Items Data Count " .count($lastestActiveInvoiceitemsData));
foreach ($lineitems_array as $ii) {
$invoiceItemsId = null;
@ -747,17 +731,24 @@ class ApiIntegration extends ResourceController
$line_item_data[$i]['invoice_child_id'] = $invoiceItemsId;
$line_item_data[$i]['wp_api_line_items_id'] = $ii->id;
$line_item_data[$i]['invoice_id'] = $last_insert_invoice_id;
$this->logger->info("Api SaveSalesDetails : Invoiceitem Data inx = $i ");
$i++;
} // line item loop closed
$message .= (!empty($line_item_data) ? $api_model->insertAndUpdateChildDetails($line_item_data, 'invoiceitems', 'invoice_child_id') : []);
$extensive_correspondence .= (!empty($line_item_data) ? $api_model->insertAndUpdateChildDetails($line_item_data, 'invoiceitems', 'invoice_child_id') : "");
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
}
else{
$this->logger->error("Api SaveSalesDetails : Err = Invoice items Data Not Found");
}
$shipping_lineitems_array = $records['shipping_lines'];
$this->logger->info("Api SaveSalesDetails : Shipping Invoice items count : " .count($shipping_lineitems_array));
if (count($shipping_lineitems_array) > 0 && $last_insert_invoice_id != "") {
$message .= " Its have " . count($shipping_lineitems_array) . " shipping details ,";
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1];
$existing_shipping_invoiceitem = $api_model->getData('invoiceitems', $where);
$extensive_correspondence .= " Its have " . count($shipping_lineitems_array) . " shipping details ,";
$basic_message .= " and Its have " . count($shipping_lineitems_array) . " shipping details";
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
$shipping_where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1,'quantity'=>0];
$existing_shipping_invoiceitem = $api_model->getData('invoiceitems', $shipping_where);
$request_shipping_invoiceitem = (array)$shipping_lineitems_array;
$filteringExistingShippingInvoiceItemWpApiId = [];
@ -773,11 +764,15 @@ class ApiIntegration extends ResourceController
}
if (!empty($filteringExistingShippingInvoiceItemWpApiId)) {
$this->logger->info("Api SaveSalesDetails : Incoming InvoiceItem (Shipping) Wp Id " .implode(",",$filteringRequestedShippingInvoiceItemWpApiId));
$this->logger->info("Api SaveSalesDetails : Existing InvoiceItem (Shipping) Wp Id " .implode(",",$filteringExistingShippingInvoiceItemWpApiId));
$A = $filteringExistingShippingInvoiceItemWpApiId;
$B = $filteringRequestedShippingInvoiceItemWpApiId;
$missingShippingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonShippingElements = array_intersect($A, $B);
if (!empty($missingShippingValues)) {
$this->logger->info("Api SaveSalesDetails : Missing InvoiceItem (shipping) Wp Id " .implode(",",$missingShippingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'invoice_id' => (int)$last_insert_invoice_id];
$inactive_whereIn[0] = 'wp_api_line_items_id';
$inactive_whereIn[1] = $missingShippingValues;
@ -786,7 +781,7 @@ class ApiIntegration extends ResourceController
}
}
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1];
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1,'quantity'=>0];
if (!empty($commonShippingElements)) {
$whereIn[0] = 'wp_api_line_items_id';
$whereIn[1] = $commonShippingElements;
@ -794,6 +789,7 @@ class ApiIntegration extends ResourceController
$whereIn = null;
}
$lastestActiveShippingInvoiceitemsData = $api_model->getData('invoiceitems', $where, $whereIn);
$this->logger->info("Api SaveSalesDetails : lastest Active Invoice Item (shipping) Data Count " .count($lastestActiveShippingInvoiceitemsData));
foreach ($shipping_lineitems_array as $sii) {
$shippingInvoiceItemsId = null;
@ -819,17 +815,23 @@ class ApiIntegration extends ResourceController
$shipping_line_item_data[$j]['invoice_child_id'] = $shippingInvoiceItemsId;
$shipping_line_item_data[$j]['wp_api_line_items_id'] = $sii->id;
$shipping_line_item_data[$j]['invoice_id'] = $last_insert_invoice_id;
$this->logger->info("Api SaveSalesDetails : Invoiceitem Data For Shipping inx = $j ");
$j++;
} // line item loop closed
$message .= (!empty($shipping_line_item_data) ? $api_model->insertAndUpdateChildDetails($shipping_line_item_data, 'invoiceitems', 'invoice_child_id') : []);
$extensive_correspondence .= (!empty($shipping_line_item_data) ? $api_model->insertAndUpdateChildDetails($shipping_line_item_data, 'invoiceitems', 'invoice_child_id') : "");
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
}
$response = ['status' => 200, 'message' => $message];
else{
$this->logger->error("Api SaveSalesDetails : Err = Invoice items (Shipping) Data Not Found");
}
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
}
else {
$this->logger->error("Api SaveSalesDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data No Found'];
}
return $response;
}
}
}

View File

@ -36,7 +36,7 @@ class Authentication extends BaseController
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');
$user = $auth_model->where('email', $username)->first();
$user = $auth_model->where(['email'=>$username,'isactive'=>1])->first();
// $this->logger->info("Authenticate: Function Called.");
if (is_null($user)) {
@ -84,7 +84,7 @@ class Authentication extends BaseController
public function auth_confirm_mail()
{
// Get the email address from the request
$email = $this->request->getGet('email');
$mail_id = $this->request->getGet('email');
$url_domain = base_url();
// Validate the email address
@ -99,43 +99,32 @@ class Authentication extends BaseController
// Check if the email exists in the database
$auth_model = new AuthenticationModel();
// $user = $auth_model->where('email', $email)->first();
$where = ['email' => $email, 'isactive' => 1];
// $user = $auth_model->where('email', $mail_id)->first();
$where = ['email' => $mail_id, 'isactive' => 1];
$user = $auth_model->where($where)->first();
if (!$user) {
$this->logger->error('There is no user enteries against given mail');
return redirect()->back()->withInput()->with('error', 'There is no user enteries against given mail');
} else {
$data['email'] = $email;
$data['mail_id'] = $mail_id;
// Generate a unique token for password reset
$token = bin2hex(random_bytes(32));
$content = "Click the link below to reset your password : " . $url_domain . "reset_password?email=" . $email . "&token=" . $token;
// $email = \Config\Services::email();
// $email->setTo('sanjeev.p@venbainfotech.com');
// $email->setFrom('venbalap08@gmail.com', 'BB-VBP');
// $email->setSubject('BB-VBP Password Reset');
// $email->setMessage($content);
$content = "Click the link below to reset your password : " . $url_domain . "auth_reset_password?email=" . $mail_id . "&token=" . $token;
$email = \Config\Services::email();
// $recipient = 'venbalap08@gmail.com';
$recipient = $mail_id;
// $email->setTo('venbalap08@gmail.com');
// $email->setFrom('venbalap08@gmail.com');
// $email->setSubject('Password Reset Testing');
// $email->setMessage('ZXER');
// if ($email->send()) {
// // Email sent successfully
// return view('auth_confirm_mail', $data);
// } else {
// $this->logger->error('Email Not Sended,Try Again');
// return redirect()->back()->withInput()->with('error', 'Email Not Sended,Try Again');
// }
// Compose the email
$email->setTo($recipient);
$email->setFrom('no-reply@tripapprovaltool.com', 'BB-VBP');
$email->setSubject('Email Notification');
// $email->setMessage('This is a notification email from CodeIgniter.');
$email->setMessage($content);
$update_token['reset_link'] = $token;
$auth_model->update($user['user_id'], $update_token);
$data['link'] = $url_domain . "auth_reset_password?email=" . $email . "&token=" . $token;
$data['link'] = $url_domain . "auth_reset_password?email=" . $mail_id . "&token=" . $token;
// Retrieve flashed session data
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
@ -144,7 +133,14 @@ class Authentication extends BaseController
// Here, we'll use the default View class for demonstration purposes
$data['successMessage'] = $successMessage;
$data['validationErrors'] = $validationErrors;
return view('auth_confirm_mail', $data);
// return view('auth_confirm_mail', $data);
if ($email->send()) {
// Email sent successfully
return view('auth_confirm_mail', $data);
} else {
$this->logger->error('Email Not Sended,Try Again');
return redirect()->back()->withInput()->with('error', 'Email Not Sended,Try Again');
}
}
}
@ -264,12 +260,15 @@ class Authentication extends BaseController
$session_uid = get_logged_user_id();
$session_uname = get_logged_name();
$auth_model = new AuthenticationModel();
$details = $auth_model->getheringDetailsForHeader($session_uid);
$data['loggedin_person'] = $session_uname;
$data['loggedin_person_role'] = $details[0]['role'];
$data['favicon'] = $details[0]['favicon'];
$data['profile_picture'] = $details[0]['profile_picture'];
$data['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico");
$data['profile_picture'] = !empty($details[0]['profile_picture']) && file_exists(FCPATH."public/uploads/".$details[0]['profile_picture']) ? base_url("public/uploads/" . $details[0]['profile_picture']) : base_url("public/assets/images/users/avatar-9.jpg");
$data['company_logo_small'] = !empty($details[0]['company_logo_small']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_small']) ? base_url("public/uploads/" . $details[0]['company_logo_small']) : base_url("public/uploads/default_logo.png");
$data['company_logo_large'] = !empty($details[0]['company_logo_large']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_large']) ? base_url("public/uploads/" . $details[0]['company_logo_large']) : base_url("public/uploads/default.png");
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
// Load and display the form view with the above data

View File

@ -74,8 +74,10 @@ abstract class BaseController extends Controller
$data['loggedin_person'] = $session_uname;
$data['loggedin_person_id'] = $session_uid;
$data['loggedin_person_role'] = $details[0]['role'];
$data['favicon'] = $details[0]['favicon'];
$data['profile_picture'] = $details[0]['profile_picture'];
$data['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico");
$data['profile_picture'] = !empty($details[0]['profile_picture']) && file_exists(FCPATH."public/uploads/".$details[0]['profile_picture']) ? base_url("public/uploads/" . $details[0]['profile_picture']) : base_url("public/assets/images/users/avatar-9.jpg");
$data['company_logo_small'] = !empty($details[0]['company_logo_small']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_small']) ? base_url("public/uploads/" . $details[0]['company_logo_small']) : base_url("public/uploads/default_logo.png");
$data['company_logo_large'] = !empty($details[0]['company_logo_large']) && file_exists(FCPATH."public/uploads/".$details[0]['company_logo_large']) ? base_url("public/uploads/" . $details[0]['company_logo_large']) : base_url("public/uploads/default.png");
$data['browser_title'] = $data['company_name'] . ' | ' . $data['company_short_name'] . ' ' . $data['page_name'];
$data['heading'] = $data['page_name'] == "Dashboard" ? 'Welcome to ' . $data['company_name'] : "";
echo view('template/header.php', $data);

View File

@ -12,9 +12,19 @@ class Business extends BaseController
{
helper('session');
if (is_session_active()) {
$session_role = get_user_role();
if (!empty($session_role) && $session_role !== "sadmin") {
$this->logger->info("Buiness: Listing In admin role .");
$where = ['business_id' => (int)get_business_id(), 'isactive' => 1];
} else {
$this->logger->info("Buiness: Listing In Super-admin role .");
$where = ['isactive !=' => NULL];
}
$BusinessModel = new BusinessModel();
$data['page_name'] = 'Buiness Listing';
$data['businesses'] = $BusinessModel->where(['isactive' => 1])->findAll();
$data['businesses'] = $BusinessModel->where($where)->findAll();
// $data['lastQuery'] = $BusinessModel->getLastQuery();
// print_r($data);die;
$this->render_page('business_list', $data);
} else {
return redirect()->to('login');
@ -43,7 +53,7 @@ class Business extends BaseController
{
helper('session');
$session_uid = get_logged_user_id();
$session_role = get_user_role();
$validationRule = [
'user' => [
'label' => 'Image File',
@ -103,8 +113,9 @@ class Business extends BaseController
$BusinessModel->insert($data);
} else {
// It's an update operation
if($session_role === 'sadmin'){
$isactive = $this->request->getPost('bcheckbox');
$data['isactive'] = ($isactive == 'on') ? 1 : 0;
$data['isactive'] = ($isactive == 'on') ? 1 : 0; }
$data['updated_by'] = $session_uid;
$BusinessModel->update($business_id, $data);
}

View File

@ -191,104 +191,4 @@ class Customer extends BaseController
$address_details = $model->where($where)->findAll();
return $address_details;
}
## ApiIntegration For Customer.
public function apiintegration()
{
helper('apiIntegration');
helper('session');
$session_bid = get_business_id();
$session_uid = get_logged_user_id();
$response = perform_http_request('GET', VB_CUSTOMERS);
$message = "";
if (count($response['response']) > 0) {
//$message = "Reponse Count : ".count($response['response'])." <br/>";
echo "Note : This For CrossCheck Purpose 1ly <br/>";
echo "Total Customer API Reponse Count : " . count($response['response']) . " <br/>";
$CustomerModel = new CustomerModel();
$x=0;
foreach ($response['response'] as $row) {
$insertion_data['first_name'] = $row->first_name;
$insertion_data['last_name'] = $row->last_name;
$insertion_data['type'] = $row->role;
$insertion_data['email'] = $row->email;
// $insertion_data['profile_picture'] = $row->avatar_url;
$insertion_data['mode'] = 'online';
$insertion_data['created_by'] = $session_uid;
$insertion_data['business_id'] = $session_bid;
$billing = $row->billing;
$shipping = $row->shipping;
$CustomerModel->insert($insertion_data);
$lastInsertId = $CustomerModel->insertID();
$insertion_baddress_data = [];$insertion_saddress_data = [];
$i = 0; $j = 0;
if(isset($billing) && gettype($billing) === 'object') {$billing = [$billing];}
if(isset($shipping) && gettype($shipping) === 'object') {$shipping = [$shipping];}
echo "Customer ID : ".$lastInsertId." have Billing address = ".count($billing)." and Shipping address = ".count($shipping)." <br/>";
if (count($billing) > 0) {
foreach ($billing as $bill) {
if ($bill->first_name !== '') {
$insertion_baddress_data[$i]['first_name'] = $bill->first_name;
$insertion_baddress_data[$i]['last_name'] = $bill->last_name;
$insertion_baddress_data[$i]['company'] = $bill->company;
$insertion_baddress_data[$i]['address_1'] = $bill->address_1;
$insertion_baddress_data[$i]['address_2'] = $bill->address_2;
$insertion_baddress_data[$i]['city'] = $bill->city;
$insertion_baddress_data[$i]['state'] = $bill->state;
$insertion_baddress_data[$i]['country'] = $bill->country;
$insertion_baddress_data[$i]['postal_code'] = $bill->postcode;
$insertion_baddress_data[$i]['customer_id'] = $lastInsertId;
$insertion_baddress_data[$i]['address_type'] = 1;
$insertion_baddress_data[$i]['created_by'] = $session_uid;
$insertion_baddress_data[$i]['email'] = isset($bill->email) ? $bill->email : '';
$insertion_baddress_data[$i]['mobile_no'] = isset($bill->phone) ? $bill->phone : '';
$i++;
echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Billing address has a value and Inserted ".$i." <br/>";
}else{
echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Billing address has no value; <br/>";
}
}
(!empty($insertion_baddress_data) ? $CustomerModel->insertAddressBatch($insertion_baddress_data) : "");
}
if (count($shipping) > 0) {
foreach ($shipping as $ship) {
if ($ship->first_name !== '') {
$insertion_saddress_data[$j]['first_name'] = $ship->first_name;
$insertion_saddress_data[$j]['last_name'] = $ship->last_name;
$insertion_saddress_data[$j]['company'] = $ship->company;
$insertion_saddress_data[$j]['address_1'] = $ship->address_1;
$insertion_saddress_data[$j]['address_2'] = $ship->address_2;
$insertion_saddress_data[$j]['city'] = $ship->city;
$insertion_saddress_data[$j]['state'] = $ship->state;
$insertion_saddress_data[$j]['country'] = $ship->country;
$insertion_saddress_data[$j]['postal_code'] = $ship->postcode;
$insertion_saddress_data[$j]['email'] = isset($ship->email)?$ship->email:"";
$insertion_saddress_data[$j]['mobile_no'] = isset($ship->phone)?$ship->phone:"";
$insertion_saddress_data[$j]['customer_id'] = $lastInsertId;
$insertion_saddress_data[$j]['address_type'] = 2;
$insertion_saddress_data[$j]['created_by'] = $session_uid;
$j++;
echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Shipping address has a value and Inserted ".$j." <br/>";
}
else{
echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Shipping address has no value <br/>";
}
}
(!empty($insertion_saddress_data) ? $CustomerModel->insertAddressBatch($insertion_saddress_data) : "");
}
} //reponse foreach closed
} //reponse count if closed
if (!empty($response['error'])) {
echo $response['error'];
echo $response['error_msg'];
$message .= $response['error'] . $response['error_msg'];
echo "Error :".$response['error'] . $response['error_msg'];
}else{
echo "Done";
}
$go_to_list_page = base_url()."customer_list";
echo "<center><a href=".$go_to_list_page.">go to list page</a></center>";
// return $message;
}
}

153
app/Controllers/Notifications.php Executable file
View File

@ -0,0 +1,153 @@
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ApiIntegrationModel;
class Notifications extends BaseController
{
// Define global variables as class properties
// protected $instance_id = '';
// protected $instance_id = "650C050D9D849";
// protected $access_token = "650be030cedb3";
protected $instance_id = "";
protected $access_token = "";
## Whatsapp Section :
// public function get_whatsapp_instance() {
// helper('apiIntegration');
// $instance_id = "";
// try {
// $response = get_whatsapp_instance($this->access_token);
// $this->logger->info("Whatsapp : get instance response type = ".gettype($response));
// if(isset($response) && !empty($response)){
// $this->logger->info("Whatsapp : get instance message = ".$response->message);
// if($response->status == "success"){
// $instance_id = $response->instance_id;
// $this->logger->info("Whatsapp : instance id = ".$response->instance_id);
// }
// else{
// $this->logger->error("Whatsapp : get instance Err = ".$response->error." Err Message = ".$response->error_msg);
// throw new \Exception("Err = ".$response->error." Err Message = ".$response->error_msg);
// }
// }
// } catch (\Exception $e) {
// $this->logger->error("Whatsapp : get instance exception", ['exception' => $e]);
// }
// return $instance_id;
// }
// public function get_whatsapp_instance($url){
// $response = get_whatsapp_instance($url);
// }
public function send_whatsapp_message() {
helper('apiIntegration');
$params = (object) Null;
try {
$this->logger->info("Whatsapp : sending message instance id = ".$this->instance_id);
$params->number = 916369084112;
$params->type = "text";
$params->message = "TestingFromVBPYUIO";
$params->instance_id = WAAI_TOKEN;
$params->access_token = WAAI_INSTANCE;
$this->logger->info("Whatsapp : sending message request type b4 = ".gettype($params));
//$url = "https://waai.in/api/send?number=916369084112&type=text&message=helper&instance_id=650C383B67BC7&access_token=650be030cedb3";
$url = "https://waai.in/api/send";
$message = perform_whatsapp_request($url,"POST",$params);
// https://waai.in/api/send?number=91639084112&type=text&message=helper&instance_id=650C383B67BC7&access_token=650be030cedb3/r/n{"status":"success","message":{"key":{"remoteJid":"91639084112@c.us","fromMe":true,"id":"BAE540383CE30F06"},"message":{"extendedTextMessage":{"text":"helper"}},"messageTimestamp":"1695362314"}}
// {"status":"success","message":{"key":{"remoteJid":"916369084112@c.us","fromMe":true,"id":"BAE500BBE10A0AC0"},"message":{"extendedTextMessage":{"text":"TestingFromVBP"}},"messageTimestamp":"1695362020"}}
// {"status":"error","message":"Access token is required"}
} catch (\Exception $e) {
$this->logger->error("An error occurred: " . $e->getMessage());
$message = "An error occurred: " . $e->getMessage();
}
return $message;
}
## Email Section :
public function mail_custom_notifications()
{ $successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
$data['page_name'] = 'Custom Notifications';
$request = \Config\Services::request();
if($request->is('post')){
$records = $request->getVar();
$cc = isset($records['carboncopy']) ? $records['carboncopy'] : '';
$bcc = isset($records['blindcarboncopy']) ? $records['blindcarboncopy'] : '';
try {
$email = \Config\Services::email();
$email->setTo($records['recipient']);
$email->setFrom('no-reply@tripapprovaltool.com', isset($records['company'])?$records['company']:"VBP");
$email->setSubject($records['subject']);
$email->setMessage($records['description']);
if (!empty($cc)) {
$ccRecipients = explode(',', $cc);
foreach ($ccRecipients as $ccRecipient) {
$email->setCC(trim($ccRecipient));
}
}
if (!empty($bcc)) {
$bccRecipients = explode(',', $bcc);
foreach ($bccRecipients as $bccRecipient) {
$email->setBCC(trim($bccRecipient));
}
}
if ($email->send()) {
$this->logger->info('Email sent successfully');
$successMessage = 'Email sent successfully';
$data['successMessage'] = $successMessage;
} else {
throw new \Exception('Email not sent. Please try again.');
}
} catch (\Exception $e) {
$this->logger->error('Error sending email: ' . $e->getMessage());
$validationErrors = 'Error sending email: ' . $e->getMessage();
$data['validationErrors'] = $validationErrors;
}
}
$this->render_page('notifications_form', $data);
}
public function whatsapp_custom_notifications(){
$successMessage = session()->getFlashdata('success');
$validationErrors = session()->getFlashdata('error');
$data['page_name'] = 'Custom Notifications';
helper('apiIntegration');
$request = \Config\Services::request();
if($request->is('post')){
$records = $request->getVar();
$params = (object) Null;
$this->access_token = "650be030cedb3";
$this->instance_id = "650C383B67BC7";
$this->logger->info("Whatsapp : sending message instance id = ".$this->instance_id);
try {
$this->logger->info("Whatsapp : sending message instance id = ".$this->instance_id);
$params->number = (int)'91'.$records['mobile'];
$params->type = $records['type'] == "" ? "text" : $records['type'];
$params->instance_id = WAAI_INSTANCE;
$params->access_token = WAAI_TOKEN;
$params->message = $records['description'];
if($records['type'] == 'media'){ $params->media_url = $records['media_url'];}
$this->logger->info("Whatsapp : sending message request type b4 = ".gettype($params));
$successMessage = perform_whatsapp_request(SEND_WAAI_URL,"POST",$params);
$this->logger->info("Whatsapp : Reponse = ".$successMessage);
$data['successMessage'] = $successMessage;
} catch (\Exception $e) {
$this->logger->error("An error occurred: " . $e->getMessage());
$validationErrors = "An error occurred: " . $e->getMessage();
$data['validationErrors'] = $validationErrors;
}
}
$this->render_page('notifications_form', $data);
}
}

View File

@ -12,17 +12,21 @@ class Users extends BaseController
public function index()
{
helper('session');
$session_role = get_user_role();
$session_bid = get_business_id();
if (!empty($session_role) && $session_role !== "sadmin") {
$this->logger->info("Users: Listing In admin role .");
$where = ['users.business_id' => (int)$session_bid, 'users.isactive' => 1];
} else {
$this->logger->info("Users: Listing In Super-admin role .");
$where = ['users.isactive !=' => NULL];
}
$model = new UsersModel();
$model->setTable('users');
$user_details = $model->where($where)->orderBy('user_id', 'DESC')->findAll();
$this->logger->info("Users: Listing Count .".count($user_details));
$data['page_name'] = 'User Details';
$data['details'] = $user_details;
$this->render_page('user_list', $data);
@ -35,9 +39,11 @@ class Users extends BaseController
$session_role = get_user_role();
$session_bid = get_business_id();
if ($id === '0') {
$this->logger->info("Users: In Add page");
$data['page_name'] = 'Add User';
$data['details'] = [];
} else if ($id !== '0') {
$this->logger->info("Users: In Edit page");
$data['page_name'] = 'Edit User';
$model = new UsersModel();
$model->setTable('users');
@ -67,56 +73,81 @@ class Users extends BaseController
## For inserting/updating details of user
public function insert_users()
{
helper('session');
$session_uid = get_logged_user_id();
$session_bid = get_business_id();
// print_r($_FILES);die();
$this->logger->info("Users: Inserting/Updating Details");
try {
## CI validation rule for profile_picture
$validationRule = [
'userfile' => [
'profile_picture' => [
'label' => 'Image File',
'rules' => [
'uploaded[profile_picture]',
'is_image[profile_picture]',
'mime_in[profile_picture,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
],
],
'rules' => 'uploaded[profile_picture]|is_image[profile_picture]|mime_in[profile_picture,image/jpg,image/jpeg,image/gif,image/png,image/webp]'
]
];
if (!$this->validate($validationRule) && $this->request->getPost('profile_picture') === '') {
$data = ['errors' => $this->validator->getErrors()];
print_r($data);
return 'hello';
}
$img = $this->request->getFile('profile_picture');
$user_id = $this->request->getPost('user_id');
$business_id = $this->request->getPost('business_id');
$filePath = 'public/uploads/' . $this->request->getPost('profile_picture');
## File Already Existing or not
if ($img->isValid() && !$img->hasMoved()) {
$fileName = $img->getName();
$img->move('public/uploads/', $fileName);
// Delete the previous image file if it exists
if ($user_id) {
$previousFileName = $this->request->getPost('previous_ufile');
if ($previousFileName && is_file('public/uploads/' . $previousFileName)) {
link('public/uploads/' . $previousFileName);
}
}
} else {
$fileName = $this->request->getPost('previous_ufile', ''); // Use the previous filename if no new image is provided
}
## Declarions
helper('session');
$UsersModel = new UsersModel();
$data = [
$session_uid = get_logged_user_id();
$session_bid = get_business_id();
$user_id = $this->request->getPost('user_id');
$business_id = $this->request->getPost('business_id')?$this->request->getPost('business_id'):$session_bid;
$img_details = $this->request->getFile('profile_picture'); // Here I Have Image details ;
$final_img_name = NULL;//Just flag
$existing_img_name = $this->request->getPost('existing_profile_picture_name'); // HiddenField for if have any pic name means;
$img_path = 'public/uploads/';
##Step 1 : image details available
if($img_details){
$this->logger->info("Users: image details avaiable");
##Step 2 : i have image details .<br/>
if ($img_details->isValid()) {
##Step 3 : image Name.$new_img_name."<br/>";
$new_img_name = $img_details->getName(); // before movement name
$this->logger->info("Users: Image Name B4 Upload".$new_img_name);
##Step 4 : Validation Rule Apply here.if not throw the error"<br/>";
if (!$this->validate($validationRule)) {
if($new_img_name !== ''){
$error = $this->validator->getErrors();
// echo "Error : ".(string)$error."<br/>";
$this->logger->error("Users: Err on image upload".$error['profile_picture']);
throw new \Exception((string)$error['profile_picture']);
}
}
##Step 5 : Check Existing and New Image Name Same Or not same no use to move on target folder
if($new_img_name !== $existing_img_name){
$this->logger->info("Users: Image Name are Differ".$new_img_name." & ".$existing_img_name);
## Step 6 : Different Image Name means removed on target folder using Unlink;
if ($existing_img_name && is_file($img_path.$existing_img_name)) {
$this->logger->info("Users: already Image Available on target Folder Path : ".$img_path.$existing_img_name." So, Deleted.");
// echo "Deleted_file : ".(string)$img_path.$existing_img_name."<br/>";
unlink($img_path.$existing_img_name);
}
## Step 7 : Moved to target;
$img_details->move($img_path, $new_img_name);
$final_img_name = $img_details->getName(); // after movement name
$this->logger->info("Users: Image Name After Upload".$final_img_name);
}else{
$final_img_name = $existing_img_name;
$this->logger->info("Users: Image Name are same".$new_img_name." & ".$existing_img_name." Can't Upload");
}
}
else{
## Step 8 : Not a Vaild Image File so replace Existing file name;
$final_img_name = $existing_img_name;
$this->logger->info("Users: Not a Vaild Image File Nothing To Update/Upload");
// throw new \Exception("Not a Vaild Image File");
}
}
else{
## Step 9 : Testing Purpose File Details Not Available. so i can't move it.;
$this->logger->info("Users: Testing Purpose Image Details Not Available. so i can't move it.");
$final_img_name = $existing_img_name;
//throw new \Exception("Testing Purpose File Details Not Available so i can't move it if you have existing filee means save it or your choice");
}
$data = [
'user_name' => $this->request->getPost('user_name'),
'profile_picture' => $fileName,
'profile_picture' => $final_img_name,
'city' => $this->request->getPost('city'),
'state' => $this->request->getPost('state'),
'email' => $this->request->getPost('email'),
@ -131,7 +162,6 @@ class Users extends BaseController
'gender' => $this->request->getPost('gender'),
'business_id' => $business_id
];
$user_id = $this->request->getPost('user_id'); // Get the business ID for update
if (empty($user_id)) {
// It's an insert operation
@ -141,34 +171,80 @@ class Users extends BaseController
$data['password'] = $hash_password;
$data['created_by'] = $session_uid;
//print_r($data);die;
$UsersModel->insert($data);
// ($UsersModel->insert($data)) ? session()->setFlashdata('success', 'User has been added successfully.')
// : session()->setFlashdata('error', 'User could not be added. Please try again.');
if ($UsersModel->insert($data)) {
session()->setFlashdata('success', 'User has been added successfully.');
$this->logger->info("Users: has been added successfully. Inserted ID = ".$UsersModel->insertID());
} else {
session()->setFlashdata('error', 'User could not be added. Please try again.');
$this->logger->error("Users: Err could not be added. Please try again.");
}
} else {
// It's an update operation
$isactive = $this->request->getPost('isactive');
$data['isactive'] = ($isactive == 'on') ? 1 : 0;
if($session_uid == $user_id && $data['isactive'] == 0){
throw new \Exception("Cant able to Update Because logged-In persons can't remove. Please Contact your Admin!....");
}
$data['updated_by'] = $session_uid;
$UsersModel->update($user_id, $data);
// $UsersModel->update($user_id, $data);
if ($UsersModel->update($user_id, $data)) {
session()->setFlashdata('success', 'User has been updated successfully.');
$this->logger->info("Users: has been updated successfully. Updated ID = ".$user_id);
} else {
session()->setFlashdata('error', 'User update failed. Please try again.');
$this->logger->error("Users: Err Failed to update ID =".$user_id);
}
}
}catch(\Exception $e) {
$this->logger->error("Users: Err Occur =".$e->getMessage());
session()->setFlashdata('error', 'Message: ' .$e->getMessage());
}
return redirect()->route('user_list');
}
## For delete the user details (Which means inactive the details)
public function delete_user($id)
{
helper('session');
$session_uid = get_logged_user_id();
try {
if($id == $session_uid){
throw new \Exception("Your Logged-In, Can't able delete");
}
$model = new UsersModel();
$where = ['users.user_id' => $id, 'users.isactive =' => 1];
$existingUser = $model->where($where)->find($id);
$this->logger->Info("Users: Going to Inactive ID = ".$id);
$model = new UsersModel();
$existingBook = $model->find($id);
if (!$existingBook) {
return redirect()->route('user_list');
if ($existingUser) {
$data['isactive'] = 0;
$data['updated_by'] = $session_uid;
if(!empty($existingUser['profile_picture']) && file_exists(FCPATH."public/uploads/".$existingUser['profile_picture'])){
unlink('public/uploads/'.$existingUser['profile_picture']);
$data['profile_picture'] = NULL;
}
if ($model->update($id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Users: has been Inactived successfully. Inactived ID = ".$id);
} else {
$this->logger->error("Users: Not able to Inactive ID =".$id);
throw new \Exception("Data Not able to Deleted");
}
}
else{
$this->logger->error("Users: Does Not Exist To Inactive, ID = ".$id);
throw new \Exception("User Already Deleted");
}
}catch(\Exception $e) {
$this->logger->error("Users: Err Occur = ".$e->getMessage());
session()->setFlashdata('error', 'Message: ' .$e->getMessage());
}
$data['isactive'] = 0;
$data['updated_by'] = $session_uid;
$model->update($id, $data);
return redirect()->route('user_list');
}
}

View File

@ -1,5 +1,56 @@
<?php
function perform_http_request($method, $url, $data = false) {
function perform_whatsapp_request($url,$method,$data){
// log_message('INFO',"PerformWhatsappRequest : request url = ".$url);
// log_message('INFO',"PerformWhatsappRequest : request data type = ".$data);
// log_message('INFO',"PerformWhatsappRequest : method = ".$method);
try{
$curl = curl_init();
$headers = array('Content-Type:application/json');
curl_setopt( $curl,CURLOPT_URL, $url);
switch ($method) {
case "POST":
curl_setopt( $curl,CURLOPT_POST, true );
if ($data) {
curl_setopt( $curl,CURLOPT_POSTFIELDS, json_encode($data));
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data) {
// print_r($data);die();
$url = sprintf("%s?%s", $url, http_build_query((array)$data));
}
}
curl_setopt( $curl,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl,CURLOPT_SSL_VERIFYPEER, true );
$curl_exec = curl_exec($curl);
// log_message('INFO',"PerformWhatsappRequest : reponse = ".$curl_exec);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_status === 200) {
$result = json_decode($curl_exec);
if ($result->status === "error") {
// log_message('ERROR',"PerformWhatsappRequest : error = ".$result->message);
throw new Exception($result->message);
}else{
$final_result = "Success";
}
}else{
$curl_errno= curl_errno($curl);
// log_message('ERROR',"PerformWhatsappRequest : curl error = ".$curl_errno);
throw new Error("Errno returned ".$curl_errno);
}
curl_close($curl);
}catch (Exception $e) {
$final_result = "Exception Errno returned".$e->getMessage()." <br/>";
}
return $final_result;
}
function perform_http_request_old($method, $url, $data = false) {
$username = "ck_935889d13267b63c2341168e42ffafe3c1ee831a";
$password = "cs_6ce1321c3f08049dfb3c8098ea21137796446bc4";
$encodekey = base64_encode($username.':'.$password);

View File

@ -10,8 +10,9 @@ class AuthenticationModel extends Model
public function getheringDetailsForHeader($user_id)
{
$builder = $this->db->table('users');
$builder->select('user_id,user_name,email,first_name,last_name,password,mobile_no,date_of_birth,address,gender,profile_picture,city,state,postal_code,users.country,role,setting_id,site_name,site_title,favicon,logo,terms_service,footer_about,admin_email,mobile,copyright,pagination_limit,site_info,about_info,mail_protocol,mail_title,mail_host,mail_port,mail_encryption,mail_username,mail_password,currency,settings.country');
$builder->join('settings', 'settings.admin_email = users.email', 'left');
$builder->select('user_id,user_name,users.email,users.first_name,users.last_name,users.password,users.mobile_no,date_of_birth,users.address,gender,profile_picture,users.city,users.state,users.postal_code,users.country,role,setting_id,site_name,site_title,favicon,logo,terms_service,footer_about,admin_email,mobile,copyright,pagination_limit,site_info,about_info,mail_protocol,mail_title,mail_host,mail_port,mail_encryption,mail_username,mail_password,currency,settings.country,settings.logo as company_logo_large,business.business_logo as company_logo_small');
$builder->join('settings', 'settings.business_id = users.business_id', 'left');
$builder->join('business', 'business.business_id = users.business_id', 'left');
$builder->where('user_id', $user_id);
//$template_mapping_details['fk_entity_id'];
$query = $builder->get();

View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class NotificationModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $allowedFields = ['user_id','user_name','email','first_name','last_name','password','mobile_no','date_of_birth','address','gender','profile_picture','city','state','postal_code','country','role','isactive','business_id'];
public function saveData($data, $id = null)
{
if ($id === null) {
// Insert new record
return $this->insert($data);
} else {
// Update existing record
return $this->update($id, $data);
}
}
}

View File

@ -9,7 +9,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public/assets/images/company/default.ico" ?>">
<link rel="shortcut icon" href="<?= base_url() . "public/uploads/default.ico" ?>">
<!-- App css -->
<link href="<?= base_url() . "public/assets/css/bootstrap.min.css" ?>" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
@ -37,16 +37,14 @@
<div class="auth-logo">
<a href="javascript:void(0);" class="logo logo-dark text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
<a href="javascript:void(0);" class="logo logo-light text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
</div>
</div>
@ -103,12 +101,12 @@
</svg>
<h3>Success !</h3>
<!-- <p class="text-muted mt-2"> A email has been send to <span class="font-weight-medium"><?= $email; ?></span>.
<p class="text-muted mt-2"> A email has been send to <span class="font-weight-medium"><?= $mail_id; ?></span>.
Please check for an email from company and click on the included link to
reset your password. </p>
<a href="<?= base_url(); ?>" class="btn btn-block btn-primary waves-effect waves-light mt-3">Back to Home</a> -->
<a href="<?= $link; ?>" class="btn btn-block btn-primary waves-effect waves-light mt-3" target="_blank">Alternative So Click here</a>
<a href="<?= base_url(); ?>" class="btn btn-block btn-primary waves-effect waves-light mt-3">Back to Home</a>
<!-- <a href="<?= $link; ?>" class="btn btn-block btn-primary waves-effect waves-light mt-3" target="_blank">Alternative So Click here</a> -->
</div>
</div> <!-- end card-body -->
</div>

View File

@ -8,7 +8,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public/assets/images/company/default.ico" ?>">
<link rel="shortcut icon" href="<?= $favicon; ?>">
<!-- App css -->
<link href="<?= base_url() . "public/assets/css/bootstrap.min.css" ?>" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
<link href="<?= base_url() . "public/assets/css/app.min.css" ?>" rel="stylesheet" type="text/css" id="app-default-stylesheet" />
@ -35,22 +35,20 @@
<div class="auth-logo">
<a href="javascript:void(0);" class="logo logo-dark text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
<a href="javascript:void(0);" class="logo logo-light text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
</div>
</div>
<div class="text-center w-75 m-auto">
<img src="<?= base_url()."public/assets/images/users/".$profile_picture; ?>" alt="user-image" class="rounded-circle avatar-lg img-thumbnail">
<img src="<?= $profile_picture; ?>" alt="user-image" class="rounded-circle avatar-lg img-thumbnail">
<h4 class="text-dark-50 text-center mt-3"><?= 'Hi ! '.$loggedin_person; ?></h4>
<p class="text-muted mb-4">Enter your password to access the <?= $loggedin_person_role; ?></p>
</div>

View File

@ -9,7 +9,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public/assets/images/company/default.ico" ?>">
<link rel="shortcut icon" href="<?= base_url() . "public/uploads/default.ico" ?>">
<!-- App css -->
<link href="<?= base_url() . "public/assets/css/bootstrap.min.css" ?>" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
@ -36,16 +36,14 @@
<div class="auth-logo">
<a href="javascript: void(0);" class="logo logo-dark text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="80">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="80">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
<a href="javascript: void(0);" class="logo logo-light text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="80">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="80">
</span>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
</div>
<p class="text-muted mb-4 mt-3">Enter your email address and password to access admin panel.</p>

View File

@ -8,7 +8,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public/assets/images/company/default.ico" ?>">
<link rel="shortcut icon" href="<?= base_url() . "public/uploads/default.ico" ?>">
<!-- App css -->
<link href="<?= base_url() . "public/assets/css/bootstrap.min.css"?>" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
@ -36,16 +36,14 @@
<div class="auth-logo">
<a href="javascript:void(0);" class="logo logo-dark text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span><br/>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
<a href="javascript:void(0);" class="logo logo-light text-center">
<span class="logo-lg">
<img src="<?= base_url() . "public/assets/images/company/default.png" ?>" alt="" height="55">
<img src="<?= base_url() . "public/uploads/default.png" ?>" alt="" height="55">
</span><br/>
<p class="text-muted"><span>BigBambooBookPublish</p>
</a>
</div>
</div>

View File

@ -9,7 +9,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public/assets/images/company/default.ico" ?>">
<link rel="shortcut icon" href="<?= base_url() . "public/uploads/default.ico" ?>">
<!-- App css -->
<link href="<?= base_url() . "public/assets/css/bootstrap-creative.min.css" ?>" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
<link href="<?= base_url() . "public/assets/css/app-creative.min.css" ?>" rel="stylesheet" type="text/css" id="app-default-stylesheet" />

View File

@ -95,7 +95,7 @@
</div>
<input type="hidden" id="business_id" name="business_id" placeholder="hidden for business id" value="<?= isset($businesses['business_id']) ? $businesses['business_id'] : '' ?>" />
<?php if (!empty($businesses)) { ?>
<?php if (!empty($businesses) && ($loggedin_person_role === 'sadmin')) { ?>
<div class="form-group text-right m-b-0 checkbox checkbox-purple">
<input type="checkbox" id="bcheckbox" name="bcheckbox" class="form-control" <?= isset($businesses) && $businesses['isactive'] == 1 ? 'checked' : '' ?>>
<label for="bcheckbox"> Is Active</label>

View File

@ -3,7 +3,9 @@
<div class="card">
<div class="card-body">
<div class="float-right">
<a href="new_bussiness/0" class="btn btn-primary"><i class="ri-briefcase-4-fill"></i> Add New </a>
<?php if($loggedin_person_role === 'sadmin'): ?>
<a href="<?= base_url()."new_bussiness/0"; ?>" class="btn btn-primary"><i class="ri-briefcase-4-fill"></i> Add Bussiness </a>
<?php endif; ?>
</div><!-- end col-->
<br>
<h4 class="header-title mb-3"><?= $page_name; ?></h4>
@ -37,8 +39,10 @@
<td><?= $business['postal_code']; ?></td>
<td><?= $business['business_logo']; ?></td>
<td>
<a href="<?= "new_bussiness/" . $business['business_id']; ?>" class="edit-button"><i class="ri-pencil-line"></i></a>
<a href="<?= "delete_business/" . $business['business_id']; ?>" class="delete-button"><i class="ri-delete-bin-line"></i></a>
<a href="<?= "new_bussiness/" . $business['business_id']; ?>" class="edit-button" title="Click to Edit Business"><i class="ri-pencil-line"></i></a>
<?php if($loggedin_person_role === 'sadmin'): ?>
<a href="<?= "delete_business/" . $business['business_id']; ?>" class="delete-button" title="Click to Delete Business"><i class="ri-delete-bin-line"></i></a>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>

View File

@ -0,0 +1,198 @@
<style>
/* Show the form section by default */
#mailFormDiv { display: none; }
#whatsappFormDiv { display: none; }
</style>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<a class="dropdown-icon-item" id="showMailLink">
<img src="<?= base_url() . "public/assets/images/brands/gmail.png" ?>" alt="mail">
<span>Mail Custom Notification</span>
</a>
</div>
<div class="col">
<a class="dropdown-icon-item" id="showWhatsappLink">
<img src="<?= base_url() . "public/assets/images/brands/whatsapp.png" ?>" alt="whatsapp">
<span>Whatsapp Custom Notification</span>
</a>
</div>
<!-- <div class="col">
<a class="dropdown-icon-item" href="<?= base_url()."send_whatsapp_message"; ?>">
<img src="<?= base_url() . "public/assets/images/brands/whatsapp.png" ?>" alt="whatsapp">
<span>Whatsapp Static Notification</span>
</a>
</div> -->
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="header-title"><?= $page_name; ?></h4>
</br>
<div id="textDiv">
<span class="widget-simple text-center">
<div class="media-body align-self-center font-24 avatar-title">
<?php if (isset($validationErrors)) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= $validationErrors ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php } elseif (isset($successMessage)) { ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= $successMessage ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php } ?>
<p style="color: #0a0a0a!important;" class="mt-0" style><?= "Please Choose Your Choice....."; ?></p>
</div>
</span>
</div>
<div id="mailFormDiv">
<form role="form" class="parsley-examples" method="POST" enctype="multipart/form-data" action="<?= base_url() . "mail_custom_notifications"; ?>">
<div class="form-group row">
<label for="recipient" class="col-4 col-form-label">Recipient Email</label>
<div class="col-7">
<input type="email" placeholder="Recipient Email" class="form-control" id="recipient" name="recipient" parsley-type="email">
</div>
</div>
<div class="form-group row">
<label for="CC" class="col-4 col-form-label">CC</label>
<div class="col-7">
<input type="text" placeholder="Enter multiple email addresses separated by commas" class="form-control" id="CC" name="carboncopy">
</div>
</div>
<div class="form-group row">
<label for="BCC" class="col-4 col-form-label">BCC</label>
<div class="col-7">
<input type="text" placeholder="Enter multiple email addresses separated by commas" class="form-control" id="BCC" name="blindcarboncopy">
</div>
</div>
<div class="form-group row">
<label for="subject" class="col-4 col-form-label">subject</label>
<div class="col-7">
<input type="text" placeholder="Subject" class="form-control" id="subject" name="subject">
</div>
</div>
<div class="form-group row">
<label for="body" class="col-4 col-form-label">Body</label>
<div class="col-7">
<textarea id="summernote-basic" name="description" class="form-control" rows="7">
<h5>Hello {User}, </h5>
<p>We create simple, flat & responsive custom mail template.</p>
<p>Please, write text here!</p>
</textarea>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1">
Send
</button>
</div>
</form>
</div>
<div id="whatsappFormDiv">
<form role="form" class="parsley-examples" method="POST" enctype="multipart/form-data" action="<?= base_url() . "whatsapp_custom_notifications"; ?>">
<div class="form-group row">
<label for="mobile" class="col-4 col-form-label">Mobile Number</label>
<div class="col-7">
<input type="number" placeholder="Mobile Number" class="form-control" id="mobile" name="mobile">
</div>
</div>
<div class="form-group row">
<label for="type" class="col-4 col-form-label">Message Type</label>
<div class="col-7">
<select class="form-control" id="type" name="type">
<option value=null>Choose your Message Type</option>
<option value="text">Text</option>
<option value="media">Media</option>
</select>
</div>
</div>
<div id="fields-for-mediaurl" style="display: none;">
<div class="form-group row">
<label for="media_url" class="col-4 col-form-label">Media Url</label>
<div class="col-7">
<input type="text" placeholder="Media URL" class="form-control" id="media_url" name="media_url">
</div>
</div>
</div>
<div class="form-group row">
<label for="message" class="col-4 col-form-label">Message</label>
<div class="col-7">
<textarea id="message" name="description" class="form-control" rows="5">Hello {User},Please,write text here!</textarea>
</div>
</div>
<div class="form-group text-right m-b-0">
<button type="submit" class="btn btn-primary waves-effect waves-light mr-1">
Send
</button>
</div>
</form>
</div>
</div> <!-- end card-body-->
</div> <!-- end card-->
</div><!-- end col -->
</div><!-- end row -->
<script>
const textDiv = document.getElementById('textDiv');
const showMailLink = document.getElementById('showMailLink');
const mailFormDiv = document.getElementById('mailFormDiv');
const showWhatsappLink = document.getElementById('showWhatsappLink');
const whatsappFormDiv = document.getElementById('whatsappFormDiv');
// Add a click event listener to the link
showMailLink.addEventListener('click', function() {
// Toggle the display of the div
// mailFormDiv.style.display = (mailFormDiv.style.display === 'none') ? 'block' : 'none';
mailFormDiv.style.display = 'block';
whatsappFormDiv.style.display = 'none';
textDiv.style.display = 'none';
const elements = document.getElementsByClassName("header-title");
for (let i = 0; i < elements.length; i++) {
elements[i].textContent = "Mail Custom Notification";
}
});
// Add a click event listener to the link
showWhatsappLink.addEventListener('click', function() {
// Toggle the display of the div
mailFormDiv.style.display = 'none';
textDiv.style.display = 'none';
// whatsappFormDiv.style.display = (whatsappFormDiv.style.display === 'none') ? 'block' : 'none';
whatsappFormDiv.style.display = 'block';
const elements = document.getElementsByClassName("header-title");
for (let i = 0; i < elements.length; i++) {
elements[i].textContent = "Whatsapp Custom Notification";
}
});
// Get references to the dropdown and field divs
const dropdown = document.getElementById("type");
const fieldsForMediaURL = document.getElementById("fields-for-mediaurl");
// Add a change event listener to the dropdown
dropdown.addEventListener("change", function() {
// Determine which option is selected and show the corresponding fields
const selectedOption = dropdown.value;
if (selectedOption === "media") {
fieldsForMediaURL.style.display = "block";
} else {
fieldsForMediaURL.style.display = "none";
document.getElementById("media_url").value = "";
}
});
</script>

View File

@ -9,8 +9,10 @@
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<p> <?= date('Y') ?> &copy; <?= $company_name; ?>.</p>
<!-- <p> <?= date('Y') ?> &copy; <?= $company_name; ?>. Page rendered in {elapsed_time} seconds</p> -->
<img src="<?= $favicon; ?>" alt="company fav icon for footer" width="25" height="25">
<script>document.write(new Date().getFullYear())</script> &copy; <?= $company_name; ?>
<!-- <p> <?= date('Y') ?> &copy; <?= $company_name; ?>.</p>
<p> <?= date('Y') ?> &copy; <?= $company_name; ?>. Page rendered in {elapsed_time} seconds</p> -->
</div>
<div class="col-md-6">
<div class="text-md-right footer-links d-none d-sm-block">
@ -464,8 +466,24 @@
<!-- Datatables init -->
<script src="<?= base_url()."public/assets/js/pages/datatables.init.js" ?>"></script>
<script src="<?= base_url()."public/assets/libs/parsleyjs/parsley.min.js" ?>"></script>
<script src="<?= base_url()."public/assets/js/pages/form-validation.init.js"?>"></script>
<!-- App js -->
<script src="<?= base_url()."public/assets/js/app.min.js" ?>"></script>
<!-- Summernote js -->
<script src="<?= base_url()."public/assets/libs/summernote/summernote-bs4.min.js" ?>"></script>
<!-- Init js -->
<script src="<?= base_url()."public/assets/js/pages/form-summernote.init.js" ?>"></script>
<script>
// Automatically close both success and error messages after 5 seconds (5000 milliseconds)
setTimeout(function () {
document.querySelectorAll('.alert').forEach(function (alert) {
alert.classList.add('d-none');
});
}, 5000); // Adjust the time (in milliseconds) as needed
</script>
</body>
</html>

View File

@ -8,7 +8,7 @@
<meta content="Coderthemes" name="author" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url()."public/assets/images/company/".$favicon ?>" >
<link rel="shortcut icon" href="<?= $favicon; ?>">
<!-- plugin css -->
<link href="<?= base_url()."public/assets/libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css" ?>" rel="stylesheet" type="text/css" />
@ -29,6 +29,7 @@
<!-- icons -->
<link href="<?= base_url()."public/assets/css/icons.min.css" ?>" rel="stylesheet" type="text/css" />
<link href="<?= base_url()."public/assets/libs/summernote/summernote-bs4.min.css" ?>" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
@ -44,25 +45,23 @@
<div class="logo-box">
<a href="dashboard" class="logo logo-dark text-center">
<span class="logo-sm">
<p style="color:#FFFFFF"><?= $company_short_name; ?></p>
<!--<img src="./assets/images/logo-sm-vbp-dark.png" alt="BB-VbP" height="24">-->
<img src="<?= $company_logo_small; ?>" alt="<?= $company_short_name; ?>" height="24">
<!-- <span class="logo-lg-text-light">Minton</span> -->
</span>
<span class="logo-lg">
<p style="color:#FFFFFF"><?= $company_name; ?></p>
<!--<img src="./assets/images/logo-vbp-dark.png" alt="BB-VijayabharathamPublishing" height="20">-->
<img src="<?= $company_logo_large; ?>" alt="<?= $company_name; ?>" height="50">
<!-- <img src="<?= base_url()."public/uploads/default.png" ?>" alt="<?= $company_name; ?>" height="20"> -->
<!-- <span class="logo-lg-text-light">M</span> -->
</span>
</a>
<a href="dashboard" class="logo logo-light text-center">
<span class="logo-sm">
<p style="color:#FFFFFF"><?= $company_short_name; ?></p>
<!--<img src="./assets/images/logo-vbp-sm.png" alt="BB-VbP" height="24">-->
<img src="<?= $company_logo_small; ?>" alt="<?= $company_short_name; ?>" height="24">
</span>
<span class="logo-lg">
<p style="color:#FFFFFF"><?= $company_name; ?></p>
<!--<img src="./assets/images/logo-vbp-light.png" alt="BB-VijayabharathamPublishing" height="20">-->
<!-- <img src="<?= base_url()."public/uploads/default.png" ?>" alt="<?= $company_name; ?>" height="24"> -->
<img src="<?= $company_logo_large; ?>" alt="<?= $company_name; ?>" height="50">
</span>
</a>
</div>
@ -71,8 +70,7 @@
<!-- User box -->
<div class="user-box text-center">
<img src="<?= base_url()."public/assets/images/users/".$profile_picture; ?>" alt="user-img" title="Mat Helme"
class="rounded-circle avatar-md">
<img src="<?= $profile_picture ?>" alt="user-img" title="Mat Helme" class="rounded-circle avatar-md">
<div class="dropdown">
<a href="javascript: void(0);" class="text-reset dropdown-toggle h5 mt-2 mb-1 d-block"
data-toggle="dropdown"><?= $loggedin_person; ?></a>
@ -186,6 +184,12 @@
<span>Address Print </span>
</a>
</li>
<li>
<a href="<?= base_url()."mail_custom_notifications"; ?>">
<i class="ri-notification-3-fill"></i>
<span> Custom Notifications </span>
</a>
</li>
</ul>

View File

@ -221,7 +221,7 @@
<li class="dropdown notification-list topbar-dropdown">
<a class="nav-link dropdown-toggle nav-user mr-0 waves-effect waves-light" data-toggle="dropdown" href="#" role="button" aria-haspopup="false" aria-expanded="false">
<img src="<?= base_url()."public/assets/images/users/".$profile_picture; ?>" alt="user-image" class="rounded-circle">
<img src="<?= $profile_picture; ?>" alt="user-image" class="rounded-circle">
<span class="pro-user-name ml-1"><?= $loggedin_person; ?><i class="mdi mdi-chevron-down"></i>
</span>
</a>
@ -270,30 +270,28 @@
<!-- LOGO -->
<div class="logo-box">
<a href="dashboard" class="logo logo-dark text-center">
<span class="logo-sm">
<p style="color:#FFFFFF"><?= $company_short_name; ?></p>
<!--<img src="./assets/images/logo-vbp-sm-dark.png" alt="BB-VBP" height="24">
<span class="logo-lg-text-light">Minton</span> -->
</span>
<span class="logo-lg">
<p style="color:#FFFFFF"><?= $company_name; ?></p>
<!-- <img src="./assets/images/logo-vbp-dark.png" alt="BB-VijayabharathamPublishing" height="20">
<span class="logo-lg-text-light">M</span> -->
</span>
</a>
<a href="dashboard" class="logo logo-dark text-center">
<span class="logo-sm">
<img src="<?= $company_logo_small; ?>" alt="<?= $company_short_name; ?>" height="24">
<!-- <span class="logo-lg-text-light">Minton</span> -->
</span>
<span class="logo-lg">
<img src="<?= $company_logo_large; ?>" alt="<?= $company_name; ?>" height="50">
<!-- <img src="<?= base_url()."public/uploads/default.png" ?>" alt="<?= $company_name; ?>" height="20"> -->
<!-- <span class="logo-lg-text-light">M</span> -->
</span>
</a>
<a href="dashboard" class="logo logo-light text-center">
<span class="logo-sm">
<p style="color:#FFFFFF"><?= $company_short_name; ?></p>
<!--<img src="./assets/images/logo-vbp-sm.png" alt="BB-VBP" height="24">-->
</span>
<span class="logo-lg">
<p style="color:#FFFFFF"><?= $company_name; ?></p>
<!--<img src="./assets/images/logo--vbp-light.png" alt="BB-VijayabharathamPublishing" height="20">-->
</span>
</a>
</div>
<a href="dashboard" class="logo logo-light text-center">
<span class="logo-sm">
<img src="<?= $company_logo_small; ?>" alt="<?= $company_short_name; ?>" height="24">
</span>
<span class="logo-lg">
<!-- <img src="<?= base_url()."public/uploads/default.png" ?>" alt="<?= $company_name; ?>" height="24"> -->
<img src="<?= $company_logo_large; ?>" alt="<?= $company_name; ?>" height="50">
</span>
</a>
</div>
<ul class="list-unstyled topnav-menu topnav-menu-left m-0">
<li>

View File

@ -6,37 +6,36 @@
<!-- <?php if (session()->getFlashdata('success')) : ?>
<div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
<?php endif; ?> -->
<form class="needs-validation" novalidate action="<?= base_url() . "insert_users"; ?>" method="post" enctype="multipart/form-data">
<form class="parsley-examples" action="<?= base_url() . "insert_users"; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-4">
<label for="user_name" class="col-form-label">User Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="user_name" name="user_name" value="<?= isset($details['user_name']) ? $details['user_name'] : '' ?>" placeholder="User Name" required />
<div class="invalid-feedback"> Please provide. </div>
<input type="text" class="form-control" id="user_name" name="user_name" value="<?= isset($details['user_name']) ? $details['user_name'] : '' ?>" placeholder="User Name" required autofocus />
</div>
<div class="form-group col-md-4">
<label for="email" class="col-form-label">Email<span class="text-danger">*</span></label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" value="<?= isset($details['email']) ? $details['email'] : '' ?>" required />
<div class="invalid-feedback"> Please provide. </div>
</div>
<?php if (empty($details)) { ?>
<div class="form-group col-md-4">
<label for="password" class="col-form-label">Password<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="password" name="password" placeholder="Password" value="<?= isset($details['password']) ? $details['password'] : '' ?>" required />
<div class="invalid-feedback"> Please provide. </div>
</div>
<?php } ?>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="first_name" class="col-form-label">First Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" value="<?= isset($details['first_name']) ? $details['first_name'] : '' ?>" required />
<div class="invalid-feedback"> Please provide. </div>
<input data-parsley-type="alphanum" type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" value="<?= isset($details['first_name']) ? $details['first_name'] : '' ?>" required />
</div>
<div class="form-group col-md-4">
<label for="last_name" class="col-form-label">Last Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" value="<?= isset($details['last_name']) ? $details['last_name'] : '' ?>" required />
<div class="invalid-feedback"> Please provide. </div>
<input data-parsley-type="alphanum" type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" value="<?= isset($details['last_name']) ? $details['last_name'] : '' ?>" required />
</div>
<div class="form-group col-md-4">
<label for="date_of_birth" class="col-form-label">Date Of Birth<span class="text-danger"></span></label>
@ -48,8 +47,8 @@
<div class="form-group col-md-4">
<label for="mobile_no" class="col-form-label">Mobile Number<span class="text-danger">*</span></label>
<input type="number" class="form-control" id="mobile_no" name="mobile_no" placeholder="Mobile Number (Enter only numbers)" required data-parsley-type="number" value="<?= isset($details['mobile_no']) ? $details['mobile_no'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
<input data-parsley-type="number" type="text" class="form-control" id="mobile_no" name="mobile_no" placeholder="Mobile Number (Enter only numbers)" required data-parsley-type="number" value="<?= isset($details['mobile_no']) ? $details['mobile_no'] : '' ?>" pattern="[0-9]{10}" maxlength="10" autofocus />
</div>
<div class="form-group col-md-4">
@ -58,71 +57,61 @@
</div>
<div class="form-group col-md-4">
<label for="role" class="col-form-label">Role<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="role" name="role" placeholder="Role" required value="<?= isset($details['role']) ? $details['role'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
<input type="text" class="form-control" id="role" name="role" placeholder="Role" required value="<?= isset($details['role']) ? $details['role'] : '' ?>" autofocus />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="address" class="col-form-label">Address<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="address" name="address" placeholder="Address (eg : 1234 Main St)" required value="<?= isset($details['address']) ? $details['address'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
</div>
<div class="form-group col-md-4">
<label for="address" class="col-form-label">Address<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="address" name="address" placeholder="Address (eg : 1234 Main St)" required value="<?= isset($details['address']) ? $details['address'] : '' ?>" />
</div>
<div class="form-group col-md-4">
<label for="city" class="col-form-label">City<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="city" name="city" placeholder="City" required value="<?= isset($details['city']) ? $details['city'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
</div>
<input type="text" class="form-control" id="city" name="city" placeholder="City" required value="<?= isset($details['city']) ? $details['city'] : '' ?>" />
</div>
<div class="form-group col-md-4">
<label for="state" class="col-form-label">State<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="state" name="state" placeholder="State" required value="<?= isset($details['state']) ? $details['state'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
</div>
<div class="form-group col-md-4">
<label for="postal_code" class="col-form-label">Postal Code<span class="text-danger">*</span></label>
<input type="text" class="form-control" id="postal_code" name="postal_code" placeholder="Postal Code (PIN)" required value="<?= isset($details['postal_code']) ? $details['postal_code'] : '' ?>" />
<div class="invalid-feedback"> Please provide. </div>
</div>
<?php if (!empty($details['profile_picture'])) { ?>
<div class="form-group col-md-4">
<label for="profile_picture" class="col-form-label">Current Business Logo</label>
<img src="<?= base_url('public/uploads/' . $details['profile_picture']) ?>" alt="Business Logo" class="preview-image" />
</div>
<?php } ?>
<div class="form-group col-md-4">
<label for="profile_picture" class="col-form-label">Profile Picture<span class="text-danger">*</span></label>
<!-- <input type="text" class="form-control" id="profile_picture" name="profile_picture" placeholder="Profile picture Name" readonly value="<?= isset($details['profile_picture']) ? $details['profile_picture'] : '' ?>" /> -->
<input type="file" name="profile_picture" placeholder="hidden Field for profile picture" readonly value="<?= isset($details['profile_picture']) ? $details['profile_picture'] : '' ?>" />
<input type="text" class="form-control" id="state" name="state" placeholder="State" required value="<?= isset($details['state']) ? $details['state'] : '' ?>" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="postal_code" class="col-form-label">Postal Code<span class="text-danger">*</span></label>
<input data-parsley-type="number" type="text" class="form-control" id="postal_code" name="postal_code" placeholder="Postal Code (PIN)" required value="<?= isset($details['postal_code']) ? $details['postal_code'] : '' ?>" pattern="[0-9]{6}" maxlength="6" />
</div>
<?php if (!empty($details['profile_picture'])) { ?>
<div class="form-group col-md-4 mt-3">
<div class="media">
<img src="<?= base_url('public/uploads/' . $details['profile_picture']) ?>" alt="Business Logo" height="50" class="preview-image d-flex align-self-start rounded mr-2">
<div class="media-body">
<h5 class="mt-0">Existing Profile Picture</h5>
<p class="mb-1"><?= $details['profile_picture']; ?></p>
<input type="hidden" id="existing_profile_picture_name" name="existing_profile_picture_name" placeholder="hidden Field for profile picture name" readonly value="<?= $details['profile_picture']; ?>" />
</div>
</div>
</div>
<?php } ?>
<div class="form-group col-md-4">
<label for="profile_picture" class="col-form-label">Profile Picture</label>
<input type="file" name="profile_picture" value="<?= isset($details['profile_picture']) ? $details['profile_picture'] : '' ?>" />
</div>
<?php if ($loggedin_person_role === 'sadmin') { ?>
<div class="form-row">
<div class="form-group col-md-6">
<label for="postal_code" class="col-form-label">Buiness<span class="text-danger">*</span></label>
<select id="business_id" name="business_id" class="form-control">
<option value=null>Choose your Buiness</option>
<?php if ($loggedin_person_role === 'sadmin') { ?>
<div class="form-group col-md-4">
<label for="business_id" class="col-form-label">Buiness<span class="text-danger">*</span></label>
<select id="business_id" name="business_id" class="form-control" required>
<option value="">Choose your Buiness</option>
<?php foreach ($business_details as $value) { ?>
<option value="<?php echo $value['business_id']; ?>" <?php if (isset($details['business_id']) && ($details['business_id'] === $value['business_id'])) echo "selected"; ?>>
<?php echo $value['title']; ?></option>
<?php } ?>
</select>
</div>
</div>
<?php } else { ?>
<input type="hidden" id="business_id" name="business_id" placeholder="hidden for business id" value="<?= isset($details['business_id']) ? $details['business_id'] : $session_bid ?>" />
<?php } ?>
</div>
<?php } ?>
</div>
<input type="hidden" id="user_id" name="user_id" placeholder="hidden for user id" value="<?= isset($details['user_id']) ? $details['user_id'] : '' ?>" />
<?php if (!empty($details)) { ?>
<div class="form-group text-right m-b-0 checkbox checkbox-purple">
@ -140,8 +129,7 @@
</button>
<a href="<?= base_url() . "user_list"; ?>" class="btn btn-secondary waves-effect">Cancel
</a>
<!-- <button id="cancelButton" type="button" class="btn btn-secondary waves-effect">Cancel</button> -->
</div>
</div>
</div>
</form>
</div> <!-- end card-body-->

View File

@ -3,13 +3,29 @@
<div class="card">
<div class="card-body">
<div class="float-right">
<a href="<?= base_url()."user_page/0"; ?>" class="btn btn-primary"><i class="ri-user-add-line"></i> Add New </a>
<a href="<?= base_url()."user_page/0"; ?>" class="btn btn-primary"><i class="ri-user-add-line"></i> Add User </a>
</div><!-- end col-->
<br>
<h4 class="header-title mb-3"><?= $page_name; ?></h4>
<?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
<?php if (session()->getFlashdata('success') || session()->getFlashdata('error')) : ?>
<?php if (session()->getFlashdata('success')) : ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= session('success') ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')) : ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= session('error') ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php endif; ?>
<?php endif; ?>
<div class="table-responsive">
<!-- <table id="datatable-buttons" class="table dt-responsive w-100"> -->
<table id="scroll-horizontal-datatable" class="table w-100 nowrap">
@ -51,8 +67,8 @@
<span class="<?php echo $class; ?>"><?php echo $message; ?></span>
</td>
<td>
<a href="<?= $edit_page_route; ?>" class="edit-button"><i class="ri-pencil-line"></i></a>
<a href="<?php echo "delete_user/".$row['user_id']; ?>" class="delete-button"><i class="ri-delete-bin-line"></i></a>
<a href="<?= $edit_page_route; ?>" class="edit-button" title="Click to Edit User" ><i class="ri-pencil-line"></i></a>
<a href="<?php echo "delete_user/".$row['user_id']; ?>" class="delete-button" title="Click to Delete User" ><i class="ri-delete-bin-line"></i></a>
</td>
</tr>
<?php endforeach; ?>

293
composer.lock generated
View File

@ -529,21 +529,21 @@
"packages-dev": [
{
"name": "codeigniter/coding-standard",
"version": "v1.7.8",
"version": "v1.7.9",
"source": {
"type": "git",
"url": "https://github.com/CodeIgniter/coding-standard.git",
"reference": "3f7e8447652ff1a0c794b8abffc0af0e8453d536"
"reference": "841ef22bac4ea9261c47efa035d300dece0e365d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/CodeIgniter/coding-standard/zipball/3f7e8447652ff1a0c794b8abffc0af0e8453d536",
"reference": "3f7e8447652ff1a0c794b8abffc0af0e8453d536",
"url": "https://api.github.com/repos/CodeIgniter/coding-standard/zipball/841ef22bac4ea9261c47efa035d300dece0e365d",
"reference": "841ef22bac4ea9261c47efa035d300dece0e365d",
"shasum": ""
},
"require": {
"ext-tokenizer": "*",
"friendsofphp/php-cs-fixer": "^3.24",
"friendsofphp/php-cs-fixer": "^3.27",
"nexusphp/cs-config": "^3.6",
"php": "^7.4 || ^8.0"
},
@ -579,7 +579,7 @@
"slack": "https://codeigniterchat.slack.com",
"source": "https://github.com/CodeIgniter/coding-standard"
},
"time": "2023-08-30T03:39:39+00:00"
"time": "2023-09-18T10:13:29+00:00"
},
{
"name": "composer/pcre",
@ -801,30 +801,30 @@
},
{
"name": "doctrine/instantiator",
"version": "1.5.0",
"version": "2.0.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/instantiator.git",
"reference": "0a0fa9780f5d4e507415a065172d26a98d02047b"
"reference": "c6222283fa3f4ac679f8b9ced9a4e23f163e80d0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/instantiator/zipball/0a0fa9780f5d4e507415a065172d26a98d02047b",
"reference": "0a0fa9780f5d4e507415a065172d26a98d02047b",
"url": "https://api.github.com/repos/doctrine/instantiator/zipball/c6222283fa3f4ac679f8b9ced9a4e23f163e80d0",
"reference": "c6222283fa3f4ac679f8b9ced9a4e23f163e80d0",
"shasum": ""
},
"require": {
"php": "^7.1 || ^8.0"
"php": "^8.1"
},
"require-dev": {
"doctrine/coding-standard": "^9 || ^11",
"doctrine/coding-standard": "^11",
"ext-pdo": "*",
"ext-phar": "*",
"phpbench/phpbench": "^0.16 || ^1",
"phpstan/phpstan": "^1.4",
"phpstan/phpstan-phpunit": "^1",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"vimeo/psalm": "^4.30 || ^5.4"
"phpbench/phpbench": "^1.2",
"phpstan/phpstan": "^1.9.4",
"phpstan/phpstan-phpunit": "^1.3",
"phpunit/phpunit": "^9.5.27",
"vimeo/psalm": "^5.4"
},
"type": "library",
"autoload": {
@ -851,7 +851,7 @@
],
"support": {
"issues": "https://github.com/doctrine/instantiator/issues",
"source": "https://github.com/doctrine/instantiator/tree/1.5.0"
"source": "https://github.com/doctrine/instantiator/tree/2.0.0"
},
"funding": [
{
@ -867,7 +867,7 @@
"type": "tidelift"
}
],
"time": "2022-12-30T00:15:36+00:00"
"time": "2022-12-30T00:23:10+00:00"
},
{
"name": "fakerphp/faker",
@ -939,16 +939,16 @@
},
{
"name": "friendsofphp/php-cs-fixer",
"version": "v3.26.1",
"version": "v3.27.0",
"source": {
"type": "git",
"url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git",
"reference": "d023ba6684055f6ea1da1352d8a02baca0426983"
"reference": "e73ccaae1208f017bb7860986eebb3da48bd25d6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/d023ba6684055f6ea1da1352d8a02baca0426983",
"reference": "d023ba6684055f6ea1da1352d8a02baca0426983",
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/e73ccaae1208f017bb7860986eebb3da48bd25d6",
"reference": "e73ccaae1208f017bb7860986eebb3da48bd25d6",
"shasum": ""
},
"require": {
@ -1022,7 +1022,7 @@
],
"support": {
"issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues",
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.26.1"
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.27.0"
},
"funding": [
{
@ -1030,7 +1030,7 @@
"type": "github"
}
],
"time": "2023-09-08T19:09:07+00:00"
"time": "2023-09-17T14:37:54+00:00"
},
{
"name": "kint-php/kint",
@ -1150,21 +1150,21 @@
},
{
"name": "nexusphp/cs-config",
"version": "v3.15.0",
"version": "v3.16.0",
"source": {
"type": "git",
"url": "https://github.com/NexusPHP/cs-config.git",
"reference": "b76198c0b0d563e6a917509348a9145df3de43dc"
"reference": "0d02bf2a9aca5e9af344e7000b973e815190b2fb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/NexusPHP/cs-config/zipball/b76198c0b0d563e6a917509348a9145df3de43dc",
"reference": "b76198c0b0d563e6a917509348a9145df3de43dc",
"url": "https://api.github.com/repos/NexusPHP/cs-config/zipball/0d02bf2a9aca5e9af344e7000b973e815190b2fb",
"reference": "0d02bf2a9aca5e9af344e7000b973e815190b2fb",
"shasum": ""
},
"require": {
"ext-tokenizer": "*",
"friendsofphp/php-cs-fixer": "^3.24",
"friendsofphp/php-cs-fixer": "^3.27",
"php": "^8.0.1"
},
"conflict": {
@ -1215,7 +1215,7 @@
"type": "github"
}
],
"time": "2023-08-30T03:31:34+00:00"
"time": "2023-09-18T10:02:35+00:00"
},
{
"name": "nikic/php-parser",
@ -1386,16 +1386,16 @@
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.28",
"version": "9.2.29",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "7134a5ccaaf0f1c92a4f5501a6c9f98ac4dcc0ef"
"reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7134a5ccaaf0f1c92a4f5501a6c9f98ac4dcc0ef",
"reference": "7134a5ccaaf0f1c92a4f5501a6c9f98ac4dcc0ef",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6a3a87ac2bbe33b25042753df8195ba4aa534c76",
"reference": "6a3a87ac2bbe33b25042753df8195ba4aa534c76",
"shasum": ""
},
"require": {
@ -1452,7 +1452,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.28"
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.29"
},
"funding": [
{
@ -1460,7 +1460,7 @@
"type": "github"
}
],
"time": "2023-09-12T14:36:20+00:00"
"time": "2023-09-19T04:57:46+00:00"
},
{
"name": "phpunit/php-file-iterator",
@ -1705,16 +1705,16 @@
},
{
"name": "phpunit/phpunit",
"version": "9.6.12",
"version": "9.6.13",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "a122c2ebd469b751d774aa0f613dc0d67697653f"
"reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a122c2ebd469b751d774aa0f613dc0d67697653f",
"reference": "a122c2ebd469b751d774aa0f613dc0d67697653f",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f3d767f7f9e191eab4189abe41ab37797e30b1be",
"reference": "f3d767f7f9e191eab4189abe41ab37797e30b1be",
"shasum": ""
},
"require": {
@ -1788,7 +1788,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.12"
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.13"
},
"funding": [
{
@ -1804,7 +1804,7 @@
"type": "tidelift"
}
],
"time": "2023-09-12T14:39:31+00:00"
"time": "2023-09-19T05:39:22+00:00"
},
{
"name": "predis/predis",
@ -2936,22 +2936,23 @@
},
{
"name": "symfony/console",
"version": "v6.0.19",
"version": "v6.3.4",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "c3ebc83d031b71c39da318ca8b7a07ecc67507ed"
"reference": "eca495f2ee845130855ddf1cf18460c38966c8b6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/c3ebc83d031b71c39da318ca8b7a07ecc67507ed",
"reference": "c3ebc83d031b71c39da318ca8b7a07ecc67507ed",
"url": "https://api.github.com/repos/symfony/console/zipball/eca495f2ee845130855ddf1cf18460c38966c8b6",
"reference": "eca495f2ee845130855ddf1cf18460c38966c8b6",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-mbstring": "~1.0",
"symfony/service-contracts": "^1.1|^2|^3",
"symfony/service-contracts": "^2.5|^3",
"symfony/string": "^5.4|^6.0"
},
"conflict": {
@ -2973,12 +2974,6 @@
"symfony/process": "^5.4|^6.0",
"symfony/var-dumper": "^5.4|^6.0"
},
"suggest": {
"psr/log": "For using the console logger",
"symfony/event-dispatcher": "",
"symfony/lock": "",
"symfony/process": ""
},
"type": "library",
"autoload": {
"psr-4": {
@ -3006,12 +3001,12 @@
"homepage": "https://symfony.com",
"keywords": [
"cli",
"command line",
"command-line",
"console",
"terminal"
],
"support": {
"source": "https://github.com/symfony/console/tree/v6.0.19"
"source": "https://github.com/symfony/console/tree/v6.3.4"
},
"funding": [
{
@ -3027,29 +3022,29 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-08-16T10:10:12+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.0.2",
"version": "v3.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c"
"reference": "7c3aff79d10325257a001fcf92d991f24fc967cf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"reference": "26954b3d62a6c5fd0ea8a2a00c0353a14978d05c",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf",
"reference": "7c3aff79d10325257a001fcf92d991f24fc967cf",
"shasum": ""
},
"require": {
"php": ">=8.0.2"
"php": ">=8.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
"dev-main": "3.4-dev"
},
"thanks": {
"name": "symfony/contracts",
@ -3078,7 +3073,7 @@
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.2"
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.3.0"
},
"funding": [
{
@ -3094,28 +3089,29 @@
"type": "tidelift"
}
],
"time": "2022-01-02T09:55:41+00:00"
"time": "2023-05-23T14:45:45+00:00"
},
{
"name": "symfony/event-dispatcher",
"version": "v6.0.19",
"version": "v6.3.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/event-dispatcher.git",
"reference": "2eaf8e63bc5b8cefabd4a800157f0d0c094f677a"
"reference": "adb01fe097a4ee930db9258a3cc906b5beb5cf2e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/2eaf8e63bc5b8cefabd4a800157f0d0c094f677a",
"reference": "2eaf8e63bc5b8cefabd4a800157f0d0c094f677a",
"url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/adb01fe097a4ee930db9258a3cc906b5beb5cf2e",
"reference": "adb01fe097a4ee930db9258a3cc906b5beb5cf2e",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"symfony/event-dispatcher-contracts": "^2|^3"
"php": ">=8.1",
"symfony/event-dispatcher-contracts": "^2.5|^3"
},
"conflict": {
"symfony/dependency-injection": "<5.4"
"symfony/dependency-injection": "<5.4",
"symfony/service-contracts": "<2.5"
},
"provide": {
"psr/event-dispatcher-implementation": "1.0",
@ -3128,13 +3124,9 @@
"symfony/error-handler": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/service-contracts": "^1.1|^2|^3",
"symfony/service-contracts": "^2.5|^3",
"symfony/stopwatch": "^5.4|^6.0"
},
"suggest": {
"symfony/dependency-injection": "",
"symfony/http-kernel": ""
},
"type": "library",
"autoload": {
"psr-4": {
@ -3161,7 +3153,7 @@
"description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/event-dispatcher/tree/v6.0.19"
"source": "https://github.com/symfony/event-dispatcher/tree/v6.3.2"
},
"funding": [
{
@ -3177,33 +3169,30 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-07-06T06:56:43+00:00"
},
{
"name": "symfony/event-dispatcher-contracts",
"version": "v3.0.2",
"version": "v3.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/event-dispatcher-contracts.git",
"reference": "7bc61cc2db649b4637d331240c5346dcc7708051"
"reference": "a76aed96a42d2b521153fb382d418e30d18b59df"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/7bc61cc2db649b4637d331240c5346dcc7708051",
"reference": "7bc61cc2db649b4637d331240c5346dcc7708051",
"url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/a76aed96a42d2b521153fb382d418e30d18b59df",
"reference": "a76aed96a42d2b521153fb382d418e30d18b59df",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"psr/event-dispatcher": "^1"
},
"suggest": {
"symfony/event-dispatcher-implementation": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
"dev-main": "3.4-dev"
},
"thanks": {
"name": "symfony/contracts",
@ -3240,7 +3229,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.0.2"
"source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.3.0"
},
"funding": [
{
@ -3256,24 +3245,24 @@
"type": "tidelift"
}
],
"time": "2022-01-02T09:55:41+00:00"
"time": "2023-05-23T14:45:45+00:00"
},
{
"name": "symfony/filesystem",
"version": "v6.0.19",
"version": "v6.3.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/filesystem.git",
"reference": "3d49eec03fda1f0fc19b7349fbbe55ebc1004214"
"reference": "edd36776956f2a6fcf577edb5b05eb0e3bdc52ae"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/filesystem/zipball/3d49eec03fda1f0fc19b7349fbbe55ebc1004214",
"reference": "3d49eec03fda1f0fc19b7349fbbe55ebc1004214",
"url": "https://api.github.com/repos/symfony/filesystem/zipball/edd36776956f2a6fcf577edb5b05eb0e3bdc52ae",
"reference": "edd36776956f2a6fcf577edb5b05eb0e3bdc52ae",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-mbstring": "~1.8"
},
@ -3303,7 +3292,7 @@
"description": "Provides basic utilities for the filesystem",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/filesystem/tree/v6.0.19"
"source": "https://github.com/symfony/filesystem/tree/v6.3.1"
},
"funding": [
{
@ -3319,24 +3308,27 @@
"type": "tidelift"
}
],
"time": "2023-01-20T17:44:14+00:00"
"time": "2023-06-01T08:30:39+00:00"
},
{
"name": "symfony/finder",
"version": "v6.0.19",
"version": "v6.3.3",
"source": {
"type": "git",
"url": "https://github.com/symfony/finder.git",
"reference": "5cc9cac6586fc0c28cd173780ca696e419fefa11"
"reference": "9915db259f67d21eefee768c1abcf1cc61b1fc9e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/finder/zipball/5cc9cac6586fc0c28cd173780ca696e419fefa11",
"reference": "5cc9cac6586fc0c28cd173780ca696e419fefa11",
"url": "https://api.github.com/repos/symfony/finder/zipball/9915db259f67d21eefee768c1abcf1cc61b1fc9e",
"reference": "9915db259f67d21eefee768c1abcf1cc61b1fc9e",
"shasum": ""
},
"require": {
"php": ">=8.0.2"
"php": ">=8.1"
},
"require-dev": {
"symfony/filesystem": "^6.0"
},
"type": "library",
"autoload": {
@ -3364,7 +3356,7 @@
"description": "Finds files and directories via an intuitive fluent interface",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/finder/tree/v6.0.19"
"source": "https://github.com/symfony/finder/tree/v6.3.3"
},
"funding": [
{
@ -3380,25 +3372,25 @@
"type": "tidelift"
}
],
"time": "2023-01-20T17:44:14+00:00"
"time": "2023-07-31T08:31:44+00:00"
},
{
"name": "symfony/options-resolver",
"version": "v6.0.19",
"version": "v6.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/options-resolver.git",
"reference": "6a180d1c45e0d9797470ca9eb46215692de00fa3"
"reference": "a10f19f5198d589d5c33333cffe98dc9820332dd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/options-resolver/zipball/6a180d1c45e0d9797470ca9eb46215692de00fa3",
"reference": "6a180d1c45e0d9797470ca9eb46215692de00fa3",
"url": "https://api.github.com/repos/symfony/options-resolver/zipball/a10f19f5198d589d5c33333cffe98dc9820332dd",
"reference": "a10f19f5198d589d5c33333cffe98dc9820332dd",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"symfony/deprecation-contracts": "^2.1|^3"
"php": ">=8.1",
"symfony/deprecation-contracts": "^2.5|^3"
},
"type": "library",
"autoload": {
@ -3431,7 +3423,7 @@
"options"
],
"support": {
"source": "https://github.com/symfony/options-resolver/tree/v6.0.19"
"source": "https://github.com/symfony/options-resolver/tree/v6.3.0"
},
"funding": [
{
@ -3447,7 +3439,7 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-05-12T14:21:09+00:00"
},
{
"name": "symfony/polyfill-ctype",
@ -3943,20 +3935,20 @@
},
{
"name": "symfony/process",
"version": "v6.0.19",
"version": "v6.3.4",
"source": {
"type": "git",
"url": "https://github.com/symfony/process.git",
"reference": "2114fd60f26a296cc403a7939ab91478475a33d4"
"reference": "0b5c29118f2e980d455d2e34a5659f4579847c54"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/process/zipball/2114fd60f26a296cc403a7939ab91478475a33d4",
"reference": "2114fd60f26a296cc403a7939ab91478475a33d4",
"url": "https://api.github.com/repos/symfony/process/zipball/0b5c29118f2e980d455d2e34a5659f4579847c54",
"reference": "0b5c29118f2e980d455d2e34a5659f4579847c54",
"shasum": ""
},
"require": {
"php": ">=8.0.2"
"php": ">=8.1"
},
"type": "library",
"autoload": {
@ -3984,7 +3976,7 @@
"description": "Executes commands in sub-processes",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/process/tree/v6.0.19"
"source": "https://github.com/symfony/process/tree/v6.3.4"
},
"funding": [
{
@ -4000,36 +3992,33 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-08-07T10:39:22+00:00"
},
{
"name": "symfony/service-contracts",
"version": "v3.0.2",
"version": "v3.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/service-contracts.git",
"reference": "d78d39c1599bd1188b8e26bb341da52c3c6d8a66"
"reference": "40da9cc13ec349d9e4966ce18b5fbcd724ab10a4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/d78d39c1599bd1188b8e26bb341da52c3c6d8a66",
"reference": "d78d39c1599bd1188b8e26bb341da52c3c6d8a66",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/40da9cc13ec349d9e4966ce18b5fbcd724ab10a4",
"reference": "40da9cc13ec349d9e4966ce18b5fbcd724ab10a4",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"psr/container": "^2.0"
},
"conflict": {
"ext-psr": "<1.1|>=2"
},
"suggest": {
"symfony/service-implementation": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.0-dev"
"dev-main": "3.4-dev"
},
"thanks": {
"name": "symfony/contracts",
@ -4039,7 +4028,10 @@
"autoload": {
"psr-4": {
"Symfony\\Contracts\\Service\\": ""
}
},
"exclude-from-classmap": [
"/Test/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@ -4066,7 +4058,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/service-contracts/tree/v3.0.2"
"source": "https://github.com/symfony/service-contracts/tree/v3.3.0"
},
"funding": [
{
@ -4082,25 +4074,25 @@
"type": "tidelift"
}
],
"time": "2022-05-30T19:17:58+00:00"
"time": "2023-05-23T14:45:45+00:00"
},
{
"name": "symfony/stopwatch",
"version": "v6.0.19",
"version": "v6.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/stopwatch.git",
"reference": "011e781839dd1d2eb8119f65ac516a530f60226d"
"reference": "fc47f1015ec80927ff64ba9094dfe8b9d48fe9f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/stopwatch/zipball/011e781839dd1d2eb8119f65ac516a530f60226d",
"reference": "011e781839dd1d2eb8119f65ac516a530f60226d",
"url": "https://api.github.com/repos/symfony/stopwatch/zipball/fc47f1015ec80927ff64ba9094dfe8b9d48fe9f2",
"reference": "fc47f1015ec80927ff64ba9094dfe8b9d48fe9f2",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"symfony/service-contracts": "^1|^2|^3"
"php": ">=8.1",
"symfony/service-contracts": "^2.5|^3"
},
"type": "library",
"autoload": {
@ -4128,7 +4120,7 @@
"description": "Provides a way to profile code",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/stopwatch/tree/v6.0.19"
"source": "https://github.com/symfony/stopwatch/tree/v6.3.0"
},
"funding": [
{
@ -4144,36 +4136,37 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-02-16T10:14:28+00:00"
},
{
"name": "symfony/string",
"version": "v6.0.19",
"version": "v6.3.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/string.git",
"reference": "d9e72497367c23e08bf94176d2be45b00a9d232a"
"reference": "53d1a83225002635bca3482fcbf963001313fb68"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/string/zipball/d9e72497367c23e08bf94176d2be45b00a9d232a",
"reference": "d9e72497367c23e08bf94176d2be45b00a9d232a",
"url": "https://api.github.com/repos/symfony/string/zipball/53d1a83225002635bca3482fcbf963001313fb68",
"reference": "53d1a83225002635bca3482fcbf963001313fb68",
"shasum": ""
},
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-intl-grapheme": "~1.0",
"symfony/polyfill-intl-normalizer": "~1.0",
"symfony/polyfill-mbstring": "~1.0"
},
"conflict": {
"symfony/translation-contracts": "<2.0"
"symfony/translation-contracts": "<2.5"
},
"require-dev": {
"symfony/error-handler": "^5.4|^6.0",
"symfony/http-client": "^5.4|^6.0",
"symfony/translation-contracts": "^2.0|^3.0",
"symfony/intl": "^6.2",
"symfony/translation-contracts": "^2.5|^3.0",
"symfony/var-exporter": "^5.4|^6.0"
},
"type": "library",
@ -4213,7 +4206,7 @@
"utf8"
],
"support": {
"source": "https://github.com/symfony/string/tree/v6.0.19"
"source": "https://github.com/symfony/string/tree/v6.3.2"
},
"funding": [
{
@ -4229,7 +4222,7 @@
"type": "tidelift"
}
],
"time": "2023-01-01T08:36:10+00:00"
"time": "2023-07-05T08:41:27+00:00"
},
{
"name": "theseer/tokenizer",
@ -4294,5 +4287,5 @@
"ext-mbstring": "*"
},
"platform-dev": [],
"plugin-api-version": "2.6.0"
"plugin-api-version": "2.2.0"
}

4184
old_composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit01bb8cdaddb35dba667c1b3b51c53f89::getLoader();

View File

@ -1,117 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Proxy PHP file generated by Composer
*
* This file includes the referenced bin path (../friendsofphp/php-cs-fixer/php-cs-fixer)
* using a stream wrapper to prevent the shebang from being output on PHP<8
*
* @generated
*/
namespace Composer;
$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
if (PHP_VERSION_ID < 80000) {
if (!class_exists('Composer\BinProxyWrapper')) {
/**
* @internal
*/
final class BinProxyWrapper
{
private $handle;
private $position;
private $realpath;
public function stream_open($path, $mode, $options, &$opened_path)
{
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
$opened_path = substr($path, 17);
$this->realpath = realpath($opened_path) ?: $opened_path;
$opened_path = $this->realpath;
$this->handle = fopen($this->realpath, $mode);
$this->position = 0;
return (bool) $this->handle;
}
public function stream_read($count)
{
$data = fread($this->handle, $count);
if ($this->position === 0) {
$data = preg_replace('{^#!.*\r?\n}', '', $data);
}
$this->position += strlen($data);
return $data;
}
public function stream_cast($castAs)
{
return $this->handle;
}
public function stream_close()
{
fclose($this->handle);
}
public function stream_lock($operation)
{
return $operation ? flock($this->handle, $operation) : true;
}
public function stream_seek($offset, $whence)
{
if (0 === fseek($this->handle, $offset, $whence)) {
$this->position = ftell($this->handle);
return true;
}
return false;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
return feof($this->handle);
}
public function stream_stat()
{
return array();
}
public function stream_set_option($option, $arg1, $arg2)
{
return true;
}
public function url_stat($path, $flags)
{
$path = substr($path, 17);
if (file_exists($path)) {
return stat($path);
}
return false;
}
}
}
if (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) {
include("phpvfscomposer://" . __DIR__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer');
exit(0);
}
}
include __DIR__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer';

View File

@ -1,117 +0,0 @@
#!/usr/bin/env php
<?php
/**
* Proxy PHP file generated by Composer
*
* This file includes the referenced bin path (../nikic/php-parser/bin/php-parse)
* using a stream wrapper to prevent the shebang from being output on PHP<8
*
* @generated
*/
namespace Composer;
$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
if (PHP_VERSION_ID < 80000) {
if (!class_exists('Composer\BinProxyWrapper')) {
/**
* @internal
*/
final class BinProxyWrapper
{
private $handle;
private $position;
private $realpath;
public function stream_open($path, $mode, $options, &$opened_path)
{
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
$opened_path = substr($path, 17);
$this->realpath = realpath($opened_path) ?: $opened_path;
$opened_path = $this->realpath;
$this->handle = fopen($this->realpath, $mode);
$this->position = 0;
return (bool) $this->handle;
}
public function stream_read($count)
{
$data = fread($this->handle, $count);
if ($this->position === 0) {
$data = preg_replace('{^#!.*\r?\n}', '', $data);
}
$this->position += strlen($data);
return $data;
}
public function stream_cast($castAs)
{
return $this->handle;
}
public function stream_close()
{
fclose($this->handle);
}
public function stream_lock($operation)
{
return $operation ? flock($this->handle, $operation) : true;
}
public function stream_seek($offset, $whence)
{
if (0 === fseek($this->handle, $offset, $whence)) {
$this->position = ftell($this->handle);
return true;
}
return false;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
return feof($this->handle);
}
public function stream_stat()
{
return array();
}
public function stream_set_option($option, $arg1, $arg2)
{
return true;
}
public function url_stat($path, $flags)
{
$path = substr($path, 17);
if (file_exists($path)) {
return stat($path);
}
return false;
}
}
}
if (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) {
include("phpvfscomposer://" . __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse');
exit(0);
}
}
include __DIR__ . '/..'.'/nikic/php-parser/bin/php-parse';

View File

@ -1,88 +0,0 @@
# Changelog
All notable changes to this library will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.7.1](https://github.com/CodeIgniter/coding-standard/compare/v1.7.0...v1.7.1) - 2022-12-22
- Fix php-cs-fixer version to 3.13.0
## [v1.7.0](https://github.com/CodeIgniter/coding-standard/compare/v1.6.2...v1.7.0) - 2022-11-01
- Bump php-cs-fixer to v3.13
- Add 'case_sensitive' option to 'general_phpdoc_annotation_remove'
- Add 'closure_fn_spacing' option to 'function_declaration'
## [v1.6.2](https://github.com/CodeIgniter/coding-standard/compare/v1.6.1...v1.6.2) - 2022-10-30
- Grouped `runTestsInSeparateProcess`, `runInSeparateProcess`, `preserveGlobalState` together
## [v1.6.1](https://github.com/CodeIgniter/coding-standard/compare/v1.6.0...v1.6.1) - 2022-10-20
- Changed `@internal` description of class CodeIgniter4 to avoid warnings in phpstorm
## [v1.6.0](https://github.com/CodeIgniter/coding-standard/compare/v1.5.0...v1.6.0) - 2022-10-15
- Bump php-cs-fixer version to v3.12 minimum
- Enable `no_useless_concat_operator`
- Update action workflows
## [v1.5.0](https://github.com/CodeIgniter/coding-standard/compare/v1.4.0...v1.5.0) - 2022-09-13
- Enable `ensure_single_space` option of `whitespace_after_comma_in_array`
- Use the `space_multiple_catch` option of `types_spaces`
- Fix multi-lines
- Add `group_to_single_imports` option to `single_import_per_statement`
- chore: fix editorconfig (#4)
- docs: add CONTRIBUTING.md (#3)
- Enable `date_time_create_from_format_call`
- Add options to `new_with_braces`
- Add `order` option to `phpdoc_order`
- Add the `trailing_comma_single_line` option to `function_declaration`
- Enable `curly_braces_position`
- Enable `single_line_comment_spacing`
- Enable `no_trailing_comma_in_singleline`
- Normalize composer.json
- Add "static analysis" Composer keyword (#2)
- Add `inline_constructor_arguments` option to `class_definition`
- Enable `statement_indentation`
- Enable `no_useless_nullsafe_operator`
- Enable `no_multiple_statements_per_line`
- Enable `control_structure_braces`
- Enable `blank_line_between_import_groups`
- Remove deprecated fixers
- Configure `groups` option in `phpdoc_separation` rule
- Bump php-cs-fixer version
## [v1.4.0](https://github.com/CodeIgniter/coding-standard/compare/v1.3.0...v1.4.0) - 2022-02-09
- Permit use of latest php-cs-fixer v3.6.0
## [v1.3.0](https://github.com/CodeIgniter/coding-standard/compare/v1.2.0...v1.3.0) - 2022-01-15
- Fix GHA workflows
- Bump versions
- PHP 7.4 minimum
- friendsofphp/php-cs-fixer v3.4.0
- phpstan/phpstan v1.0 minimum
- Enable `ordered_class_elements` rule
- Enable `global_namespace_import` rule (#1)
- Use `GITHUB_TOKEN` so that secrets can be passed to PRs
## [v1.2.0](https://github.com/CodeIgniter/coding-standard/compare/v1.1.0...v1.2.0) - 2021-10-18
- Bump `friendsofphp/php-cs-fixer` to v3.2 minimum
- Change behavior of `class_attributes_separation` rule
- Add support for new fixers added in php-cs-fixer v3.2.0
- Enable `no_alternative_syntax` rule
## [v1.1.0](https://github.com/CodeIgniter/coding-standard/compare/v1.0.0...v1.1.0) - 2021-08-31
- Bump to `friendsofphp/php-cs-fixer` v3.1.0
- Fix release script
- Bump to `nexusphp/cs-config` v3.3.0
## [v1.0.0](https://github.com/CodeIgniter/coding-standard/releases/tag/v1.0.0) - 2021-08-29
Initial release.

View File

@ -1,10 +0,0 @@
# Contributing to CodeIgniter Coding Standard
CodeIgniter Coding Standard is a community driven project and accepts contributions of
code and documentation from the community.
If you'd like to contribute, please read the [Contributing to CodeIgniter](https://github.com/codeigniter4/CodeIgniter4/blob/develop/contributing/README.md)
guide in the [main repository](https://github.com/codeigniter4/CodeIgniter4).
If you are going to contribute to this repository, please report bugs or send PRs
to this repository instead of the main repository.

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2021 CodeIgniter Foundation and John Paul E. Balandan, CPA
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,115 +0,0 @@
# CodeIgniter Coding Standard
[![Unit Tests](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-phpunit.yml/badge.svg)](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-phpunit.yml)
[![Coding Standards](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-coding-standards.yml/badge.svg)](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-coding-standards.yml)
[![PHPStan Static Analysis](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-phpstan.yml/badge.svg)](https://github.com/CodeIgniter/coding-standard/actions/workflows/test-phpstan.yml)
[![PHPStan level](https://img.shields.io/badge/PHPStan-max%20level-brightgreen)](phpstan.neon.dist)
[![Coverage Status](https://coveralls.io/repos/github/CodeIgniter/coding-standard/badge.svg?branch=develop)](https://coveralls.io/github/CodeIgniter/coding-standard?branch=develop)
[![Latest Stable Version](http://poser.pugx.org/codeigniter/coding-standard/v)](https://packagist.org/packages/codeigniter/coding-standard)
[![License](https://img.shields.io/github/license/codeigniter/coding-standard)](LICENSE)
[![Total Downloads](http://poser.pugx.org/codeigniter/coding-standard/downloads)](https://packagist.org/packages/codeigniter/coding-standard)
This library holds the official coding standards of CodeIgniter based
on [PHP CS Fixer][1] and powered by [Nexus CS Config][2].
## Installation
You can add this library as a local, per-project dependency to your project
using [Composer](https://getcomposer.org/):
composer require codeigniter/coding-standard
If you only need this library during development, for instance to run your project's test suite,
then you should add it as a development-time dependency:
composer require --dev codeigniter/coding-standard
## Setup
To start, let us create a `.php-cs-fixer.dist.php` file at the root of your project.
```php
<?php
use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;
return Factory::create(new CodeIgniter4())->forProjects();
```
This minimal setup will return a default instance of `PhpCsFixer\Config` containing all rules applicable
for the CodeIgniter organization.
Then, in your terminal, run the following command:
```console
$ vendor/bin/php-cs-fixer fix --verbose
```
## Adding License Headers
The default setup will not configure a license header in files. License headers can be especially useful
for library authors to assert copyright. To add license headers in your PHP files, you can simply provide
your name and name of library. Optionally, you can also provide your email and starting license year.
```diff
<?php
use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;
-return Factory::create(new CodeIgniter4())->forProjects();
+return Factory::create(new CodeIgniter4())->forLibrary(
+ 'CodeIgniter 4 framework',
+ 'CodeIgniter Foundation',
+ 'admin@codeigniter.com',
+ 2021,
+);
```
## Providing Overriding Rules and Options
The list of enabled rules can be found in the [`CodeIgniter\CodingStandard\CodeIgniter4`][3] class. If you
feel the rule is not applicable to you or you want to modify it, you can do so by providing an array of
overriding rules to the second parameter of `Factory::create()`.
Similarly, you can further modify the `PhpCsFixer\Config` instance returned by using the available options.
All available options are fully supported by [Nexus CS Config][2] and abstracted by simply providing an
array of key-value pairs in the third parameter of `Factory::create()`.
```diff
<?php
use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;
-return Factory::create(new CodeIgniter4())->forProjects();
+return Factory::create(new CodeIgniter4(), [], [
+ 'usingCache' => false,
+])->forProjects();
```
You can check out this library's own [`.php-cs-fixer.dist.php`][4] for inspiration on how it is done.
For more detailed documentation on all available options, you can check [here][2].
## Contributing
All forms of contributions are welcome!
Since the rules here will be propagated and used within the CodeIgniter organization, all proposed rules
and modifications to existing rules should have a proof-of-concept (POC) PR sent first to
the [CodeIgniter4][5] repository with possible changes to the code styles applied there. Once accepted
there, you can send in a PR here to apply those rules.
## License
This work is open-sourced under the MIT license.
[1]: https://github.com/FriendsOfPHP/PHP-CS-Fixer
[2]: https://github.com/NexusPHP/cs-config
[3]: src/CodeIgniter4.php
[4]: .php-cs-fixer.dist.php
[5]: https://github.com/codeigniter4/CodeIgniter4

View File

@ -1,49 +0,0 @@
{
"name": "codeigniter/coding-standard",
"description": "Official Coding Standards for CodeIgniter based on PHP CS Fixer",
"license": "MIT",
"type": "library",
"keywords": [
"phpcs",
"static analysis"
],
"authors": [
{
"name": "John Paul E. Balandan, CPA",
"email": "paulbalandan@gmail.com"
}
],
"support": {
"forum": "http://forum.codeigniter.com/",
"source": "https://github.com/CodeIgniter/coding-standard",
"slack": "https://codeigniterchat.slack.com"
},
"require": {
"php": "^7.4 || ^8.0",
"ext-tokenizer": "*",
"friendsofphp/php-cs-fixer": "3.13.0",
"nexusphp/cs-config": "^3.6"
},
"require-dev": {
"nexusphp/tachycardia": "^1.3",
"phpstan/phpstan": "^1.0",
"phpunit/phpunit": "^9.5"
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
"psr-4": {
"CodeIgniter\\CodingStandard\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"CodeIgniter\\CodingStandard\\Tests\\": "tests/"
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
}
}

View File

@ -1,616 +0,0 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) 2021 CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CodingStandard;
use Nexus\CsConfig\Ruleset\AbstractRuleset;
/**
* Defines the ruleset used for the CodeIgniter4 organization.
*
* {@internal Use of this class is not covered by the backward compatibility promise for CodeIgniter4.}
*/
final class CodeIgniter4 extends AbstractRuleset
{
public function __construct()
{
$this->name = 'CodeIgniter4 Coding Standards';
$this->rules = [
'align_multiline_comment' => ['comment_type' => 'phpdocs_only'],
'array_indentation' => true,
'array_push' => true,
'array_syntax' => ['syntax' => 'short'],
'assign_null_coalescing_to_coalesce_equal' => true,
'backtick_to_shell_exec' => true,
'binary_operator_spaces' => [
'default' => 'single_space',
'operators' => [
'=' => 'align_single_space_minimal',
'=>' => 'align_single_space_minimal',
'||' => 'align_single_space_minimal',
'.=' => 'align_single_space_minimal',
],
],
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'blank_line_before_statement' => [
'statements' => [
'case',
'continue',
'declare',
'default',
'do',
'exit',
'for',
'foreach',
'goto',
'return',
'switch',
'throw',
'try',
'while',
'yield',
'yield_from',
],
],
'blank_line_between_import_groups' => true,
'braces' => [
'allow_single_line_anonymous_class_with_empty_body' => true,
'allow_single_line_closure' => true,
'position_after_anonymous_constructs' => 'same',
'position_after_control_structures' => 'same',
'position_after_functions_and_oop_constructs' => 'next',
],
'cast_spaces' => ['space' => 'single'],
'class_attributes_separation' => [
'elements' => [
'const' => 'none',
'property' => 'none',
'method' => 'one',
'trait_import' => 'none',
],
],
'class_definition' => [
'multi_line_extends_each_single_line' => true,
'single_item_single_line' => true,
'single_line' => true,
'space_before_parenthesis' => true,
'inline_constructor_arguments' => true,
],
'class_reference_name_casing' => true,
'clean_namespace' => true,
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'combine_nested_dirname' => true,
'comment_to_phpdoc' => [
'ignored_tags' => [
'todo',
'codeCoverageIgnore',
'codeCoverageIgnoreStart',
'codeCoverageIgnoreEnd',
'phpstan-ignore-line',
'phpstan-ignore-next-line',
],
],
'compact_nullable_typehint' => true,
'concat_space' => ['spacing' => 'one'],
'constant_case' => ['case' => 'lower'],
'control_structure_braces' => true,
'control_structure_continuation_position' => ['position' => 'same_line'],
'curly_braces_position' => [
'control_structures_opening_brace' => 'same_line',
'functions_opening_brace' => 'next_line_unless_newline_at_signature_end',
'anonymous_functions_opening_brace' => 'same_line',
'classes_opening_brace' => 'next_line_unless_newline_at_signature_end',
'anonymous_classes_opening_brace' => 'same_line',
'allow_single_line_empty_anonymous_classes' => true,
'allow_single_line_anonymous_functions' => true,
],
'date_time_create_from_format_call' => true,
'date_time_immutable' => false,
'declare_equal_normalize' => ['space' => 'none'],
'declare_parentheses' => true,
'declare_strict_types' => false,
'dir_constant' => true,
'doctrine_annotation_array_assignment' => false,
'doctrine_annotation_braces' => false,
'doctrine_annotation_indentation' => false,
'doctrine_annotation_spaces' => false,
'echo_tag_syntax' => [
'format' => 'short',
'long_function' => 'echo',
'shorten_simple_statements_only' => false,
],
'elseif' => true,
'empty_loop_body' => ['style' => 'braces'],
'empty_loop_condition' => ['style' => 'while'],
'encoding' => true,
'ereg_to_preg' => true,
'error_suppression' => [
'mute_deprecation_error' => true,
'noise_remaining_usages' => false,
'noise_remaining_usages_exclude' => [],
],
'escape_implicit_backslashes' => [
'double_quoted' => true,
'heredoc_syntax' => true,
'single_quoted' => false,
],
'explicit_indirect_variable' => true,
'explicit_string_variable' => true,
'final_class' => false,
'final_internal_class' => [
'annotation_exclude' => ['@no-final'],
'annotation_include' => ['@internal'],
'consider_absent_docblock_as_internal_class' => false,
],
'final_public_method_for_abstract_class' => false,
'fopen_flag_order' => true,
'fopen_flags' => ['b_mode' => true],
'full_opening_tag' => true,
'fully_qualified_strict_types' => true,
'function_declaration' => [
'closure_function_spacing' => 'one',
'closure_fn_spacing' => 'one',
'trailing_comma_single_line' => false,
],
'function_to_constant' => [
'functions' => [
'get_called_class',
'get_class',
'get_class_this',
'php_sapi_name',
'phpversion',
'pi',
],
],
'function_typehint_space' => true,
'general_phpdoc_annotation_remove' => [
'annotations' => [
'author',
'package',
'subpackage',
],
'case_sensitive' => false,
],
'general_phpdoc_tag_rename' => [
'case_sensitive' => false,
'fix_annotation' => true,
'fix_inline' => true,
'replacements' => ['inheritDocs' => 'inheritDoc'],
],
'get_class_to_class_keyword' => false,
'global_namespace_import' => [
'import_constants' => false,
'import_functions' => false,
'import_classes' => true,
],
'group_import' => false,
'header_comment' => false, // false by default
'heredoc_indentation' => ['indentation' => 'start_plus_one'],
'heredoc_to_nowdoc' => true,
'implode_call' => true,
'include' => true,
'increment_style' => ['style' => 'post'],
'indentation_type' => true,
'integer_literal_case' => true,
'is_null' => true,
'lambda_not_used_import' => true,
'line_ending' => true,
'linebreak_after_opening_tag' => true,
'list_syntax' => ['syntax' => 'short'],
'logical_operators' => true,
'lowercase_cast' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true,
'magic_constant_casing' => true,
'magic_method_casing' => true,
'mb_str_functions' => false,
'method_argument_space' => [
'after_heredoc' => false,
'keep_multiple_spaces_after_comma' => false,
'on_multiline' => 'ensure_fully_multiline',
],
'method_chaining_indentation' => true,
'modernize_strpos' => false, // requires 8.0+
'modernize_types_casting' => true,
'multiline_comment_opening_closing' => true,
'multiline_whitespace_before_semicolons' => ['strategy' => 'no_multi_line'],
'native_constant_invocation' => false,
'native_function_casing' => true,
'native_function_invocation' => false,
'native_function_type_declaration_casing' => true,
'new_with_braces' => [
'named_class' => true,
'anonymous_class' => true,
],
'no_alias_functions' => ['sets' => ['@all']],
'no_alias_language_construct_call' => true,
'no_alternative_syntax' => ['fix_non_monolithic_code' => false],
'no_binary_string' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_blank_lines_before_namespace' => false, // conflicts with `single_blank_line_before_namespace`
'no_break_comment' => ['comment_text' => 'no break'],
'no_closing_tag' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => ['tokens' => ['extra']],
'no_homoglyph_names' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => ['use' => 'echo'],
'no_multiline_whitespace_around_double_arrow' => true,
'no_multiple_statements_per_line' => true,
'no_null_property_initialization' => true,
'no_php4_constructor' => true,
'no_short_bool_cast' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_space_around_double_colon' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => ['positions' => ['inside', 'outside']],
'no_spaces_inside_parenthesis' => true,
'no_superfluous_elseif' => true,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
'allow_unused_params' => true,
'remove_inheritdoc' => false,
],
'no_trailing_comma_in_singleline' => [
'elements' => [
'arguments',
'array_destructuring',
'array',
'group_import',
],
],
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_trailing_whitespace_in_string' => true,
'no_unneeded_control_parentheses' => [
'statements' => [
'break',
'clone',
'continue',
'echo_print',
'return',
'switch_case',
'yield',
],
],
'no_unneeded_curly_braces' => ['namespaces' => true],
'no_unneeded_final_method' => ['private_methods' => true],
'no_unneeded_import_alias' => true,
'no_unreachable_default_argument_value' => true,
'no_unset_cast' => true,
'no_unset_on_property' => false,
'no_unused_imports' => true,
'no_useless_concat_operator' => ['juggle_simple_strings' => true],
'no_useless_else' => true,
'no_useless_nullsafe_operator' => true,
'no_useless_return' => true,
'no_useless_sprintf' => true,
'no_whitespace_before_comma_in_array' => ['after_heredoc' => true],
'no_whitespace_in_blank_line' => true,
'non_printable_character' => ['use_escape_sequences_in_strings' => true],
'normalize_index_brace' => true,
'not_operator_with_space' => false,
'not_operator_with_successor_space' => true,
'nullable_type_declaration_for_default_null_value' => ['use_nullable_type_declaration' => true],
'object_operator_without_whitespace' => true,
'octal_notation' => false, // requires 8.1+
'operator_linebreak' => ['only_booleans' => true, 'position' => 'beginning'],
'ordered_class_elements' => [
'order' => [
'use_trait',
'constant',
'property',
'method',
],
'sort_algorithm' => 'none',
],
'ordered_imports' => [
'sort_algorithm' => 'alpha',
'imports_order' => ['class', 'function', 'const'],
],
'ordered_interfaces' => false,
'ordered_traits' => false,
'php_unit_construct' => [
'assertions' => [
'assertSame',
'assertEquals',
'assertNotEquals',
'assertNotSame',
],
],
'php_unit_dedicate_assert' => ['target' => 'newest'],
'php_unit_dedicate_assert_internal_type' => ['target' => 'newest'],
'php_unit_expectation' => ['target' => 'newest'],
'php_unit_fqcn_annotation' => true,
'php_unit_internal_class' => ['types' => ['normal', 'final']],
'php_unit_method_casing' => ['case' => 'camel_case'],
'php_unit_mock' => ['target' => 'newest'],
'php_unit_mock_short_will_return' => true,
'php_unit_namespaced' => ['target' => 'newest'],
'php_unit_no_expectation_annotation' => [
'target' => 'newest',
'use_class_const' => true,
],
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_size_class' => false,
'php_unit_strict' => [
'assertions' => [
'assertAttributeEquals',
'assertAttributeNotEquals',
'assertEquals',
'assertNotEquals',
],
],
'php_unit_test_annotation' => ['style' => 'prefix'],
'php_unit_test_case_static_method_calls' => [
'call_type' => 'this',
'methods' => [],
],
'php_unit_test_class_requires_covers' => false,
'phpdoc_add_missing_param_annotation' => ['only_untyped' => true],
'phpdoc_align' => [
'align' => 'vertical',
'tags' => [
'method',
'param',
'property',
'return',
'throws',
'type',
'var',
],
],
'phpdoc_annotation_without_dot' => false,
'phpdoc_indent' => true,
'phpdoc_inline_tag_normalizer' => [
'tags' => [
'example',
'id',
'internal',
'inheritdoc',
'inheritdocs',
'link',
'source',
'toc',
'tutorial',
],
],
'phpdoc_line_span' => [
'const' => 'multi',
'method' => 'multi',
'property' => 'multi',
],
'phpdoc_no_access' => true,
'phpdoc_no_alias_tag' => [
'replacements' => [
'property-read' => 'property',
'property-write' => 'property',
'type' => 'var',
'link' => 'see',
],
],
'phpdoc_no_empty_return' => false,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_order' => [
'order' => ['param', 'return', 'throws'],
],
'phpdoc_order_by_value' => [
'annotations' => [
'author',
'covers',
'coversNothing',
'dataProvider',
'depends',
'group',
'internal',
'method',
'property',
'property-read',
'property-write',
'requires',
'throws',
'uses',
],
],
'phpdoc_return_self_reference' => [
'replacements' => [
'this' => '$this',
'@this' => '$this',
'$self' => 'self',
'@self' => 'self',
'$static' => 'static',
'@static' => 'static',
],
],
'phpdoc_scalar' => [
'types' => [
'boolean',
'callback',
'double',
'integer',
'real',
'str',
],
],
'phpdoc_separation' => [
'groups' => [
['immutable', 'psalm-immutable'],
['param', 'phpstan-param', 'psalm-param'],
['phpstan-pure', 'psalm-pure'],
['readonly', 'psalm-readonly'],
['return', 'phpstan-return', 'psalm-return'],
['runTestsInSeparateProcess', 'runInSeparateProcess', 'preserveGlobalState'],
['template', 'phpstan-template', 'psalm-template'],
['template-covariant', 'phpstan-template-covariant', 'psalm-template-covariant'],
['phpstan-type', 'psalm-type'],
['var', 'phpstan-var', 'psalm-var'],
],
],
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => false,
'phpdoc_tag_casing' => ['tags' => ['inheritDoc']],
'phpdoc_tag_type' => ['tags' => ['inheritDoc' => 'inline']],
'phpdoc_to_comment' => false,
'phpdoc_to_param_type' => false,
'phpdoc_to_property_type' => false,
'phpdoc_to_return_type' => false,
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => ['groups' => ['simple', 'alias', 'meta']],
'phpdoc_types_order' => [
'null_adjustment' => 'always_last',
'sort_algorithm' => 'alpha',
],
'phpdoc_var_annotation_correct_order' => true,
'phpdoc_var_without_name' => true,
'pow_to_exponentiation' => true,
'protected_to_private' => true,
'psr_autoloading' => ['dir' => null],
'random_api_migration' => [
'replacements' => [
'getrandmax' => 'mt_getrandmax',
'rand' => 'mt_rand',
'srand' => 'mt_srand',
],
],
'regular_callable_call' => true,
'return_assignment' => true,
'return_type_declaration' => ['space_before' => 'none'],
'self_accessor' => false,
'self_static_accessor' => true,
'semicolon_after_instruction' => false,
'set_type_to_cast' => true,
'short_scalar_cast' => true,
'simple_to_complex_string_variable' => true,
'simplified_if_return' => true,
'simplified_null_return' => false,
'single_blank_line_at_eof' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => ['elements' => ['const', 'property']],
'single_import_per_statement' => ['group_to_single_imports' => true],
'single_line_after_imports' => true,
'single_line_comment_spacing' => true,
'single_line_comment_style' => ['comment_types' => ['asterisk', 'hash']],
'single_line_throw' => false,
'single_quote' => ['strings_containing_single_quote_chars' => false],
'single_space_after_construct' => [
'constructs' => [
'abstract',
'as',
'attribute',
'break',
'case',
'catch',
'class',
'clone',
'comment',
'const',
'const_import',
'continue',
'do',
'echo',
'else',
'elseif',
'extends',
'final',
'finally',
'for',
'foreach',
'function',
'function_import',
'global',
'goto',
'if',
'implements',
'include',
'include_once',
'instanceof',
'insteadof',
'interface',
'match',
'named_argument',
'new',
'open_tag_with_echo',
'php_doc',
'php_open',
'print',
'private',
'protected',
'public',
'require',
'require_once',
'return',
'static',
'throw',
'trait',
'try',
'use',
'use_lambda',
'use_trait',
'var',
'while',
'yield',
'yield_from',
],
],
'single_trait_insert_per_statement' => true,
'space_after_semicolon' => ['remove_in_empty_for_expressions' => true],
'standardize_increment' => true,
'standardize_not_equals' => true,
'statement_indentation' => true,
'static_lambda' => true,
'strict_comparison' => true,
'strict_param' => true,
'string_length_to_empty' => true,
'string_line_ending' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'switch_continue_to_break' => true,
'ternary_operator_spaces' => true,
'ternary_to_elvis_operator' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline' => [
'after_heredoc' => true,
'elements' => ['arrays'],
],
'trim_array_spaces' => true,
'types_spaces' => [
'space' => 'none',
'space_multiple_catch' => 'none',
],
'unary_operator_spaces' => true,
'use_arrow_functions' => true,
'visibility_required' => ['elements' => ['const', 'method', 'property']],
'void_return' => false, // changes method signature
'whitespace_after_comma_in_array' => ['ensure_single_space' => true],
'yoda_style' => [
'equal' => false,
'identical' => null,
'less_and_greater' => false,
'always_move_variable' => false,
],
];
$this->requiredPHPVersion = 70400;
$this->autoActivateIsRiskyAllowed = true;
}
}

View File

@ -1,572 +0,0 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var ?string */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
}
/**
* @return string[]
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param string[]|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param string[]|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
*
* @return self[]
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
* @private
*/
function includeFile($file)
{
include $file;
}

View File

@ -1,350 +0,0 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = require __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;
return $installed;
}
}

View File

@ -1,21 +0,0 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@ -1,20 +0,0 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php',
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'3917c79c5052b270641b5a200963dbc2' => $vendorDir . '/kint-php/kint/init.php',
'ec07570ca5a812141189b1fa81503674' => $vendorDir . '/phpunit/phpunit/src/Framework/Assert/Functions.php',
);

View File

@ -1,10 +0,0 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'org\\bovigo\\vfs\\' => array($vendorDir . '/mikey179/vfsstream/src/main/php'),
);

View File

@ -1,46 +0,0 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php81\\' => array($vendorDir . '/symfony/polyfill-php81'),
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'),
'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'),
'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'),
'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'),
'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Psr\\Cache\\' => array($vendorDir . '/psr/cache/src'),
'Predis\\' => array($vendorDir . '/predis/predis/src'),
'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser'),
'PhpCsFixer\\' => array($vendorDir . '/friendsofphp/php-cs-fixer/src'),
'Nexus\\CsConfig\\' => array($vendorDir . '/nexusphp/cs-config/src'),
'Laminas\\Escaper\\' => array($vendorDir . '/laminas/laminas-escaper/src'),
'Kint\\' => array($vendorDir . '/kint-php/kint/src'),
'Faker\\' => array($vendorDir . '/fakerphp/faker/src/Faker'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'Doctrine\\Deprecations\\' => array($vendorDir . '/doctrine/deprecations/lib/Doctrine/Deprecations'),
'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/src'),
'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations'),
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'),
'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'),
'Composer\\Pcre\\' => array($vendorDir . '/composer/pcre/src'),
'CodeIgniter\\CodingStandard\\' => array($vendorDir . '/codeigniter/coding-standard/src'),
'CodeIgniter\\' => array($baseDir . '/system'),
);

View File

@ -1,80 +0,0 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit01bb8cdaddb35dba667c1b3b51c53f89
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit01bb8cdaddb35dba667c1b3b51c53f89', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__)));
spl_autoload_unregister(array('ComposerAutoloaderInit01bb8cdaddb35dba667c1b3b51c53f89', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit01bb8cdaddb35dba667c1b3b51c53f89::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit01bb8cdaddb35dba667c1b3b51c53f89::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire01bb8cdaddb35dba667c1b3b51c53f89($fileIdentifier, $file);
}
return $loader;
}
}
/**
* @param string $fileIdentifier
* @param string $file
* @return void
*/
function composerRequire01bb8cdaddb35dba667c1b3b51c53f89($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,608 +0,0 @@
<?php return array(
'root' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'name' => 'codeigniter4/framework',
'dev' => true,
),
'versions' => array(
'codeigniter/coding-standard' => array(
'pretty_version' => 'v1.7.1',
'version' => '1.7.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../codeigniter/coding-standard',
'aliases' => array(),
'reference' => '9b3a18ebd635e05717e984d40cc2f888afa52683',
'dev_requirement' => true,
),
'codeigniter4/framework' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'dev_requirement' => false,
),
'composer/pcre' => array(
'pretty_version' => '3.1.0',
'version' => '3.1.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/./pcre',
'aliases' => array(),
'reference' => '4bff79ddd77851fe3cdd11616ed3f92841ba5bd2',
'dev_requirement' => true,
),
'composer/semver' => array(
'pretty_version' => '3.3.2',
'version' => '3.3.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/./semver',
'aliases' => array(),
'reference' => '3953f23262f2bff1919fc82183ad9acb13ff62c9',
'dev_requirement' => true,
),
'composer/xdebug-handler' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/./xdebug-handler',
'aliases' => array(),
'reference' => 'ced299686f41dce890debac69273b47ffe98a40c',
'dev_requirement' => true,
),
'doctrine/annotations' => array(
'pretty_version' => '1.14.3',
'version' => '1.14.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../doctrine/annotations',
'aliases' => array(),
'reference' => 'fb0d71a7393298a7b232cbf4c8b1f73f3ec3d5af',
'dev_requirement' => true,
),
'doctrine/deprecations' => array(
'pretty_version' => 'v1.1.1',
'version' => '1.1.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../doctrine/deprecations',
'aliases' => array(),
'reference' => '612a3ee5ab0d5dd97b7cf3874a6efe24325efac3',
'dev_requirement' => true,
),
'doctrine/instantiator' => array(
'pretty_version' => '2.0.0',
'version' => '2.0.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../doctrine/instantiator',
'aliases' => array(),
'reference' => 'c6222283fa3f4ac679f8b9ced9a4e23f163e80d0',
'dev_requirement' => true,
),
'doctrine/lexer' => array(
'pretty_version' => '2.1.0',
'version' => '2.1.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../doctrine/lexer',
'aliases' => array(),
'reference' => '39ab8fcf5a51ce4b85ca97c7a7d033eb12831124',
'dev_requirement' => true,
),
'fakerphp/faker' => array(
'pretty_version' => 'v1.23.0',
'version' => '1.23.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../fakerphp/faker',
'aliases' => array(),
'reference' => 'e3daa170d00fde61ea7719ef47bb09bb8f1d9b01',
'dev_requirement' => true,
),
'friendsofphp/php-cs-fixer' => array(
'pretty_version' => 'v3.13.0',
'version' => '3.13.0.0',
'type' => 'application',
'install_path' => __DIR__ . '/../friendsofphp/php-cs-fixer',
'aliases' => array(),
'reference' => 'a6232229a8309e8811dc751c28b91cb34b2943e1',
'dev_requirement' => true,
),
'kint-php/kint' => array(
'pretty_version' => '5.0.7',
'version' => '5.0.7.0',
'type' => 'library',
'install_path' => __DIR__ . '/../kint-php/kint',
'aliases' => array(),
'reference' => 'a700653a77250b122920799b10c94e904c9b78c7',
'dev_requirement' => true,
),
'laminas/laminas-escaper' => array(
'pretty_version' => '2.12.0',
'version' => '2.12.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../laminas/laminas-escaper',
'aliases' => array(),
'reference' => 'ee7a4c37bf3d0e8c03635d5bddb5bb3184ead490',
'dev_requirement' => false,
),
'mikey179/vfsstream' => array(
'pretty_version' => 'v1.6.11',
'version' => '1.6.11.0',
'type' => 'library',
'install_path' => __DIR__ . '/../mikey179/vfsstream',
'aliases' => array(),
'reference' => '17d16a85e6c26ce1f3e2fa9ceeacdc2855db1e9f',
'dev_requirement' => true,
),
'myclabs/deep-copy' => array(
'pretty_version' => '1.11.1',
'version' => '1.11.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../myclabs/deep-copy',
'aliases' => array(),
'reference' => '7284c22080590fb39f2ffa3e9057f10a4ddd0e0c',
'dev_requirement' => true,
),
'nexusphp/cs-config' => array(
'pretty_version' => 'v3.8.0',
'version' => '3.8.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../nexusphp/cs-config',
'aliases' => array(),
'reference' => '8ef2d10694d0dfadb1fc028c9b5de07c8e852092',
'dev_requirement' => true,
),
'nikic/php-parser' => array(
'pretty_version' => 'v4.17.1',
'version' => '4.17.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../nikic/php-parser',
'aliases' => array(),
'reference' => 'a6303e50c90c355c7eeee2c4a8b27fe8dc8fef1d',
'dev_requirement' => true,
),
'phar-io/manifest' => array(
'pretty_version' => '2.0.3',
'version' => '2.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phar-io/manifest',
'aliases' => array(),
'reference' => '97803eca37d319dfa7826cc2437fc020857acb53',
'dev_requirement' => true,
),
'phar-io/version' => array(
'pretty_version' => '3.2.1',
'version' => '3.2.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phar-io/version',
'aliases' => array(),
'reference' => '4f7fd7836c6f332bb2933569e566a0d6c4cbed74',
'dev_requirement' => true,
),
'phpunit/php-code-coverage' => array(
'pretty_version' => '9.2.27',
'version' => '9.2.27.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-code-coverage',
'aliases' => array(),
'reference' => 'b0a88255cb70d52653d80c890bd7f38740ea50d1',
'dev_requirement' => true,
),
'phpunit/php-file-iterator' => array(
'pretty_version' => '3.0.6',
'version' => '3.0.6.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-file-iterator',
'aliases' => array(),
'reference' => 'cf1c2e7c203ac650e352f4cc675a7021e7d1b3cf',
'dev_requirement' => true,
),
'phpunit/php-invoker' => array(
'pretty_version' => '3.1.1',
'version' => '3.1.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-invoker',
'aliases' => array(),
'reference' => '5a10147d0aaf65b58940a0b72f71c9ac0423cc67',
'dev_requirement' => true,
),
'phpunit/php-text-template' => array(
'pretty_version' => '2.0.4',
'version' => '2.0.4.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-text-template',
'aliases' => array(),
'reference' => '5da5f67fc95621df9ff4c4e5a84d6a8a2acf7c28',
'dev_requirement' => true,
),
'phpunit/php-timer' => array(
'pretty_version' => '5.0.3',
'version' => '5.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-timer',
'aliases' => array(),
'reference' => '5a63ce20ed1b5bf577850e2c4e87f4aa902afbd2',
'dev_requirement' => true,
),
'phpunit/phpunit' => array(
'pretty_version' => '9.6.10',
'version' => '9.6.10.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/phpunit',
'aliases' => array(),
'reference' => 'a6d351645c3fe5a30f5e86be6577d946af65a328',
'dev_requirement' => true,
),
'predis/predis' => array(
'pretty_version' => 'v2.2.1',
'version' => '2.2.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../predis/predis',
'aliases' => array(),
'reference' => '5f2b410a74afaff296a87a494e4c5488cf9fab57',
'dev_requirement' => true,
),
'psr/cache' => array(
'pretty_version' => '3.0.0',
'version' => '3.0.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/cache',
'aliases' => array(),
'reference' => 'aa5030cfa5405eccfdcb1083ce040c2cb8d253bf',
'dev_requirement' => true,
),
'psr/container' => array(
'pretty_version' => '2.0.2',
'version' => '2.0.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/container',
'aliases' => array(),
'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963',
'dev_requirement' => true,
),
'psr/event-dispatcher' => array(
'pretty_version' => '1.0.0',
'version' => '1.0.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/event-dispatcher',
'aliases' => array(),
'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0',
'dev_requirement' => true,
),
'psr/event-dispatcher-implementation' => array(
'dev_requirement' => true,
'provided' => array(
0 => '1.0',
),
),
'psr/log' => array(
'pretty_version' => '1.1.4',
'version' => '1.1.4.0',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/log',
'aliases' => array(),
'reference' => 'd49695b909c3b7628b6289db5479a1c204601f11',
'dev_requirement' => false,
),
'psr/log-implementation' => array(
'dev_requirement' => true,
'provided' => array(
0 => '1.0|2.0|3.0',
),
),
'sebastian/cli-parser' => array(
'pretty_version' => '1.0.1',
'version' => '1.0.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/cli-parser',
'aliases' => array(),
'reference' => '442e7c7e687e42adc03470c7b668bc4b2402c0b2',
'dev_requirement' => true,
),
'sebastian/code-unit' => array(
'pretty_version' => '1.0.8',
'version' => '1.0.8.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/code-unit',
'aliases' => array(),
'reference' => '1fc9f64c0927627ef78ba436c9b17d967e68e120',
'dev_requirement' => true,
),
'sebastian/code-unit-reverse-lookup' => array(
'pretty_version' => '2.0.3',
'version' => '2.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/code-unit-reverse-lookup',
'aliases' => array(),
'reference' => 'ac91f01ccec49fb77bdc6fd1e548bc70f7faa3e5',
'dev_requirement' => true,
),
'sebastian/comparator' => array(
'pretty_version' => '4.0.8',
'version' => '4.0.8.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/comparator',
'aliases' => array(),
'reference' => 'fa0f136dd2334583309d32b62544682ee972b51a',
'dev_requirement' => true,
),
'sebastian/complexity' => array(
'pretty_version' => '2.0.2',
'version' => '2.0.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/complexity',
'aliases' => array(),
'reference' => '739b35e53379900cc9ac327b2147867b8b6efd88',
'dev_requirement' => true,
),
'sebastian/diff' => array(
'pretty_version' => '4.0.5',
'version' => '4.0.5.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/diff',
'aliases' => array(),
'reference' => '74be17022044ebaaecfdf0c5cd504fc9cd5a7131',
'dev_requirement' => true,
),
'sebastian/environment' => array(
'pretty_version' => '5.1.5',
'version' => '5.1.5.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/environment',
'aliases' => array(),
'reference' => '830c43a844f1f8d5b7a1f6d6076b784454d8b7ed',
'dev_requirement' => true,
),
'sebastian/exporter' => array(
'pretty_version' => '4.0.5',
'version' => '4.0.5.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/exporter',
'aliases' => array(),
'reference' => 'ac230ed27f0f98f597c8a2b6eb7ac563af5e5b9d',
'dev_requirement' => true,
),
'sebastian/global-state' => array(
'pretty_version' => '5.0.6',
'version' => '5.0.6.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/global-state',
'aliases' => array(),
'reference' => 'bde739e7565280bda77be70044ac1047bc007e34',
'dev_requirement' => true,
),
'sebastian/lines-of-code' => array(
'pretty_version' => '1.0.3',
'version' => '1.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/lines-of-code',
'aliases' => array(),
'reference' => 'c1c2e997aa3146983ed888ad08b15470a2e22ecc',
'dev_requirement' => true,
),
'sebastian/object-enumerator' => array(
'pretty_version' => '4.0.4',
'version' => '4.0.4.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/object-enumerator',
'aliases' => array(),
'reference' => '5c9eeac41b290a3712d88851518825ad78f45c71',
'dev_requirement' => true,
),
'sebastian/object-reflector' => array(
'pretty_version' => '2.0.4',
'version' => '2.0.4.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/object-reflector',
'aliases' => array(),
'reference' => 'b4f479ebdbf63ac605d183ece17d8d7fe49c15c7',
'dev_requirement' => true,
),
'sebastian/recursion-context' => array(
'pretty_version' => '4.0.5',
'version' => '4.0.5.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/recursion-context',
'aliases' => array(),
'reference' => 'e75bd0f07204fec2a0af9b0f3cfe97d05f92efc1',
'dev_requirement' => true,
),
'sebastian/resource-operations' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/resource-operations',
'aliases' => array(),
'reference' => '0f4443cb3a1d92ce809899753bc0d5d5a8dd19a8',
'dev_requirement' => true,
),
'sebastian/type' => array(
'pretty_version' => '3.2.1',
'version' => '3.2.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/type',
'aliases' => array(),
'reference' => '75e2c2a32f5e0b3aef905b9ed0b179b953b3d7c7',
'dev_requirement' => true,
),
'sebastian/version' => array(
'pretty_version' => '3.0.2',
'version' => '3.0.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/version',
'aliases' => array(),
'reference' => 'c6c1022351a901512170118436c764e473f6de8c',
'dev_requirement' => true,
),
'symfony/console' => array(
'pretty_version' => 'v6.3.2',
'version' => '6.3.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/console',
'aliases' => array(),
'reference' => 'aa5d64ad3f63f2e48964fc81ee45cb318a723898',
'dev_requirement' => true,
),
'symfony/deprecation-contracts' => array(
'pretty_version' => 'v3.3.0',
'version' => '3.3.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
'aliases' => array(),
'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf',
'dev_requirement' => true,
),
'symfony/event-dispatcher' => array(
'pretty_version' => 'v6.3.2',
'version' => '6.3.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/event-dispatcher',
'aliases' => array(),
'reference' => 'adb01fe097a4ee930db9258a3cc906b5beb5cf2e',
'dev_requirement' => true,
),
'symfony/event-dispatcher-contracts' => array(
'pretty_version' => 'v3.3.0',
'version' => '3.3.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/event-dispatcher-contracts',
'aliases' => array(),
'reference' => 'a76aed96a42d2b521153fb382d418e30d18b59df',
'dev_requirement' => true,
),
'symfony/event-dispatcher-implementation' => array(
'dev_requirement' => true,
'provided' => array(
0 => '2.0|3.0',
),
),
'symfony/filesystem' => array(
'pretty_version' => 'v6.3.1',
'version' => '6.3.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/filesystem',
'aliases' => array(),
'reference' => 'edd36776956f2a6fcf577edb5b05eb0e3bdc52ae',
'dev_requirement' => true,
),
'symfony/finder' => array(
'pretty_version' => 'v6.3.3',
'version' => '6.3.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/finder',
'aliases' => array(),
'reference' => '9915db259f67d21eefee768c1abcf1cc61b1fc9e',
'dev_requirement' => true,
),
'symfony/options-resolver' => array(
'pretty_version' => 'v6.3.0',
'version' => '6.3.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/options-resolver',
'aliases' => array(),
'reference' => 'a10f19f5198d589d5c33333cffe98dc9820332dd',
'dev_requirement' => true,
),
'symfony/polyfill-ctype' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
'aliases' => array(),
'reference' => '5bbc823adecdae860bb64756d639ecfec17b050a',
'dev_requirement' => true,
),
'symfony/polyfill-intl-grapheme' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-intl-grapheme',
'aliases' => array(),
'reference' => '511a08c03c1960e08a883f4cffcacd219b758354',
'dev_requirement' => true,
),
'symfony/polyfill-intl-normalizer' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-intl-normalizer',
'aliases' => array(),
'reference' => '19bd1e4fcd5b91116f14d8533c57831ed00571b6',
'dev_requirement' => true,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'reference' => '8ad114f6b39e2c98a8b0e3bd907732c207c2b534',
'dev_requirement' => true,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'reference' => '7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936',
'dev_requirement' => true,
),
'symfony/polyfill-php81' => array(
'pretty_version' => 'v1.27.0',
'version' => '1.27.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php81',
'aliases' => array(),
'reference' => '707403074c8ea6e2edaf8794b0157a0bfa52157a',
'dev_requirement' => true,
),
'symfony/process' => array(
'pretty_version' => 'v6.3.2',
'version' => '6.3.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/process',
'aliases' => array(),
'reference' => 'c5ce962db0d9b6e80247ca5eb9af6472bd4d7b5d',
'dev_requirement' => true,
),
'symfony/service-contracts' => array(
'pretty_version' => 'v3.3.0',
'version' => '3.3.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/service-contracts',
'aliases' => array(),
'reference' => '40da9cc13ec349d9e4966ce18b5fbcd724ab10a4',
'dev_requirement' => true,
),
'symfony/stopwatch' => array(
'pretty_version' => 'v6.3.0',
'version' => '6.3.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/stopwatch',
'aliases' => array(),
'reference' => 'fc47f1015ec80927ff64ba9094dfe8b9d48fe9f2',
'dev_requirement' => true,
),
'symfony/string' => array(
'pretty_version' => 'v6.3.2',
'version' => '6.3.2.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/string',
'aliases' => array(),
'reference' => '53d1a83225002635bca3482fcbf963001313fb68',
'dev_requirement' => true,
),
'theseer/tokenizer' => array(
'pretty_version' => '1.2.1',
'version' => '1.2.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../theseer/tokenizer',
'aliases' => array(),
'reference' => '34a41e998c2183e22995f158c581e7b5e755ab9e',
'dev_requirement' => true,
),
),
);

View File

@ -1,19 +0,0 @@
Copyright (C) 2021 Composer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,181 +0,0 @@
composer/pcre
=============
PCRE wrapping library that offers type-safe `preg_*` replacements.
This library gives you a way to ensure `preg_*` functions do not fail silently, returning
unexpected `null`s that may not be handled.
As of 3.0 this library enforces [`PREG_UNMATCHED_AS_NULL`](#preg_unmatched_as_null) usage
for all matching and replaceCallback functions, [read more below](#preg_unmatched_as_null)
to understand the implications.
It thus makes it easier to work with static analysis tools like PHPStan or Psalm as it
simplifies and reduces the possible return values from all the `preg_*` functions which
are quite packed with edge cases.
This library is a thin wrapper around `preg_*` functions with [some limitations](#restrictions--limitations).
If you are looking for a richer API to handle regular expressions have a look at
[rawr/t-regx](https://packagist.org/packages/rawr/t-regx) instead.
[![Continuous Integration](https://github.com/composer/pcre/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/pcre/actions)
Installation
------------
Install the latest version with:
```bash
$ composer require composer/pcre
```
Requirements
------------
* PHP 7.4.0 is required for 3.x versions
* PHP 7.2.0 is required for 2.x versions
* PHP 5.3.2 is required for 1.x versions
Basic usage
-----------
Instead of:
```php
if (preg_match('{fo+}', $string, $matches)) { ... }
if (preg_match('{fo+}', $string, $matches, PREG_OFFSET_CAPTURE)) { ... }
if (preg_match_all('{fo+}', $string, $matches)) { ... }
$newString = preg_replace('{fo+}', 'bar', $string);
$newString = preg_replace_callback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string);
$newString = preg_replace_callback_array(['{fo+}' => fn ($match) => strtoupper($match[0])], $string);
$filtered = preg_grep('{[a-z]}', $elements);
$array = preg_split('{[a-z]+}', $string);
```
You can now call these on the `Preg` class:
```php
use Composer\Pcre\Preg;
if (Preg::match('{fo+}', $string, $matches)) { ... }
if (Preg::matchWithOffsets('{fo+}', $string, $matches)) { ... }
if (Preg::matchAll('{fo+}', $string, $matches)) { ... }
$newString = Preg::replace('{fo+}', 'bar', $string);
$newString = Preg::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string);
$newString = Preg::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string);
$filtered = Preg::grep('{[a-z]}', $elements);
$array = Preg::split('{[a-z]+}', $string);
```
The main difference is if anything fails to match/replace/.., it will throw a `Composer\Pcre\PcreException`
instead of returning `null` (or false in some cases), so you can now use the return values safely relying on
the fact that they can only be strings (for replace), ints (for match) or arrays (for grep/split).
Additionally the `Preg` class provides match methods that return `bool` rather than `int`, for stricter type safety
when the number of pattern matches is not useful:
```php
use Composer\Pcre\Preg;
if (Preg::isMatch('{fo+}', $string, $matches)) // bool
if (Preg::isMatchAll('{fo+}', $string, $matches)) // bool
```
Finally the `Preg` class provides a few `*StrictGroups` method variants that ensure match groups
are always present and thus non-nullable, making it easier to write type-safe code:
```php
use Composer\Pcre\Preg;
// $matches is guaranteed to be an array of strings, if a subpattern does not match and produces a null it will throw
if (Preg::matchStrictGroups('{fo+}', $string, $matches))
if (Preg::matchAllStrictGroups('{fo+}', $string, $matches))
```
**Note:** This is generally safe to use as long as you do not have optional subpatterns (i.e. `(something)?`
or `(something)*` or branches with a `|` that result in some groups not being matched at all).
A subpattern that can match an empty string like `(.*)` is **not** optional, it will be present as an
empty string in the matches. A non-matching subpattern, even if optional like `(?:foo)?` will anyway not be present in
matches so it is also not a problem to use these with `*StrictGroups` methods.
If you would prefer a slightly more verbose usage, replacing by-ref arguments by result objects, you can use the `Regex` class:
```php
use Composer\Pcre\Regex;
// this is useful when you are just interested in knowing if something matched
// as it returns a bool instead of int(1/0) for match
$bool = Regex::isMatch('{fo+}', $string);
$result = Regex::match('{fo+}', $string);
if ($result->matched) { something($result->matches); }
$result = Regex::matchWithOffsets('{fo+}', $string);
if ($result->matched) { something($result->matches); }
$result = Regex::matchAll('{fo+}', $string);
if ($result->matched && $result->count > 3) { something($result->matches); }
$newString = Regex::replace('{fo+}', 'bar', $string)->result;
$newString = Regex::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string)->result;
$newString = Regex::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string)->result;
```
Note that `preg_grep` and `preg_split` are only callable via the `Preg` class as they do not have
complex return types warranting a specific result object.
See the [MatchResult](src/MatchResult.php), [MatchWithOffsetsResult](src/MatchWithOffsetsResult.php), [MatchAllResult](src/MatchAllResult.php),
[MatchAllWithOffsetsResult](src/MatchAllWithOffsetsResult.php), and [ReplaceResult](src/ReplaceResult.php) class sources for more details.
Restrictions / Limitations
--------------------------
Due to type safety requirements a few restrictions are in place.
- matching using `PREG_OFFSET_CAPTURE` is made available via `matchWithOffsets` and `matchAllWithOffsets`.
You cannot pass the flag to `match`/`matchAll`.
- `Preg::split` will also reject `PREG_SPLIT_OFFSET_CAPTURE` and you should use `splitWithOffsets`
instead.
- `matchAll` rejects `PREG_SET_ORDER` as it also changes the shape of the returned matches. There
is no alternative provided as you can fairly easily code around it.
- `preg_filter` is not supported as it has a rather crazy API, most likely you should rather
use `Preg::grep` in combination with some loop and `Preg::replace`.
- `replace`, `replaceCallback` and `replaceCallbackArray` do not support an array `$subject`,
only simple strings.
- As of 2.0, the library always uses `PREG_UNMATCHED_AS_NULL` for matching, which offers [much
saner/more predictable results](#preg_unmatched_as_null). As of 3.0 the flag is also set for
`replaceCallback` and `replaceCallbackArray`.
#### PREG_UNMATCHED_AS_NULL
As of 2.0, this library always uses PREG_UNMATCHED_AS_NULL for all `match*` and `isMatch*`
functions. As of 3.0 it is also done for `replaceCallback` and `replaceCallbackArray`.
This means your matches will always contain all matching groups, either as null if unmatched
or as string if it matched.
The advantages in clarity and predictability are clearer if you compare the two outputs of
running this with and without PREG_UNMATCHED_AS_NULL in $flags:
```php
preg_match('/(a)(b)*(c)(d)*/', 'ac', $matches, $flags);
```
| no flag | PREG_UNMATCHED_AS_NULL |
| --- | --- |
| array (size=4) | array (size=5) |
| 0 => string 'ac' (length=2) | 0 => string 'ac' (length=2) |
| 1 => string 'a' (length=1) | 1 => string 'a' (length=1) |
| 2 => string '' (length=0) | 2 => null |
| 3 => string 'c' (length=1) | 3 => string 'c' (length=1) |
| | 4 => null |
| group 2 (any unmatched group preceding one that matched) is set to `''`. You cannot tell if it matched an empty string or did not match at all | group 2 is `null` when unmatched and a string if it matched, easy to check for |
| group 4 (any optional group without a matching one following) is missing altogether. So you have to check with `isset()`, but really you want `isset($m[4]) && $m[4] !== ''` for safety unless you are very careful to check that a non-optional group follows it | group 4 is always set, and null in this case as there was no match, easy to check for with `$m[4] !== null` |
License
-------
composer/pcre is licensed under the MIT License, see the LICENSE file for details.

View File

@ -1,46 +0,0 @@
{
"name": "composer/pcre",
"description": "PCRE wrapping library that offers type-safe preg_* replacements.",
"type": "library",
"license": "MIT",
"keywords": [
"pcre",
"regex",
"preg",
"regular expression"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"require": {
"php": "^7.4 || ^8.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^5",
"phpstan/phpstan": "^1.3",
"phpstan/phpstan-strict-rules": "^1.1"
},
"autoload": {
"psr-4": {
"Composer\\Pcre\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Composer\\Pcre\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"scripts": {
"test": "vendor/bin/simple-phpunit",
"phpstan": "phpstan analyse"
}
}

View File

@ -1,46 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchAllResult
{
/**
* An array of match group => list of matched strings
*
* @readonly
* @var array<int|string, list<string|null>>
*/
public $matches;
/**
* @readonly
* @var 0|positive-int
*/
public $count;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<int|string, array<string|null>> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
$this->count = $count;
}
}

View File

@ -1,46 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchAllStrictGroupsResult
{
/**
* An array of match group => list of matched strings
*
* @readonly
* @var array<int|string, list<string>>
*/
public $matches;
/**
* @readonly
* @var 0|positive-int
*/
public $count;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<array<string>> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
$this->count = $count;
}
}

View File

@ -1,48 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchAllWithOffsetsResult
{
/**
* An array of match group => list of matches, every match being a pair of string matched + offset in bytes (or -1 if no match)
*
* @readonly
* @var array<int|string, list<array{string|null, int}>>
* @phpstan-var array<int|string, list<array{string|null, int<-1, max>}>>
*/
public $matches;
/**
* @readonly
* @var 0|positive-int
*/
public $count;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<int|string, list<array{string|null, int}>> $matches
* @phpstan-param array<int|string, list<array{string|null, int<-1, max>}>> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
$this->count = $count;
}
}

View File

@ -1,39 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchResult
{
/**
* An array of match group => string matched
*
* @readonly
* @var array<int|string, string|null>
*/
public $matches;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<string|null> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
}
}

View File

@ -1,39 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchStrictGroupsResult
{
/**
* An array of match group => string matched
*
* @readonly
* @var array<int|string, string>
*/
public $matches;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<string> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
}
}

View File

@ -1,41 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class MatchWithOffsetsResult
{
/**
* An array of match group => pair of string matched + offset in bytes (or -1 if no match)
*
* @readonly
* @var array<int|string, array{string|null, int}>
* @phpstan-var array<int|string, array{string|null, int<-1, max>}>
*/
public $matches;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
* @param array<array{string|null, int}> $matches
* @phpstan-param array<int|string, array{string|null, int<-1, max>}> $matches
*/
public function __construct(int $count, array $matches)
{
$this->matches = $matches;
$this->matched = (bool) $count;
}
}

View File

@ -1,60 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
class PcreException extends \RuntimeException
{
/**
* @param string $function
* @param string|string[] $pattern
* @return self
*/
public static function fromFunction($function, $pattern)
{
$code = preg_last_error();
if (is_array($pattern)) {
$pattern = implode(', ', $pattern);
}
return new PcreException($function.'(): failed executing "'.$pattern.'": '.self::pcreLastErrorMessage($code), $code);
}
/**
* @param int $code
* @return string
*/
private static function pcreLastErrorMessage($code)
{
if (function_exists('preg_last_error_msg')) {
return preg_last_error_msg();
}
// older php versions did not set the code properly in all cases
if (PHP_VERSION_ID < 70201 && $code === 0) {
return 'UNDEFINED_ERROR';
}
$constants = get_defined_constants(true);
if (!isset($constants['pcre'])) {
return 'UNDEFINED_ERROR';
}
foreach ($constants['pcre'] as $const => $val) {
if ($val === $code && substr($const, -6) === '_ERROR') {
return $const;
}
}
return 'UNDEFINED_ERROR';
}
}

View File

@ -1,428 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
class Preg
{
/** @internal */
public const ARRAY_MSG = '$subject as an array is not supported. You can use \'foreach\' instead.';
/** @internal */
public const INVALID_TYPE_MSG = '$subject must be a string, %s given.';
/**
* @param non-empty-string $pattern
* @param array<string|null> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @return 0|1
*
* @param-out array<int|string, string|null> $matches
*/
public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
{
self::checkOffsetCapture($flags, 'matchWithOffsets');
$result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset);
if ($result === false) {
throw PcreException::fromFunction('preg_match', $pattern);
}
return $result;
}
/**
* Variant of `match()` which outputs non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param array<string> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @return 0|1
* @throws UnexpectedNullMatchException
*
* @param-out array<int|string, string> $matches
*/
public static function matchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
{
$result = self::match($pattern, $subject, $matchesInternal, $flags, $offset);
$matches = self::enforceNonNullMatches($pattern, $matchesInternal, 'match');
return $result;
}
/**
* Runs preg_match with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param array<int|string, array{string|null, int}> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_UNMATCHED_AS_NULL and PREG_OFFSET_CAPTURE are always set, no other flags are supported
* @return 0|1
*
* @param-out array<int|string, array{string|null, int<-1, max>}> $matches
*/
public static function matchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int
{
$result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset);
if ($result === false) {
throw PcreException::fromFunction('preg_match', $pattern);
}
return $result;
}
/**
* @param non-empty-string $pattern
* @param array<int|string, list<string|null>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @return 0|positive-int
*
* @param-out array<int|string, list<string|null>> $matches
*/
public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
{
self::checkOffsetCapture($flags, 'matchAllWithOffsets');
self::checkSetOrder($flags);
$result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset);
if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false
throw PcreException::fromFunction('preg_match_all', $pattern);
}
return $result;
}
/**
* Variant of `match()` which outputs non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param array<int|string, list<string|null>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @return 0|positive-int
* @throws UnexpectedNullMatchException
*
* @param-out array<int|string, list<string>> $matches
*/
public static function matchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
{
$result = self::matchAll($pattern, $subject, $matchesInternal, $flags, $offset);
$matches = self::enforceNonNullMatchAll($pattern, $matchesInternal, 'matchAll');
return $result;
}
/**
* Runs preg_match_all with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param array<int|string, list<array{string|null, int}>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported
* @return 0|positive-int
*
* @phpstan-param array<int|string, list<array{string|null, int<-1, max>}>> $matches
*/
public static function matchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int
{
self::checkSetOrder($flags);
$result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset);
if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false
throw PcreException::fromFunction('preg_match_all', $pattern);
}
return $result;
}
/**
* @param string|string[] $pattern
* @param string|string[] $replacement
* @param string $subject
* @param int $count Set by method
*
* @param-out int<0, max> $count
*/
public static function replace($pattern, $replacement, $subject, int $limit = -1, int &$count = null): string
{
if (!is_scalar($subject)) {
if (is_array($subject)) {
throw new \InvalidArgumentException(static::ARRAY_MSG);
}
throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject)));
}
$result = preg_replace($pattern, $replacement, $subject, $limit, $count);
if ($result === null) {
throw PcreException::fromFunction('preg_replace', $pattern);
}
return $result;
}
/**
* @param string|string[] $pattern
* @param callable(array<int|string, string|null>): string $replacement
* @param string $subject
* @param int $count Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set
*
* @param-out int<0, max> $count
*/
public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0): string
{
if (!is_scalar($subject)) {
if (is_array($subject)) {
throw new \InvalidArgumentException(static::ARRAY_MSG);
}
throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject)));
}
$result = preg_replace_callback($pattern, $replacement, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL);
if ($result === null) {
throw PcreException::fromFunction('preg_replace_callback', $pattern);
}
return $result;
}
/**
* Variant of `replaceCallback()` which outputs non-null matches (or throws)
*
* @param string $pattern
* @param callable(array<int|string, string>): string $replacement
* @param string $subject
* @param int $count Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+
*
* @param-out int<0, max> $count
*/
public static function replaceCallbackStrictGroups(string $pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0): string
{
return self::replaceCallback($pattern, function (array $matches) use ($pattern, $replacement) {
return $replacement(self::enforceNonNullMatches($pattern, $matches, 'replaceCallback'));
}, $subject, $limit, $count, $flags);
}
/**
* @param array<string, callable(array<int|string, string|null>): string> $pattern
* @param string $subject
* @param int $count Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set
*
* @param-out int<0, max> $count
*/
public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int &$count = null, int $flags = 0): string
{
if (!is_scalar($subject)) {
if (is_array($subject)) {
throw new \InvalidArgumentException(static::ARRAY_MSG);
}
throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject)));
}
$result = preg_replace_callback_array($pattern, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL);
if ($result === null) {
$pattern = array_keys($pattern);
throw PcreException::fromFunction('preg_replace_callback_array', $pattern);
}
return $result;
}
/**
* @param int-mask<PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_OFFSET_CAPTURE> $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE
* @return list<string>
*/
public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array
{
if (($flags & PREG_SPLIT_OFFSET_CAPTURE) !== 0) {
throw new \InvalidArgumentException('PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffsets() instead');
}
$result = preg_split($pattern, $subject, $limit, $flags);
if ($result === false) {
throw PcreException::fromFunction('preg_split', $pattern);
}
return $result;
}
/**
* @param int-mask<PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_OFFSET_CAPTURE> $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE is always set
* @return list<array{string, int}>
* @phpstan-return list<array{string, int<0, max>}>
*/
public static function splitWithOffsets(string $pattern, string $subject, int $limit = -1, int $flags = 0): array
{
$result = preg_split($pattern, $subject, $limit, $flags | PREG_SPLIT_OFFSET_CAPTURE);
if ($result === false) {
throw PcreException::fromFunction('preg_split', $pattern);
}
return $result;
}
/**
* @template T of string|\Stringable
* @param string $pattern
* @param array<T> $array
* @param int-mask<PREG_GREP_INVERT> $flags PREG_GREP_INVERT
* @return array<T>
*/
public static function grep(string $pattern, array $array, int $flags = 0): array
{
$result = preg_grep($pattern, $array, $flags);
if ($result === false) {
throw PcreException::fromFunction('preg_grep', $pattern);
}
return $result;
}
/**
* Variant of match() which returns a bool instead of int
*
* @param non-empty-string $pattern
* @param array<string|null> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*
* @param-out array<int|string, string|null> $matches
*/
public static function isMatch(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool
{
return (bool) static::match($pattern, $subject, $matches, $flags, $offset);
}
/**
* Variant of `isMatch()` which outputs non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param array<string> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @throws UnexpectedNullMatchException
*
* @param-out array<int|string, string> $matches
*/
public static function isMatchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool
{
return (bool) self::matchStrictGroups($pattern, $subject, $matches, $flags, $offset);
}
/**
* Variant of matchAll() which returns a bool instead of int
*
* @param non-empty-string $pattern
* @param array<int|string, list<string|null>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*
* @param-out array<int|string, list<string|null>> $matches
*/
public static function isMatchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool
{
return (bool) static::matchAll($pattern, $subject, $matches, $flags, $offset);
}
/**
* Variant of `isMatchAll()` which outputs non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param array<int|string, list<string>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*
* @param-out array<int|string, list<string>> $matches
*/
public static function isMatchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool
{
return (bool) self::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset);
}
/**
* Variant of matchWithOffsets() which returns a bool instead of int
*
* Runs preg_match with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param array<int|string, array{string|null, int}> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*
* @param-out array<int|string, array{string|null, int<-1, max>}> $matches
*/
public static function isMatchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool
{
return (bool) static::matchWithOffsets($pattern, $subject, $matches, $flags, $offset);
}
/**
* Variant of matchAllWithOffsets() which returns a bool instead of int
*
* Runs preg_match_all with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param array<int|string, list<array{string|null, int}>> $matches Set by method
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*
* @param-out array<int|string, list<array{string|null, int<-1, max>}>> $matches
*/
public static function isMatchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool
{
return (bool) static::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset);
}
private static function checkOffsetCapture(int $flags, string $useFunctionName): void
{
if (($flags & PREG_OFFSET_CAPTURE) !== 0) {
throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the type of $matches, use ' . $useFunctionName . '() instead');
}
}
private static function checkSetOrder(int $flags): void
{
if (($flags & PREG_SET_ORDER) !== 0) {
throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the type of $matches');
}
}
/**
* @param array<int|string, string|null> $matches
* @return array<int|string, string>
* @throws UnexpectedNullMatchException
*/
private static function enforceNonNullMatches(string $pattern, array $matches, string $variantMethod)
{
foreach ($matches as $group => $match) {
if (null === $match) {
throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.');
}
}
/** @var array<string> */
return $matches;
}
/**
* @param array<int|string, list<string|null>> $matches
* @return array<int|string, list<string>>
* @throws UnexpectedNullMatchException
*/
private static function enforceNonNullMatchAll(string $pattern, array $matches, string $variantMethod)
{
foreach ($matches as $group => $groupMatches) {
foreach ($groupMatches as $match) {
if (null === $match) {
throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.');
}
}
}
/** @var array<int|string, list<string>> */
return $matches;
}
}

View File

@ -1,174 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
class Regex
{
/**
* @param non-empty-string $pattern
*/
public static function isMatch(string $pattern, string $subject, int $offset = 0): bool
{
return (bool) Preg::match($pattern, $subject, $matches, 0, $offset);
}
/**
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*/
public static function match(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchResult
{
self::checkOffsetCapture($flags, 'matchWithOffsets');
$count = Preg::match($pattern, $subject, $matches, $flags, $offset);
return new MatchResult($count, $matches);
}
/**
* Variant of `match()` which returns non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @throws UnexpectedNullMatchException
*/
public static function matchStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchStrictGroupsResult
{
$count = Preg::matchStrictGroups($pattern, $subject, $matches, $flags, $offset);
return new MatchStrictGroupsResult($count, $matches);
}
/**
* Runs preg_match with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported
*/
public static function matchWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchWithOffsetsResult
{
$count = Preg::matchWithOffsets($pattern, $subject, $matches, $flags, $offset);
return new MatchWithOffsetsResult($count, $matches);
}
/**
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
*/
public static function matchAll(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllResult
{
self::checkOffsetCapture($flags, 'matchAllWithOffsets');
self::checkSetOrder($flags);
$count = Preg::matchAll($pattern, $subject, $matches, $flags, $offset);
return new MatchAllResult($count, $matches);
}
/**
* Variant of `matchAll()` which returns non-null matches (or throws)
*
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL> $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported
* @throws UnexpectedNullMatchException
*/
public static function matchAllStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllStrictGroupsResult
{
self::checkOffsetCapture($flags, 'matchAllWithOffsets');
self::checkSetOrder($flags);
$count = Preg::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset);
return new MatchAllStrictGroupsResult($count, $matches);
}
/**
* Runs preg_match_all with PREG_OFFSET_CAPTURE
*
* @param non-empty-string $pattern
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported
*/
public static function matchAllWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllWithOffsetsResult
{
self::checkSetOrder($flags);
$count = Preg::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset);
return new MatchAllWithOffsetsResult($count, $matches);
}
/**
* @param string|string[] $pattern
* @param string|string[] $replacement
* @param string $subject
*/
public static function replace($pattern, $replacement, $subject, int $limit = -1): ReplaceResult
{
$result = Preg::replace($pattern, $replacement, $subject, $limit, $count);
return new ReplaceResult($count, $result);
}
/**
* @param string|string[] $pattern
* @param callable(array<int|string, string|null>): string $replacement
* @param string $subject
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set
*/
public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult
{
$result = Preg::replaceCallback($pattern, $replacement, $subject, $limit, $count, $flags);
return new ReplaceResult($count, $result);
}
/**
* Variant of `replaceCallback()` which outputs non-null matches (or throws)
*
* @param string $pattern
* @param callable(array<int|string, string>): string $replacement
* @param string $subject
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+
*/
public static function replaceCallbackStrictGroups($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult
{
$result = Preg::replaceCallbackStrictGroups($pattern, $replacement, $subject, $limit, $count, $flags);
return new ReplaceResult($count, $result);
}
/**
* @param array<string, callable(array<int|string, string|null>): string> $pattern
* @param string $subject
* @param int-mask<PREG_UNMATCHED_AS_NULL|PREG_OFFSET_CAPTURE> $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set
*/
public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int $flags = 0): ReplaceResult
{
$result = Preg::replaceCallbackArray($pattern, $subject, $limit, $count, $flags);
return new ReplaceResult($count, $result);
}
private static function checkOffsetCapture(int $flags, string $useFunctionName): void
{
if (($flags & PREG_OFFSET_CAPTURE) !== 0) {
throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the return type, use '.$useFunctionName.'() instead');
}
}
private static function checkSetOrder(int $flags): void
{
if (($flags & PREG_SET_ORDER) !== 0) {
throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the return type');
}
}
}

View File

@ -1,43 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
final class ReplaceResult
{
/**
* @readonly
* @var string
*/
public $result;
/**
* @readonly
* @var 0|positive-int
*/
public $count;
/**
* @readonly
* @var bool
*/
public $matched;
/**
* @param 0|positive-int $count
*/
public function __construct(int $count, string $result)
{
$this->count = $count;
$this->matched = (bool) $count;
$this->result = $result;
}
}

View File

@ -1,20 +0,0 @@
<?php
/*
* This file is part of composer/pcre.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Pcre;
class UnexpectedNullMatchException extends PcreException
{
public static function fromFunction($function, $pattern)
{
throw new \LogicException('fromFunction should not be called on '.self::class.', use '.PcreException::class);
}
}

View File

@ -1,26 +0,0 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 70400)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

View File

@ -1,209 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
### [3.3.2] 2022-04-01
* Fixed handling of non-string values (#134)
### [3.3.1] 2022-03-16
* Fixed possible cache key clash in the CompilingMatcher memoization (#132)
### [3.3.0] 2022-03-15
* Improved performance of CompilingMatcher by memoizing more (#131)
* Added CompilingMatcher::clear to clear all memoization caches
### [3.2.9] 2022-02-04
* Revert #129 (Fixed MultiConstraint with MatchAllConstraint) which caused regressions
### [3.2.8] 2022-02-04
* Updates to latest phpstan / CI by @Seldaek in https://github.com/composer/semver/pull/130
* Fixed MultiConstraint with MatchAllConstraint by @Toflar in https://github.com/composer/semver/pull/129
### [3.2.7] 2022-01-04
* Fixed: typo in type definition of Intervals class causing issues with Psalm scanning vendors
### [3.2.6] 2021-10-25
* Fixed: type improvements to parseStability
### [3.2.5] 2021-05-24
* Fixed: issue comparing disjunctive MultiConstraints to conjunctive ones (#127)
* Fixed: added complete type information using phpstan annotations
### [3.2.4] 2020-11-13
* Fixed: code clean-up
### [3.2.3] 2020-11-12
* Fixed: constraints in the form of `X || Y, >=Y.1` and other such complex constructs were in some cases being optimized into a more restrictive constraint
### [3.2.2] 2020-10-14
* Fixed: internal code cleanups
### [3.2.1] 2020-09-27
* Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases
* Fixed: normalization of beta0 and such which was dropping the 0
### [3.2.0] 2020-09-09
* Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0
* Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience
### [3.1.0] 2020-09-08
* Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 3.0.1
* Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package
### [3.0.1] 2020-09-08
* Fixed: handling of some invalid -dev versions which were seen as valid
### [3.0.0] 2020-05-26
* Break: Renamed `EmptyConstraint`, replace it with `MatchAllConstraint`
* Break: Unlikely to affect anyone but strictly speaking a breaking change, `*.*` and such variants will not match all `dev-*` versions anymore, only `*` does
* Break: ConstraintInterface is now considered internal/private and not meant to be implemented by third parties anymore
* Added `Intervals` class to check if a constraint is a subsets of another one, and allow compacting complex MultiConstraints into simpler ones
* Added `CompilingMatcher` class to speed up constraint matching against simple Constraint instances
* Added `MatchAllConstraint` and `MatchNoneConstraint` which match everything and nothing
* Added more advanced optimization of contiguous constraints inside MultiConstraint
* Added tentative support for PHP 8
* Fixed ConstraintInterface::matches to be commutative in all cases
### [2.0.0] 2020-04-21
* Break: `dev-master`, `dev-trunk` and `dev-default` now normalize to `dev-master`, `dev-trunk` and `dev-default` instead of `9999999-dev` in 1.x
* Break: Removed the deprecated `AbstractConstraint`
* Added `getUpperBound` and `getLowerBound` to ConstraintInterface. They return `Composer\Semver\Constraint\Bound` instances
* Added `MultiConstraint::create` to create the most-optimal form of ConstraintInterface from an array of constraint strings
### [1.7.2] 2020-12-03
* Fixed: Allow installing on php 8
### [1.7.1] 2020-09-27
* Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases
* Fixed: normalization of beta0 and such which was dropping the 0
### [1.7.0] 2020-09-09
* Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0
* Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience
### [1.6.0] 2020-09-08
* Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2
* Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package
### [1.5.2] 2020-09-08
* Fixed: handling of some invalid -dev versions which were seen as valid
* Fixed: some doctypes
### [1.5.1] 2020-01-13
* Fixed: Parsing of aliased version was not validating the alias to be a valid version
### [1.5.0] 2019-03-19
* Added: some support for date versions (e.g. 201903) in `~` operator
* Fixed: support for stabilities in `~` operator was inconsistent
### [1.4.2] 2016-08-30
* Fixed: collapsing of complex constraints lead to buggy constraints
### [1.4.1] 2016-06-02
* Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38).
### [1.4.0] 2016-03-30
* Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35).
### [1.3.0] 2016-02-25
* Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889).
* Changed: collapse contiguous constraints when possible.
### [1.2.0] 2015-11-10
* Changed: allow multiple numerical identifiers in 'pre-release' version part.
* Changed: add more 'v' prefix support.
### [1.1.0] 2015-11-03
* Changed: dropped redundant `test` namespace.
* Changed: minor adjustment in datetime parsing normalization.
* Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore.
* Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0.
* Changed: `Constraint` is now extensible.
### [1.0.0] 2015-09-21
* Break: `VersionConstraint` renamed to `Constraint`.
* Break: `SpecificConstraint` renamed to `AbstractConstraint`.
* Break: `LinkConstraintInterface` renamed to `ConstraintInterface`.
* Break: `VersionParser::parseNameVersionPairs` was removed.
* Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now.
* Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now.
* Changed: Fixed namespace(s) of test files.
* Changed: `Comparator::compare` no longer throws `InvalidArgumentException`.
* Changed: `Constraint` now throws `InvalidArgumentException`.
### [0.1.0] 2015-07-23
* Added: `Composer\Semver\Comparator`, various methods to compare versions.
* Added: various documents such as README.md, LICENSE, etc.
* Added: configuration files for Git, Travis, php-cs-fixer, phpunit.
* Break: the following namespaces were renamed:
- Namespace: `Composer\Package\Version` -> `Composer\Semver`
- Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint`
- Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver`
- Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint`
* Changed: code style using php-cs-fixer.
[3.3.2]: https://github.com/composer/semver/compare/3.3.1...3.3.2
[3.3.1]: https://github.com/composer/semver/compare/3.3.0...3.3.1
[3.3.0]: https://github.com/composer/semver/compare/3.2.9...3.3.0
[3.2.9]: https://github.com/composer/semver/compare/3.2.8...3.2.9
[3.2.8]: https://github.com/composer/semver/compare/3.2.7...3.2.8
[3.2.7]: https://github.com/composer/semver/compare/3.2.6...3.2.7
[3.2.6]: https://github.com/composer/semver/compare/3.2.5...3.2.6
[3.2.5]: https://github.com/composer/semver/compare/3.2.4...3.2.5
[3.2.4]: https://github.com/composer/semver/compare/3.2.3...3.2.4
[3.2.3]: https://github.com/composer/semver/compare/3.2.2...3.2.3
[3.2.2]: https://github.com/composer/semver/compare/3.2.1...3.2.2
[3.2.1]: https://github.com/composer/semver/compare/3.2.0...3.2.1
[3.2.0]: https://github.com/composer/semver/compare/3.1.0...3.2.0
[3.1.0]: https://github.com/composer/semver/compare/3.0.1...3.1.0
[3.0.1]: https://github.com/composer/semver/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/composer/semver/compare/2.0.0...3.0.0
[2.0.0]: https://github.com/composer/semver/compare/1.5.1...2.0.0
[1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2
[1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1
[1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0
[1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0
[1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2
[1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1
[1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0
[1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2
[1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1
[1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0
[1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0
[1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0
[1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0
[0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0

View File

@ -1,19 +0,0 @@
Copyright (C) 2015 Composer
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,98 +0,0 @@
composer/semver
===============
Semver (Semantic Versioning) library that offers utilities, version constraint parsing and validation.
Originally written as part of [composer/composer](https://github.com/composer/composer),
now extracted and made available as a stand-alone library.
[![Continuous Integration](https://github.com/composer/semver/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/semver/actions)
Installation
------------
Install the latest version with:
```bash
$ composer require composer/semver
```
Requirements
------------
* PHP 5.3.2 is required but using the latest version of PHP is highly recommended.
Version Comparison
------------------
For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md)
article in the documentation section of the [getcomposer.org](https://getcomposer.org) website.
Basic usage
-----------
### Comparator
The [`Composer\Semver\Comparator`](https://github.com/composer/semver/blob/main/src/Comparator.php) class provides the following methods for comparing versions:
* greaterThan($v1, $v2)
* greaterThanOrEqualTo($v1, $v2)
* lessThan($v1, $v2)
* lessThanOrEqualTo($v1, $v2)
* equalTo($v1, $v2)
* notEqualTo($v1, $v2)
Each function takes two version strings as arguments and returns a boolean. For example:
```php
use Composer\Semver\Comparator;
Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0
```
### Semver
The [`Composer\Semver\Semver`](https://github.com/composer/semver/blob/main/src/Semver.php) class provides the following methods:
* satisfies($version, $constraints)
* satisfiedBy(array $versions, $constraint)
* sort($versions)
* rsort($versions)
### Intervals
The [`Composer\Semver\Intervals`](https://github.com/composer/semver/blob/main/src/Intervals.php) static class provides
a few utilities to work with complex constraints or read version intervals from a constraint:
```php
use Composer\Semver\Intervals;
// Checks whether $candidate is a subset of $constraint
Intervals::isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint);
// Checks whether $a and $b have any intersection, equivalent to $a->matches($b)
Intervals::haveIntersections(ConstraintInterface $a, ConstraintInterface $b);
// Optimizes a complex multi constraint by merging all intervals down to the smallest
// possible multi constraint. The drawbacks are this is not very fast, and the resulting
// multi constraint will have no human readable prettyConstraint configured on it
Intervals::compactConstraint(ConstraintInterface $constraint);
// Creates an array of numeric intervals and branch constraints representing a given constraint
Intervals::get(ConstraintInterface $constraint);
// Clears the memoization cache when you are done processing constraints
Intervals::clear()
```
See the class docblocks for more details.
License
-------
composer/semver is licensed under the MIT License, see the LICENSE file for details.

View File

@ -1,59 +0,0 @@
{
"name": "composer/semver",
"description": "Semver library that offers utilities, version constraint parsing and validation.",
"type": "library",
"license": "MIT",
"keywords": [
"semver",
"semantic",
"versioning",
"validation"
],
"authors": [
{
"name": "Nils Adermann",
"email": "naderman@naderman.de",
"homepage": "http://www.naderman.de"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
},
{
"name": "Rob Bast",
"email": "rob.bast@gmail.com",
"homepage": "http://robbast.nl"
}
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/semver/issues"
},
"require": {
"php": "^5.3.2 || ^7.0 || ^8.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^4.2 || ^5",
"phpstan/phpstan": "^1.4"
},
"autoload": {
"psr-4": {
"Composer\\Semver\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Composer\\Semver\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"scripts": {
"test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor/bin/simple-phpunit",
"phpstan": "@php vendor/bin/phpstan analyse"
}
}

View File

@ -1,113 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Comparator
{
/**
* Evaluates the expression: $version1 > $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function greaterThan($version1, $version2)
{
return self::compare($version1, '>', $version2);
}
/**
* Evaluates the expression: $version1 >= $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function greaterThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '>=', $version2);
}
/**
* Evaluates the expression: $version1 < $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function lessThan($version1, $version2)
{
return self::compare($version1, '<', $version2);
}
/**
* Evaluates the expression: $version1 <= $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function lessThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '<=', $version2);
}
/**
* Evaluates the expression: $version1 == $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function equalTo($version1, $version2)
{
return self::compare($version1, '==', $version2);
}
/**
* Evaluates the expression: $version1 != $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function notEqualTo($version1, $version2)
{
return self::compare($version1, '!=', $version2);
}
/**
* Evaluates the expression: $version1 $operator $version2.
*
* @param string $version1
* @param string $operator
* @param string $version2
*
* @return bool
*
* @phpstan-param Constraint::STR_OP_* $operator
*/
public static function compare($version1, $operator, $version2)
{
$constraint = new Constraint($operator, $version2);
return $constraint->matchSpecific(new Constraint('==', $version1), true);
}
}

View File

@ -1,94 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
/**
* Helper class to evaluate constraint by compiling and reusing the code to evaluate
*/
class CompilingMatcher
{
/**
* @var array
* @phpstan-var array<string, callable>
*/
private static $compiledCheckerCache = array();
/**
* @var array
* @phpstan-var array<string, bool>
*/
private static $resultCache = array();
/** @var bool */
private static $enabled;
/**
* @phpstan-var array<Constraint::OP_*, Constraint::STR_OP_*>
*/
private static $transOpInt = array(
Constraint::OP_EQ => Constraint::STR_OP_EQ,
Constraint::OP_LT => Constraint::STR_OP_LT,
Constraint::OP_LE => Constraint::STR_OP_LE,
Constraint::OP_GT => Constraint::STR_OP_GT,
Constraint::OP_GE => Constraint::STR_OP_GE,
Constraint::OP_NE => Constraint::STR_OP_NE,
);
/**
* Clears the memoization cache once you are done
*
* @return void
*/
public static function clear()
{
self::$resultCache = array();
self::$compiledCheckerCache = array();
}
/**
* Evaluates the expression: $constraint match $operator $version
*
* @param ConstraintInterface $constraint
* @param int $operator
* @phpstan-param Constraint::OP_* $operator
* @param string $version
*
* @return mixed
*/
public static function match(ConstraintInterface $constraint, $operator, $version)
{
$resultCacheKey = $operator.$constraint.';'.$version;
if (isset(self::$resultCache[$resultCacheKey])) {
return self::$resultCache[$resultCacheKey];
}
if (self::$enabled === null) {
self::$enabled = !\in_array('eval', explode(',', (string) ini_get('disable_functions')), true);
}
if (!self::$enabled) {
return self::$resultCache[$resultCacheKey] = $constraint->matches(new Constraint(self::$transOpInt[$operator], $version));
}
$cacheKey = $operator.$constraint;
if (!isset(self::$compiledCheckerCache[$cacheKey])) {
$code = $constraint->compile($operator);
self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};');
} else {
$function = self::$compiledCheckerCache[$cacheKey];
}
return self::$resultCache[$resultCacheKey] = $function($version, strpos($version, 'dev-') === 0);
}
}

View File

@ -1,122 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
class Bound
{
/**
* @var string
*/
private $version;
/**
* @var bool
*/
private $isInclusive;
/**
* @param string $version
* @param bool $isInclusive
*/
public function __construct($version, $isInclusive)
{
$this->version = $version;
$this->isInclusive = $isInclusive;
}
/**
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* @return bool
*/
public function isInclusive()
{
return $this->isInclusive;
}
/**
* @return bool
*/
public function isZero()
{
return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive();
}
/**
* @return bool
*/
public function isPositiveInfinity()
{
return $this->getVersion() === PHP_INT_MAX.'.0.0.0' && !$this->isInclusive();
}
/**
* Compares a bound to another with a given operator.
*
* @param Bound $other
* @param string $operator
*
* @return bool
*/
public function compareTo(Bound $other, $operator)
{
if (!\in_array($operator, array('<', '>'), true)) {
throw new \InvalidArgumentException('Does not support any other operator other than > or <.');
}
// If they are the same it doesn't matter
if ($this == $other) {
return false;
}
$compareResult = version_compare($this->getVersion(), $other->getVersion());
// Not the same version means we don't need to check if the bounds are inclusive or not
if (0 !== $compareResult) {
return (('>' === $operator) ? 1 : -1) === $compareResult;
}
// Question we're answering here is "am I higher than $other?"
return '>' === $operator ? $other->isInclusive() : !$other->isInclusive();
}
public function __toString()
{
return sprintf(
'%s [%s]',
$this->getVersion(),
$this->isInclusive() ? 'inclusive' : 'exclusive'
);
}
/**
* @return self
*/
public static function zero()
{
return new Bound('0.0.0.0-dev', true);
}
/**
* @return self
*/
public static function positiveInfinity()
{
return new Bound(PHP_INT_MAX.'.0.0.0', false);
}
}

View File

@ -1,435 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines a constraint.
*/
class Constraint implements ConstraintInterface
{
/* operator integer values */
const OP_EQ = 0;
const OP_LT = 1;
const OP_LE = 2;
const OP_GT = 3;
const OP_GE = 4;
const OP_NE = 5;
/* operator string values */
const STR_OP_EQ = '==';
const STR_OP_EQ_ALT = '=';
const STR_OP_LT = '<';
const STR_OP_LE = '<=';
const STR_OP_GT = '>';
const STR_OP_GE = '>=';
const STR_OP_NE = '!=';
const STR_OP_NE_ALT = '<>';
/**
* Operator to integer translation table.
*
* @var array
* @phpstan-var array<self::STR_OP_*, self::OP_*>
*/
private static $transOpStr = array(
'=' => self::OP_EQ,
'==' => self::OP_EQ,
'<' => self::OP_LT,
'<=' => self::OP_LE,
'>' => self::OP_GT,
'>=' => self::OP_GE,
'<>' => self::OP_NE,
'!=' => self::OP_NE,
);
/**
* Integer to operator translation table.
*
* @var array
* @phpstan-var array<self::OP_*, self::STR_OP_*>
*/
private static $transOpInt = array(
self::OP_EQ => '==',
self::OP_LT => '<',
self::OP_LE => '<=',
self::OP_GT => '>',
self::OP_GE => '>=',
self::OP_NE => '!=',
);
/**
* @var int
* @phpstan-var self::OP_*
*/
protected $operator;
/** @var string */
protected $version;
/** @var string|null */
protected $prettyString;
/** @var Bound */
protected $lowerBound;
/** @var Bound */
protected $upperBound;
/**
* Sets operator and version to compare with.
*
* @param string $operator
* @param string $version
*
* @throws \InvalidArgumentException if invalid operator is given.
*
* @phpstan-param self::STR_OP_* $operator
*/
public function __construct($operator, $version)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$this->operator = self::$transOpStr[$operator];
$this->version = $version;
}
/**
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* @return string
*
* @phpstan-return self::STR_OP_*
*/
public function getOperator()
{
return self::$transOpInt[$this->operator];
}
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
if ($provider instanceof self) {
return $this->matchSpecific($provider);
}
// turn matching around to find a match
return $provider->matches($this);
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return $this->__toString();
}
/**
* Get all supported comparison operators.
*
* @return array
*
* @phpstan-return list<self::STR_OP_*>
*/
public static function getSupportedOperators()
{
return array_keys(self::$transOpStr);
}
/**
* @param string $operator
* @return int
*
* @phpstan-param self::STR_OP_* $operator
* @phpstan-return self::OP_*
*/
public static function getOperatorConstant($operator)
{
return self::$transOpStr[$operator];
}
/**
* @param string $a
* @param string $b
* @param string $operator
* @param bool $compareBranches
*
* @throws \InvalidArgumentException if invalid operator is given.
*
* @return bool
*
* @phpstan-param self::STR_OP_* $operator
*/
public function versionCompare($a, $b, $operator, $compareBranches = false)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$aIsBranch = strpos($a, 'dev-') === 0;
$bIsBranch = strpos($b, 'dev-') === 0;
if ($operator === '!=' && ($aIsBranch || $bIsBranch)) {
return $a !== $b;
}
if ($aIsBranch && $bIsBranch) {
return $operator === '==' && $a === $b;
}
// when branches are not comparable, we make sure dev branches never match anything
if (!$compareBranches && ($aIsBranch || $bIsBranch)) {
return false;
}
return \version_compare($a, $b, $operator);
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
if (strpos($this->version, 'dev-') === 0) {
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b && $v === %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
return 'false';
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
return 'false';
}
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('\version_compare($v, %s, \'==\')', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('$b || \version_compare($v, %s, \'!=\')', \var_export($this->version, true));
}
return sprintf('!$b && \version_compare(%s, $v, \'%s\')', \var_export($this->version, true), self::$transOpInt[$otherOperator]);
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b || (!$b && \version_compare($v, %s, \'!=\'))', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
if (self::OP_LT === $this->operator || self::OP_LE === $this->operator) {
if (self::OP_LT === $otherOperator || self::OP_LE === $otherOperator) {
return '!$b';
}
} else { // $this->operator must be self::OP_GT || self::OP_GE here
if (self::OP_GT === $otherOperator || self::OP_GE === $otherOperator) {
return '!$b';
}
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
$codeComparison = sprintf('\version_compare($v, %s, \'%s\')', \var_export($this->version, true), self::$transOpInt[$this->operator]);
if ($this->operator === self::OP_LE) {
if ($otherOperator === self::OP_GT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
} elseif ($this->operator === self::OP_GE) {
if ($otherOperator === self::OP_LT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
}
return sprintf('!$b && %s', $codeComparison);
}
/**
* @param Constraint $provider
* @param bool $compareBranches
*
* @return bool
*/
public function matchSpecific(Constraint $provider, $compareBranches = false)
{
$noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]);
$providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]);
$isEqualOp = self::OP_EQ === $this->operator;
$isNonEqualOp = self::OP_NE === $this->operator;
$isProviderEqualOp = self::OP_EQ === $provider->operator;
$isProviderNonEqualOp = self::OP_NE === $provider->operator;
// '!=' operator is match when other operator is not '==' operator or version is not match
// these kinds of comparisons always have a solution
if ($isNonEqualOp || $isProviderNonEqualOp) {
if ($isNonEqualOp && !$isProviderNonEqualOp && !$isProviderEqualOp && strpos($provider->version, 'dev-') === 0) {
return false;
}
if ($isProviderNonEqualOp && !$isNonEqualOp && !$isEqualOp && strpos($this->version, 'dev-') === 0) {
return false;
}
if (!$isEqualOp && !$isProviderEqualOp) {
return true;
}
return $this->versionCompare($provider->version, $this->version, '!=', $compareBranches);
}
// an example for the condition is <= 2.0 & < 1.0
// these kinds of comparisons always have a solution
if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) {
return !(strpos($this->version, 'dev-') === 0 || strpos($provider->version, 'dev-') === 0);
}
$version1 = $isEqualOp ? $this->version : $provider->version;
$version2 = $isEqualOp ? $provider->version : $this->version;
$operator = $isEqualOp ? $provider->operator : $this->operator;
if ($this->versionCompare($version1, $version2, self::$transOpInt[$operator], $compareBranches)) {
// special case, e.g. require >= 1.0 and provide < 1.0
// 1.0 >= 1.0 but 1.0 is outside of the provided interval
return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp
&& self::$transOpInt[$this->operator] !== $noEqualOp
&& \version_compare($provider->version, $this->version, '=='));
}
return false;
}
/**
* @return string
*/
public function __toString()
{
return self::$transOpInt[$this->operator] . ' ' . $this->version;
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
$this->extractBounds();
return $this->lowerBound;
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
$this->extractBounds();
return $this->upperBound;
}
/**
* @return void
*/
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
// Branches
if (strpos($this->version, 'dev-') === 0) {
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
return;
}
switch ($this->operator) {
case self::OP_EQ:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_LT:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, false);
break;
case self::OP_LE:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_GT:
$this->lowerBound = new Bound($this->version, false);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_GE:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_NE:
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
break;
}
}
}

View File

@ -1,75 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* DO NOT IMPLEMENT this interface. It is only meant for usage as a type hint
* in libraries relying on composer/semver but creating your own constraint class
* that implements this interface is not a supported use case and will cause the
* composer/semver components to return unexpected results.
*/
interface ConstraintInterface
{
/**
* Checks whether the given constraint intersects in any way with this constraint
*
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider);
/**
* Provides a compiled version of the constraint for the given operator
* The compiled version must be a PHP expression.
* Executor of compile version must provide 2 variables:
* - $v = the string version to compare with
* - $b = whether or not the version is a non-comparable branch (starts with "dev-")
*
* @see Constraint::OP_* for the list of available operators.
* @example return '!$b && version_compare($v, '1.0', '>')';
*
* @param int $otherOperator one Constraint::OP_*
*
* @return string
*
* @phpstan-param Constraint::OP_* $otherOperator
*/
public function compile($otherOperator);
/**
* @return Bound
*/
public function getUpperBound();
/**
* @return Bound
*/
public function getLowerBound();
/**
* @return string
*/
public function getPrettyString();
/**
* @param string|null $prettyString
*
* @return void
*/
public function setPrettyString($prettyString);
/**
* @return string
*/
public function __toString();
}

View File

@ -1,85 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines the absence of a constraint.
*
* This constraint matches everything.
*/
class MatchAllConstraint implements ConstraintInterface
{
/** @var string|null */
protected $prettyString;
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
return true;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
return 'true';
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
return '*';
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
return Bound::positiveInfinity();
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
return Bound::zero();
}
}

View File

@ -1,83 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Blackhole of constraints, nothing escapes it
*/
class MatchNoneConstraint implements ConstraintInterface
{
/** @var string|null */
protected $prettyString;
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
return false;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
return 'false';
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
return '[]';
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
return new Bound('0.0.0.0-dev', false);
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
return new Bound('0.0.0.0-dev', false);
}
}

View File

@ -1,325 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines a conjunctive or disjunctive set of constraints.
*/
class MultiConstraint implements ConstraintInterface
{
/**
* @var ConstraintInterface[]
* @phpstan-var non-empty-array<ConstraintInterface>
*/
protected $constraints;
/** @var string|null */
protected $prettyString;
/** @var string|null */
protected $string;
/** @var bool */
protected $conjunctive;
/** @var Bound|null */
protected $lowerBound;
/** @var Bound|null */
protected $upperBound;
/**
* @param ConstraintInterface[] $constraints A set of constraints
* @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive
*
* @throws \InvalidArgumentException If less than 2 constraints are passed
*/
public function __construct(array $constraints, $conjunctive = true)
{
if (\count($constraints) < 2) {
throw new \InvalidArgumentException(
'Must provide at least two constraints for a MultiConstraint. Use '.
'the regular Constraint class for one constraint only or MatchAllConstraint for none. You may use '.
'MultiConstraint::create() which optimizes and handles those cases automatically.'
);
}
$this->constraints = $constraints;
$this->conjunctive = $conjunctive;
}
/**
* @return ConstraintInterface[]
*/
public function getConstraints()
{
return $this->constraints;
}
/**
* @return bool
*/
public function isConjunctive()
{
return $this->conjunctive;
}
/**
* @return bool
*/
public function isDisjunctive()
{
return !$this->conjunctive;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
$parts = array();
foreach ($this->constraints as $constraint) {
$code = $constraint->compile($otherOperator);
if ($code === 'true') {
if (!$this->conjunctive) {
return 'true';
}
} elseif ($code === 'false') {
if ($this->conjunctive) {
return 'false';
}
} else {
$parts[] = '('.$code.')';
}
}
if (!$parts) {
return $this->conjunctive ? 'true' : 'false';
}
return $this->conjunctive ? implode('&&', $parts) : implode('||', $parts);
}
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
if (false === $this->conjunctive) {
foreach ($this->constraints as $constraint) {
if ($provider->matches($constraint)) {
return true;
}
}
return false;
}
// when matching a conjunctive and a disjunctive multi constraint we have to iterate over the disjunctive one
// otherwise we'd return true if different parts of the disjunctive constraint match the conjunctive one
// which would lead to incorrect results, e.g. [>1 and <2] would match [<1 or >2] although they do not intersect
if ($provider instanceof MultiConstraint && $provider->isDisjunctive()) {
return $provider->matches($this);
}
foreach ($this->constraints as $constraint) {
if (!$provider->matches($constraint)) {
return false;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
if ($this->string !== null) {
return $this->string;
}
$constraints = array();
foreach ($this->constraints as $constraint) {
$constraints[] = (string) $constraint;
}
return $this->string = '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']';
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
$this->extractBounds();
if (null === $this->lowerBound) {
throw new \LogicException('extractBounds should have populated the lowerBound property');
}
return $this->lowerBound;
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
$this->extractBounds();
if (null === $this->upperBound) {
throw new \LogicException('extractBounds should have populated the upperBound property');
}
return $this->upperBound;
}
/**
* Tries to optimize the constraints as much as possible, meaning
* reducing/collapsing congruent constraints etc.
* Does not necessarily return a MultiConstraint instance if
* things can be reduced to a simple constraint
*
* @param ConstraintInterface[] $constraints A set of constraints
* @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive
*
* @return ConstraintInterface
*/
public static function create(array $constraints, $conjunctive = true)
{
if (0 === \count($constraints)) {
return new MatchAllConstraint();
}
if (1 === \count($constraints)) {
return $constraints[0];
}
$optimized = self::optimizeConstraints($constraints, $conjunctive);
if ($optimized !== null) {
list($constraints, $conjunctive) = $optimized;
if (\count($constraints) === 1) {
return $constraints[0];
}
}
return new self($constraints, $conjunctive);
}
/**
* @param ConstraintInterface[] $constraints
* @param bool $conjunctive
* @return ?array
*
* @phpstan-return array{0: list<ConstraintInterface>, 1: bool}|null
*/
private static function optimizeConstraints(array $constraints, $conjunctive)
{
// parse the two OR groups and if they are contiguous we collapse
// them into one constraint
// [>= 1 < 2] || [>= 2 < 3] || [>= 3 < 4] => [>= 1 < 4]
if (!$conjunctive) {
$left = $constraints[0];
$mergedConstraints = array();
$optimized = false;
for ($i = 1, $l = \count($constraints); $i < $l; $i++) {
$right = $constraints[$i];
if (
$left instanceof self
&& $left->conjunctive
&& $right instanceof self
&& $right->conjunctive
&& \count($left->constraints) === 2
&& \count($right->constraints) === 2
&& ($left0 = (string) $left->constraints[0])
&& $left0[0] === '>' && $left0[1] === '='
&& ($left1 = (string) $left->constraints[1])
&& $left1[0] === '<'
&& ($right0 = (string) $right->constraints[0])
&& $right0[0] === '>' && $right0[1] === '='
&& ($right1 = (string) $right->constraints[1])
&& $right1[0] === '<'
&& substr($left1, 2) === substr($right0, 3)
) {
$optimized = true;
$left = new MultiConstraint(
array(
$left->constraints[0],
$right->constraints[1],
),
true);
} else {
$mergedConstraints[] = $left;
$left = $right;
}
}
if ($optimized) {
$mergedConstraints[] = $left;
return array($mergedConstraints, false);
}
}
// TODO: Here's the place to put more optimizations
return null;
}
/**
* @return void
*/
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
foreach ($this->constraints as $constraint) {
if (null === $this->lowerBound || null === $this->upperBound) {
$this->lowerBound = $constraint->getLowerBound();
$this->upperBound = $constraint->getUpperBound();
continue;
}
if ($constraint->getLowerBound()->compareTo($this->lowerBound, $this->isConjunctive() ? '>' : '<')) {
$this->lowerBound = $constraint->getLowerBound();
}
if ($constraint->getUpperBound()->compareTo($this->upperBound, $this->isConjunctive() ? '<' : '>')) {
$this->upperBound = $constraint->getUpperBound();
}
}
}
}

View File

@ -1,98 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Interval
{
/** @var Constraint */
private $start;
/** @var Constraint */
private $end;
public function __construct(Constraint $start, Constraint $end)
{
$this->start = $start;
$this->end = $end;
}
/**
* @return Constraint
*/
public function getStart()
{
return $this->start;
}
/**
* @return Constraint
*/
public function getEnd()
{
return $this->end;
}
/**
* @return Constraint
*/
public static function fromZero()
{
static $zero;
if (null === $zero) {
$zero = new Constraint('>=', '0.0.0.0-dev');
}
return $zero;
}
/**
* @return Constraint
*/
public static function untilPositiveInfinity()
{
static $positiveInfinity;
if (null === $positiveInfinity) {
$positiveInfinity = new Constraint('<', PHP_INT_MAX.'.0.0.0');
}
return $positiveInfinity;
}
/**
* @return self
*/
public static function any()
{
return new self(self::fromZero(), self::untilPositiveInfinity());
}
/**
* @return array{'names': string[], 'exclude': bool}
*/
public static function anyDev()
{
// any == exclude nothing
return array('names' => array(), 'exclude' => true);
}
/**
* @return array{'names': string[], 'exclude': bool}
*/
public static function noDev()
{
// nothing == no names included
return array('names' => array(), 'exclude' => false);
}
}

View File

@ -1,478 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MatchNoneConstraint;
use Composer\Semver\Constraint\MultiConstraint;
/**
* Helper class generating intervals from constraints
*
* This contains utilities for:
*
* - compacting an existing constraint which can be used to combine several into one
* by creating a MultiConstraint out of the many constraints you have.
*
* - checking whether one subset is a subset of another.
*
* Note: You should call clear to free memoization memory usage when you are done using this class
*/
class Intervals
{
/**
* @phpstan-var array<string, array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}>
*/
private static $intervalsCache = array();
/**
* @phpstan-var array<string, int>
*/
private static $opSortOrder = array(
'>=' => -3,
'<' => -2,
'>' => 2,
'<=' => 3,
);
/**
* Clears the memoization cache once you are done
*
* @return void
*/
public static function clear()
{
self::$intervalsCache = array();
}
/**
* Checks whether $candidate is a subset of $constraint
*
* @return bool
*/
public static function isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint)
{
if ($constraint instanceof MatchAllConstraint) {
return true;
}
if ($candidate instanceof MatchNoneConstraint || $constraint instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::get(new MultiConstraint(array($candidate, $constraint), true));
$candidateIntervals = self::get($candidate);
if (\count($intersectionIntervals['numeric']) !== \count($candidateIntervals['numeric'])) {
return false;
}
foreach ($intersectionIntervals['numeric'] as $index => $interval) {
if (!isset($candidateIntervals['numeric'][$index])) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getStart() !== (string) $interval->getStart()) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getEnd() !== (string) $interval->getEnd()) {
return false;
}
}
if ($intersectionIntervals['branches']['exclude'] !== $candidateIntervals['branches']['exclude']) {
return false;
}
if (\count($intersectionIntervals['branches']['names']) !== \count($candidateIntervals['branches']['names'])) {
return false;
}
foreach ($intersectionIntervals['branches']['names'] as $index => $name) {
if ($name !== $candidateIntervals['branches']['names'][$index]) {
return false;
}
}
return true;
}
/**
* Checks whether $a and $b have any intersection, equivalent to $a->matches($b)
*
* @return bool
*/
public static function haveIntersections(ConstraintInterface $a, ConstraintInterface $b)
{
if ($a instanceof MatchAllConstraint || $b instanceof MatchAllConstraint) {
return true;
}
if ($a instanceof MatchNoneConstraint || $b instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::generateIntervals(new MultiConstraint(array($a, $b), true), true);
return \count($intersectionIntervals['numeric']) > 0 || $intersectionIntervals['branches']['exclude'] || \count($intersectionIntervals['branches']['names']) > 0;
}
/**
* Attempts to optimize a MultiConstraint
*
* When merging MultiConstraints together they can get very large, this will
* compact it by looking at the real intervals covered by all the constraints
* and then creates a new constraint containing only the smallest amount of rules
* to match the same intervals.
*
* @return ConstraintInterface
*/
public static function compactConstraint(ConstraintInterface $constraint)
{
if (!$constraint instanceof MultiConstraint) {
return $constraint;
}
$intervals = self::generateIntervals($constraint);
$constraints = array();
$hasNumericMatchAll = false;
if (\count($intervals['numeric']) === 1 && (string) $intervals['numeric'][0]->getStart() === (string) Interval::fromZero() && (string) $intervals['numeric'][0]->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $intervals['numeric'][0]->getStart();
$hasNumericMatchAll = true;
} else {
$unEqualConstraints = array();
for ($i = 0, $count = \count($intervals['numeric']); $i < $count; $i++) {
$interval = $intervals['numeric'][$i];
// if current interval ends with < N and next interval begins with > N we can swap this out for != N
// but this needs to happen as a conjunctive expression together with the start of the current interval
// and end of next interval, so [>=M, <N] || [>N, <P] => [>=M, !=N, <P] but M/P can be skipped if
// they are zero/+inf
if ($interval->getEnd()->getOperator() === '<' && $i+1 < $count) {
$nextInterval = $intervals['numeric'][$i+1];
if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') {
// only add a start if we didn't already do so, can be skipped if we're looking at second
// interval in [>=M, <N] || [>N, <P] || [>P, <Q] where unEqualConstraints currently contains
// [>=M, !=N] already and we only want to add !=P right now
if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) {
$unEqualConstraints[] = $interval->getStart();
}
$unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion());
continue;
}
}
if (\count($unEqualConstraints) > 0) {
// this is where the end of the following interval of a != constraint is added as explained above
if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) {
$unEqualConstraints[] = $interval->getEnd();
}
// count is 1 if entire constraint is just one != expression
if (\count($unEqualConstraints) > 1) {
$constraints[] = new MultiConstraint($unEqualConstraints, true);
} else {
$constraints[] = $unEqualConstraints[0];
}
$unEqualConstraints = array();
continue;
}
// convert back >= x - <= x intervals to == x
if ($interval->getStart()->getVersion() === $interval->getEnd()->getVersion() && $interval->getStart()->getOperator() === '>=' && $interval->getEnd()->getOperator() === '<=') {
$constraints[] = new Constraint('==', $interval->getStart()->getVersion());
continue;
}
if ((string) $interval->getStart() === (string) Interval::fromZero()) {
$constraints[] = $interval->getEnd();
} elseif ((string) $interval->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $interval->getStart();
} else {
$constraints[] = new MultiConstraint(array($interval->getStart(), $interval->getEnd()), true);
}
}
}
$devConstraints = array();
if (0 === \count($intervals['branches']['names'])) {
if ($intervals['branches']['exclude']) {
if ($hasNumericMatchAll) {
return new MatchAllConstraint;
}
// otherwise constraint should contain a != operator and already cover this
}
} else {
foreach ($intervals['branches']['names'] as $branchName) {
if ($intervals['branches']['exclude']) {
$devConstraints[] = new Constraint('!=', $branchName);
} else {
$devConstraints[] = new Constraint('==', $branchName);
}
}
// excluded branches, e.g. != dev-foo are conjunctive with the interval, so
// > 2.0 != dev-foo must return a conjunctive constraint
if ($intervals['branches']['exclude']) {
if (\count($constraints) > 1) {
return new MultiConstraint(array_merge(
array(new MultiConstraint($constraints, false)),
$devConstraints
), true);
}
if (\count($constraints) === 1 && (string)$constraints[0] === (string)Interval::fromZero()) {
if (\count($devConstraints) > 1) {
return new MultiConstraint($devConstraints, true);
}
return $devConstraints[0];
}
return new MultiConstraint(array_merge($constraints, $devConstraints), true);
}
// otherwise devConstraints contains a list of == operators for branches which are disjunctive with the
// rest of the constraint
$constraints = array_merge($constraints, $devConstraints);
}
if (\count($constraints) > 1) {
return new MultiConstraint($constraints, false);
}
if (\count($constraints) === 1) {
return $constraints[0];
}
return new MatchNoneConstraint;
}
/**
* Creates an array of numeric intervals and branch constraints representing a given constraint
*
* if the returned numeric array is empty it means the constraint matches nothing in the numeric range (0 - +inf)
* if the returned branches array is empty it means no dev-* versions are matched
* if a constraint matches all possible dev-* versions, branches will contain Interval::anyDev()
*
* @return array
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
public static function get(ConstraintInterface $constraint)
{
$key = (string) $constraint;
if (!isset(self::$intervalsCache[$key])) {
self::$intervalsCache[$key] = self::generateIntervals($constraint);
}
return self::$intervalsCache[$key];
}
/**
* @param bool $stopOnFirstValidInterval
*
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
private static function generateIntervals(ConstraintInterface $constraint, $stopOnFirstValidInterval = false)
{
if ($constraint instanceof MatchAllConstraint) {
return array('numeric' => array(new Interval(Interval::fromZero(), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev());
}
if ($constraint instanceof MatchNoneConstraint) {
return array('numeric' => array(), 'branches' => array('names' => array(), 'exclude' => false));
}
if ($constraint instanceof Constraint) {
return self::generateSingleConstraintIntervals($constraint);
}
if (!$constraint instanceof MultiConstraint) {
throw new \UnexpectedValueException('The constraint passed in should be an MatchAllConstraint, Constraint or MultiConstraint instance, got '.\get_class($constraint).'.');
}
$constraints = $constraint->getConstraints();
$numericGroups = array();
$constraintBranches = array();
foreach ($constraints as $c) {
$res = self::get($c);
$numericGroups[] = $res['numeric'];
$constraintBranches[] = $res['branches'];
}
if ($constraint->isDisjunctive()) {
$branches = Interval::noDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
// disjunctive constraint, so only exclude what's excluded in all constraints
// !=a,!=b || !=b,!=c => !=b
$branches['names'] = array_intersect($branches['names'], $b['names']);
} else {
// disjunctive constraint so exclude all names which are not explicitly included in the alternative
// (==b || ==c) || !=a,!=b => !=a
$branches['exclude'] = true;
$branches['names'] = array_diff($b['names'], $branches['names']);
}
} else {
if ($branches['exclude']) {
// disjunctive constraint so exclude all names which are not explicitly included in the alternative
// !=a,!=b || (==b || ==c) => !=a
$branches['names'] = array_diff($branches['names'], $b['names']);
} else {
// disjunctive constraint, so just add all the other branches
// (==a || ==b) || ==c => ==a || ==b || ==c
$branches['names'] = array_merge($branches['names'], $b['names']);
}
}
}
} else {
$branches = Interval::anyDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
// conjunctive, so just add all branch names to be excluded
// !=a && !=b => !=a,!=b
$branches['names'] = array_merge($branches['names'], $b['names']);
} else {
// conjunctive, so only keep included names which are not excluded
// (==a||==c) && !=a,!=b => ==c
$branches['names'] = array_diff($branches['names'], $b['names']);
}
} else {
if ($branches['exclude']) {
// conjunctive, so only keep included names which are not excluded
// !=a,!=b && (==a||==c) => ==c
$branches['names'] = array_diff($b['names'], $branches['names']);
$branches['exclude'] = false;
} else {
// conjunctive, so only keep names that are included in both
// (==a||==b) && (==a||==c) => ==a
$branches['names'] = array_intersect($branches['names'], $b['names']);
}
}
}
}
$branches['names'] = array_unique($branches['names']);
if (\count($numericGroups) === 1) {
return array('numeric' => $numericGroups[0], 'branches' => $branches);
}
$borders = array();
foreach ($numericGroups as $group) {
foreach ($group as $interval) {
$borders[] = array('version' => $interval->getStart()->getVersion(), 'operator' => $interval->getStart()->getOperator(), 'side' => 'start');
$borders[] = array('version' => $interval->getEnd()->getVersion(), 'operator' => $interval->getEnd()->getOperator(), 'side' => 'end');
}
}
$opSortOrder = self::$opSortOrder;
usort($borders, function ($a, $b) use ($opSortOrder) {
$order = version_compare($a['version'], $b['version']);
if ($order === 0) {
return $opSortOrder[$a['operator']] - $opSortOrder[$b['operator']];
}
return $order;
});
$activeIntervals = 0;
$intervals = array();
$index = 0;
$activationThreshold = $constraint->isConjunctive() ? \count($numericGroups) : 1;
$start = null;
foreach ($borders as $border) {
if ($border['side'] === 'start') {
$activeIntervals++;
} else {
$activeIntervals--;
}
if (!$start && $activeIntervals >= $activationThreshold) {
$start = new Constraint($border['operator'], $border['version']);
} elseif ($start && $activeIntervals < $activationThreshold) {
// filter out invalid intervals like > x - <= x, or >= x - < x
if (
version_compare($start->getVersion(), $border['version'], '=')
&& (
($start->getOperator() === '>' && $border['operator'] === '<=')
|| ($start->getOperator() === '>=' && $border['operator'] === '<')
)
) {
unset($intervals[$index]);
} else {
$intervals[$index] = new Interval($start, new Constraint($border['operator'], $border['version']));
$index++;
if ($stopOnFirstValidInterval) {
break;
}
}
$start = null;
}
}
return array('numeric' => $intervals, 'branches' => $branches);
}
/**
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
private static function generateSingleConstraintIntervals(Constraint $constraint)
{
$op = $constraint->getOperator();
// handle branch constraints first
if (strpos($constraint->getVersion(), 'dev-') === 0) {
$intervals = array();
$branches = array('names' => array(), 'exclude' => false);
// != dev-foo means any numeric version may match, we treat >/< like != they are not really defined for branches
if ($op === '!=') {
$intervals[] = new Interval(Interval::fromZero(), Interval::untilPositiveInfinity());
$branches = array('names' => array($constraint->getVersion()), 'exclude' => true);
} elseif ($op === '==') {
$branches['names'][] = $constraint->getVersion();
}
return array(
'numeric' => $intervals,
'branches' => $branches,
);
}
if ($op[0] === '>') { // > & >=
return array('numeric' => array(new Interval($constraint, Interval::untilPositiveInfinity())), 'branches' => Interval::noDev());
}
if ($op[0] === '<') { // < & <=
return array('numeric' => array(new Interval(Interval::fromZero(), $constraint)), 'branches' => Interval::noDev());
}
if ($op === '!=') {
// convert !=x to intervals of 0 - <x && >x - +inf + dev*
return array('numeric' => array(
new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())),
new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity()),
), 'branches' => Interval::anyDev());
}
// convert ==x to an interval of >=x - <=x
return array('numeric' => array(
new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion())),
), 'branches' => Interval::noDev());
}
}

View File

@ -1,129 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Semver
{
const SORT_ASC = 1;
const SORT_DESC = -1;
/** @var VersionParser */
private static $versionParser;
/**
* Determine if given version satisfies given constraints.
*
* @param string $version
* @param string $constraints
*
* @return bool
*/
public static function satisfies($version, $constraints)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$provider = new Constraint('==', $versionParser->normalize($version));
$parsedConstraints = $versionParser->parseConstraints($constraints);
return $parsedConstraints->matches($provider);
}
/**
* Return all versions that satisfy given constraints.
*
* @param string[] $versions
* @param string $constraints
*
* @return string[]
*/
public static function satisfiedBy(array $versions, $constraints)
{
$versions = array_filter($versions, function ($version) use ($constraints) {
return Semver::satisfies($version, $constraints);
});
return array_values($versions);
}
/**
* Sort given array of versions.
*
* @param string[] $versions
*
* @return string[]
*/
public static function sort(array $versions)
{
return self::usort($versions, self::SORT_ASC);
}
/**
* Sort given array of versions in reverse.
*
* @param string[] $versions
*
* @return string[]
*/
public static function rsort(array $versions)
{
return self::usort($versions, self::SORT_DESC);
}
/**
* @param string[] $versions
* @param int $direction
*
* @return string[]
*/
private static function usort(array $versions, $direction)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$normalized = array();
// Normalize outside of usort() scope for minor performance increase.
// Creates an array of arrays: [[normalized, key], ...]
foreach ($versions as $key => $version) {
$normalizedVersion = $versionParser->normalize($version);
$normalizedVersion = $versionParser->normalizeDefaultBranch($normalizedVersion);
$normalized[] = array($normalizedVersion, $key);
}
usort($normalized, function (array $left, array $right) use ($direction) {
if ($left[0] === $right[0]) {
return 0;
}
if (Comparator::lessThan($left[0], $right[0])) {
return -$direction;
}
return $direction;
});
// Recreate input array, using the original indexes which are now in sorted order.
$sorted = array();
foreach ($normalized as $item) {
$sorted[] = $versions[$item[1]];
}
return $sorted;
}
}

View File

@ -1,586 +0,0 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
use Composer\Semver\Constraint\Constraint;
/**
* Version parser.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class VersionParser
{
/**
* Regex to match pre-release data (sort of).
*
* Due to backwards compatibility:
* - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted.
* - Only stabilities as recognized by Composer are allowed to precede a numerical identifier.
* - Numerical-only pre-release identifiers are not supported, see tests.
*
* |--------------|
* [major].[minor].[patch] -[pre-release] +[build-metadata]
*
* @var string
*/
private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?';
/** @var string */
private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev';
/**
* Returns the stability of a version.
*
* @param string $version
*
* @return string
* @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev'
*/
public static function parseStability($version)
{
$version = (string) preg_replace('{#.+$}', '', (string) $version);
if (strpos($version, 'dev-') === 0 || '-dev' === substr($version, -4)) {
return 'dev';
}
preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match);
if (!empty($match[3])) {
return 'dev';
}
if (!empty($match[1])) {
if ('beta' === $match[1] || 'b' === $match[1]) {
return 'beta';
}
if ('alpha' === $match[1] || 'a' === $match[1]) {
return 'alpha';
}
if ('rc' === $match[1]) {
return 'RC';
}
}
return 'stable';
}
/**
* @param string $stability
*
* @return string
*/
public static function normalizeStability($stability)
{
$stability = strtolower((string) $stability);
return $stability === 'rc' ? 'RC' : $stability;
}
/**
* Normalizes a version string to be able to perform comparisons on it.
*
* @param string $version
* @param ?string $fullVersion optional complete version string to give more context
*
* @throws \UnexpectedValueException
*
* @return string
*/
public function normalize($version, $fullVersion = null)
{
$version = trim((string) $version);
$origVersion = $version;
if (null === $fullVersion) {
$fullVersion = $version;
}
// strip off aliasing
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) {
$version = $match[1];
}
// strip off stability flag
if (preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) {
$version = substr($version, 0, strlen($version) - strlen($match[0]));
}
// normalize master/trunk/default branches to dev-name for BC with 1.x as these used to be valid constraints
if (\in_array($version, array('master', 'trunk', 'default'), true)) {
$version = 'dev-' . $version;
}
// if requirement is branch-like, use full name
if (stripos($version, 'dev-') === 0) {
return 'dev-' . substr($version, 4);
}
// strip off build metadata
if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) {
$version = $match[1];
}
// match classical versioning
if (preg_match('{^v?(\d{1,5})(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = $matches[1]
. (!empty($matches[2]) ? $matches[2] : '.0')
. (!empty($matches[3]) ? $matches[3] : '.0')
. (!empty($matches[4]) ? $matches[4] : '.0');
$index = 5;
// match date(time) based versioning
} elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = preg_replace('{\D}', '.', $matches[1]);
$index = 2;
}
// add version modifiers if a version was matched
if (isset($index)) {
if (!empty($matches[$index])) {
if ('stable' === $matches[$index]) {
return $version;
}
$version .= '-' . $this->expandStability($matches[$index]) . (isset($matches[$index + 1]) && '' !== $matches[$index + 1] ? ltrim($matches[$index + 1], '.-') : '');
}
if (!empty($matches[$index + 2])) {
$version .= '-dev';
}
return $version;
}
// match dev branches
if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
try {
$normalized = $this->normalizeBranch($match[1]);
// a branch ending with -dev is only valid if it is numeric
// if it gets prefixed with dev- it means the branch name should
// have had a dev- prefix already when passed to normalize
if (strpos($normalized, 'dev-') === false) {
return $normalized;
}
} catch (\Exception $e) {
}
}
$extraMessage = '';
if (preg_match('{ +as +' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))?$}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version';
} elseif (preg_match('{^' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))? +as +}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
}
throw new \UnexpectedValueException('Invalid version string "' . $origVersion . '"' . $extraMessage);
}
/**
* Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison.
*
* @param string $branch Branch name (e.g. 2.1.x-dev)
*
* @return string|false Numeric prefix if present (e.g. 2.1.) or false
*/
public function parseNumericAliasPrefix($branch)
{
if (preg_match('{^(?P<version>(\d++\\.)*\d++)(?:\.x)?-dev$}i', (string) $branch, $matches)) {
return $matches['version'] . '.';
}
return false;
}
/**
* Normalizes a branch name to be able to perform comparisons on it.
*
* @param string $name
*
* @return string
*/
public function normalizeBranch($name)
{
$name = trim((string) $name);
if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) {
$version = '';
for ($i = 1; $i < 5; ++$i) {
$version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
}
return str_replace('x', '9999999', $version) . '-dev';
}
return 'dev-' . $name;
}
/**
* Normalizes a default branch name (i.e. master on git) to 9999999-dev.
*
* @param string $name
*
* @return string
*
* @deprecated No need to use this anymore in theory, Composer 2 does not normalize any branch names to 9999999-dev anymore
*/
public function normalizeDefaultBranch($name)
{
if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') {
return '9999999-dev';
}
return (string) $name;
}
/**
* Parses a constraint string into MultiConstraint and/or Constraint objects.
*
* @param string $constraints
*
* @return ConstraintInterface
*/
public function parseConstraints($constraints)
{
$prettyConstraint = (string) $constraints;
$orConstraints = preg_split('{\s*\|\|?\s*}', trim((string) $constraints));
if (false === $orConstraints) {
throw new \RuntimeException('Failed to preg_split string: '.$constraints);
}
$orGroups = array();
foreach ($orConstraints as $constraints) {
$andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
if (false === $andConstraints) {
throw new \RuntimeException('Failed to preg_split string: '.$constraints);
}
if (\count($andConstraints) > 1) {
$constraintObjects = array();
foreach ($andConstraints as $constraint) {
foreach ($this->parseConstraint($constraint) as $parsedConstraint) {
$constraintObjects[] = $parsedConstraint;
}
}
} else {
$constraintObjects = $this->parseConstraint($andConstraints[0]);
}
if (1 === \count($constraintObjects)) {
$constraint = $constraintObjects[0];
} else {
$constraint = new MultiConstraint($constraintObjects);
}
$orGroups[] = $constraint;
}
$constraint = MultiConstraint::create($orGroups, false);
$constraint->setPrettyString($prettyConstraint);
return $constraint;
}
/**
* @param string $constraint
*
* @throws \UnexpectedValueException
*
* @return array
*
* @phpstan-return non-empty-array<ConstraintInterface>
*/
private function parseConstraint($constraint)
{
// strip off aliasing
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $constraint, $match)) {
$constraint = $match[1];
}
// strip @stability flags, and keep it for later use
if (preg_match('{^([^,\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) {
$constraint = '' !== $match[1] ? $match[1] : '*';
if ($match[2] !== 'stable') {
$stabilityModifier = $match[2];
}
}
// get rid of #refs as those are used by composer only
if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraint, $match)) {
$constraint = $match[1];
}
if (preg_match('{^(v)?[xX*](\.[xX*])*$}i', $constraint, $match)) {
if (!empty($match[1]) || !empty($match[2])) {
return array(new Constraint('>=', '0.0.0.0-dev'));
}
return array(new MatchAllConstraint());
}
$versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?(?:' . self::$modifierRegex . '|\.([xX*][.-]?dev))(?:\+[^\s]+)?';
// Tilde Range
//
// Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous
// version, to ensure that unstable instances of the current version are allowed. However, if a stability
// suffix is added to the constraint, then a >= match on the current version is used instead.
if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) {
if (strpos($constraint, '~>') === 0) {
throw new \UnexpectedValueException(
'Could not parse version constraint ' . $constraint . ': ' .
'Invalid operator "~>", you probably meant to use the "~" operator'
);
}
// Work out which position in the version we are operating at
if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) {
$position = 4;
} elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
// when matching 2.x-dev or 3.0.x-dev we have to shift the second or third number, despite no second/third number matching above
if (!empty($matches[8])) {
$position++;
}
// Calculate the stability suffix
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
// For upper bound, we increment the position of one more significance,
// but highPosition = 0 would be illegal
$highPosition = max(1, $position - 1);
$highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
// Caret Range
//
// Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple.
// In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for
// versions 0.X >=0.1.0, and no updates for versions 0.0.X
if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) {
// Work out which position in the version we are operating at
if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) {
$position = 1;
} elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) {
$position = 2;
} else {
$position = 3;
}
// Calculate the stability suffix
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
// For upper bound, we increment the position of one more significance,
// but highPosition = 0 would be illegal
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
// X Range
//
// Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple.
// A partial version range is treated as an X-Range, so the special character is in fact optional.
if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) {
if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
$lowVersion = $this->manipulateVersionString($matches, $position) . '-dev';
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
if ($lowVersion === '0.0.0.0-dev') {
return array(new Constraint('<', $highVersion));
}
return array(
new Constraint('>=', $lowVersion),
new Constraint('<', $highVersion),
);
}
// Hyphen Range
//
// Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range,
// then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in
// the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but
// nothing that would be greater than the provided tuple parts.
if (preg_match('{^(?P<from>' . $versionRegex . ') +- +(?P<to>' . $versionRegex . ')($)}i', $constraint, $matches)) {
// Calculate the stability suffix
$lowStabilitySuffix = '';
if (empty($matches[6]) && empty($matches[8]) && empty($matches[9])) {
$lowStabilitySuffix = '-dev';
}
$lowVersion = $this->normalize($matches['from']);
$lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix);
$empty = function ($x) {
return ($x === 0 || $x === '0') ? false : empty($x);
};
if ((!$empty($matches[12]) && !$empty($matches[13])) || !empty($matches[15]) || !empty($matches[17]) || !empty($matches[18])) {
$highVersion = $this->normalize($matches['to']);
$upperBound = new Constraint('<=', $highVersion);
} else {
$highMatch = array('', $matches[11], $matches[12], $matches[13], $matches[14]);
// validate to version
$this->normalize($matches['to']);
$highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
}
return array(
$lowerBound,
$upperBound,
);
}
// Basic Comparators
if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
try {
try {
$version = $this->normalize($matches[2]);
} catch (\UnexpectedValueException $e) {
// recover from an invalid constraint like foobar-dev which should be dev-foobar
// except if the constraint uses a known operator, in which case it must be a parse error
if (substr($matches[2], -4) === '-dev' && preg_match('{^[0-9a-zA-Z-./]+$}', $matches[2])) {
$version = $this->normalize('dev-'.substr($matches[2], 0, -4));
} else {
throw $e;
}
}
$op = $matches[1] ?: '=';
if ($op !== '==' && $op !== '=' && !empty($stabilityModifier) && self::parseStability($version) === 'stable') {
$version .= '-' . $stabilityModifier;
} elseif ('<' === $op || '>=' === $op) {
if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
if (strpos($matches[2], 'dev-') !== 0) {
$version .= '-dev';
}
}
}
return array(new Constraint($matches[1] ?: '=', $version));
} catch (\Exception $e) {
}
}
$message = 'Could not parse version constraint ' . $constraint;
if (isset($e)) {
$message .= ': ' . $e->getMessage();
}
throw new \UnexpectedValueException($message);
}
/**
* Increment, decrement, or simply pad a version number.
*
* Support function for {@link parseConstraint()}
*
* @param array $matches Array with version parts in array indexes 1,2,3,4
* @param int $position 1,2,3,4 - which segment of the version to increment/decrement
* @param int $increment
* @param string $pad The string to pad version parts after $position
*
* @return string|null The new version
*
* @phpstan-param string[] $matches
*/
private function manipulateVersionString(array $matches, $position, $increment = 0, $pad = '0')
{
for ($i = 4; $i > 0; --$i) {
if ($i > $position) {
$matches[$i] = $pad;
} elseif ($i === $position && $increment) {
$matches[$i] += $increment;
// If $matches[$i] was 0, carry the decrement
if ($matches[$i] < 0) {
$matches[$i] = $pad;
--$position;
// Return null on a carry overflow
if ($i === 1) {
return null;
}
}
}
}
return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
}
/**
* Expand shorthand stability string to long version.
*
* @param string $stability
*
* @return string
*/
private function expandStability($stability)
{
$stability = strtolower($stability);
switch ($stability) {
case 'a':
return 'alpha';
case 'b':
return 'beta';
case 'p':
case 'pl':
return 'patch';
case 'rc':
return 'RC';
default:
return $stability;
}
}
}

View File

@ -1,134 +0,0 @@
## [Unreleased]
## [3.0.3] - 2022-02-25
* Added: support for composer/pcre versions 2 and 3.
## [3.0.2] - 2022-02-24
* Fixed: regression in 3.0.1 affecting Xdebug 2
## [3.0.1] - 2022-01-04
* Fixed: error when calling `isXdebugActive` before class instantiation.
## [3.0.0] - 2021-12-23
* Removed: support for legacy PHP versions (< PHP 7.2.5).
* Added: type declarations to arguments and return values.
* Added: strict typing to all classes.
## [2.0.3] - 2021-12-08
* Added: support, type annotations and refactoring for stricter PHPStan analysis.
## [2.0.2] - 2021-07-31
* Added: support for `xdebug_info('mode')` in Xdebug 3.1.
* Added: support for Psr\Log versions 2 and 3.
* Fixed: remove ini directives from non-cli HOST/PATH sections.
## [2.0.1] - 2021-05-05
* Fixed: don't restart if the cwd is a UNC path and cmd.exe will be invoked.
## [2.0.0] - 2021-04-09
* Break: this is a major release, see [UPGRADE.md](UPGRADE.md) for more information.
* Break: removed optional `$colorOption` constructor param and passthru fallback.
* Break: renamed `requiresRestart` param from `$isLoaded` to `$default`.
* Break: changed `restart` param `$command` from a string to an array.
* Added: support for Xdebug3 to only restart if Xdebug is not running with `xdebug.mode=off`.
* Added: `isXdebugActive()` method to determine if Xdebug is still running in the restart.
* Added: feature to bypass the shell in PHP-7.4+ by giving `proc_open` an array of arguments.
* Added: Process utility class to the API.
## [1.4.6] - 2021-03-25
* Fixed: fail restart if `proc_open` has been disabled in `disable_functions`.
* Fixed: enable Windows CTRL event handling in the restarted process.
## [1.4.5] - 2020-11-13
* Fixed: use `proc_open` when available for correct FD forwarding to the restarted process.
## [1.4.4] - 2020-10-24
* Fixed: exception if 'pcntl_signal' is disabled.
## [1.4.3] - 2020-08-19
* Fixed: restore SIGINT to default handler in restarted process if no other handler exists.
## [1.4.2] - 2020-06-04
* Fixed: ignore SIGINTs to let the restarted process handle them.
## [1.4.1] - 2020-03-01
* Fixed: restart fails if an ini file is empty.
## [1.4.0] - 2019-11-06
* Added: support for `NO_COLOR` environment variable: https://no-color.org
* Added: color support for Hyper terminal: https://github.com/zeit/hyper
* Fixed: correct capitalization of Xdebug (apparently).
* Fixed: improved handling for uopz extension.
## [1.3.3] - 2019-05-27
* Fixed: add environment changes to `$_ENV` if it is being used.
## [1.3.2] - 2019-01-28
* Fixed: exit call being blocked by uopz extension, resulting in application code running twice.
## [1.3.1] - 2018-11-29
* Fixed: fail restart if `passthru` has been disabled in `disable_functions`.
* Fixed: fail restart if an ini file cannot be opened, otherwise settings will be missing.
## [1.3.0] - 2018-08-31
* Added: `setPersistent` method to use environment variables for the restart.
* Fixed: improved debugging by writing output to stderr.
* Fixed: no restart when `php_ini_scanned_files` is not functional and is needed.
## [1.2.1] - 2018-08-23
* Fixed: fatal error with apc, when using `apc.mmap_file_mask`.
## [1.2.0] - 2018-08-16
* Added: debug information using `XDEBUG_HANDLER_DEBUG`.
* Added: fluent interface for setters.
* Added: `PhpConfig` helper class for calling PHP sub-processes.
* Added: `PHPRC` original value to restart stettings, for use in a restarted process.
* Changed: internal procedure to disable ini-scanning, using `-n` command-line option.
* Fixed: replaced `escapeshellarg` usage to avoid locale problems.
* Fixed: improved color-option handling to respect double-dash delimiter.
* Fixed: color-option handling regression from main script changes.
* Fixed: improved handling when checking main script.
* Fixed: handling for standard input, that never actually did anything.
* Fixed: fatal error when ctype extension is not available.
## [1.1.0] - 2018-04-11
* Added: `getRestartSettings` method for calling PHP processes in a restarted process.
* Added: API definition and @internal class annotations.
* Added: protected `requiresRestart` method for extending classes.
* Added: `setMainScript` method for applications that change the working directory.
* Changed: private `tmpIni` variable to protected for extending classes.
* Fixed: environment variables not available in $_SERVER when restored in the restart.
* Fixed: relative path problems caused by Phar::interceptFileFuncs.
* Fixed: incorrect handling when script file cannot be found.
## [1.0.0] - 2018-03-08
* Added: PSR3 logging for optional status output.
* Added: existing ini settings are merged to catch command-line overrides.
* Added: code, tests and other artefacts to decouple from Composer.
* Break: the following class was renamed:
- `Composer\XdebugHandler` -> `Composer\XdebugHandler\XdebugHandler`
[Unreleased]: https://github.com/composer/xdebug-handler/compare/3.0.3...HEAD
[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.2...3.0.3
[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.1...3.0.2
[3.0.1]: https://github.com/composer/xdebug-handler/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/composer/xdebug-handler/compare/2.0.3...3.0.0
[2.0.3]: https://github.com/composer/xdebug-handler/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/composer/xdebug-handler/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/composer/xdebug-handler/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/composer/xdebug-handler/compare/1.4.6...2.0.0
[1.4.6]: https://github.com/composer/xdebug-handler/compare/1.4.5...1.4.6
[1.4.5]: https://github.com/composer/xdebug-handler/compare/1.4.4...1.4.5
[1.4.4]: https://github.com/composer/xdebug-handler/compare/1.4.3...1.4.4
[1.4.3]: https://github.com/composer/xdebug-handler/compare/1.4.2...1.4.3
[1.4.2]: https://github.com/composer/xdebug-handler/compare/1.4.1...1.4.2
[1.4.1]: https://github.com/composer/xdebug-handler/compare/1.4.0...1.4.1
[1.4.0]: https://github.com/composer/xdebug-handler/compare/1.3.3...1.4.0
[1.3.3]: https://github.com/composer/xdebug-handler/compare/1.3.2...1.3.3
[1.3.2]: https://github.com/composer/xdebug-handler/compare/1.3.1...1.3.2
[1.3.1]: https://github.com/composer/xdebug-handler/compare/1.3.0...1.3.1
[1.3.0]: https://github.com/composer/xdebug-handler/compare/1.2.1...1.3.0
[1.2.1]: https://github.com/composer/xdebug-handler/compare/1.2.0...1.2.1
[1.2.0]: https://github.com/composer/xdebug-handler/compare/1.1.0...1.2.0
[1.1.0]: https://github.com/composer/xdebug-handler/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/composer/xdebug-handler/compare/d66f0d15cb57...1.0.0

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 Composer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,298 +0,0 @@
# composer/xdebug-handler
[![packagist](https://img.shields.io/packagist/v/composer/xdebug-handler)](https://packagist.org/packages/composer/xdebug-handler)
[![Continuous Integration](https://github.com/composer/xdebug-handler/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/xdebug-handler/actions?query=branch:main)
![license](https://img.shields.io/github/license/composer/xdebug-handler.svg)
![php](https://img.shields.io/packagist/php-v/composer/xdebug-handler?colorB=8892BF)
Restart a CLI process without loading the Xdebug extension, unless `xdebug.mode=off`.
Originally written as part of [composer/composer](https://github.com/composer/composer),
now extracted and made available as a stand-alone library.
### Version 3
Removed support for legacy PHP versions and added type declarations.
Long term support for version 2 (PHP 5.3.2 - 7.2.4) follows [Composer 2.2 LTS](https://blog.packagist.com/composer-2-2/) policy.
## Installation
Install the latest version with:
```bash
$ composer require composer/xdebug-handler
```
## Requirements
* PHP 7.2.5 minimum, although using the latest PHP version is highly recommended.
## Basic Usage
```php
use Composer\XdebugHandler\XdebugHandler;
$xdebug = new XdebugHandler('myapp');
$xdebug->check();
unset($xdebug);
```
The constructor takes a single parameter, `$envPrefix`, which is upper-cased and prepended to default base values to create two distinct environment variables. The above example enables the use of:
- `MYAPP_ALLOW_XDEBUG=1` to override automatic restart and allow Xdebug
- `MYAPP_ORIGINAL_INIS` to obtain ini file locations in a restarted process
## Advanced Usage
* [How it works](#how-it-works)
* [Limitations](#limitations)
* [Helper methods](#helper-methods)
* [Setter methods](#setter-methods)
* [Process configuration](#process-configuration)
* [Troubleshooting](#troubleshooting)
* [Extending the library](#extending-the-library)
### How it works
A temporary ini file is created from the loaded (and scanned) ini files, with any references to the Xdebug extension commented out. Current ini settings are merged, so that most ini settings made on the command-line or by the application are included (see [Limitations](#limitations))
* `MYAPP_ALLOW_XDEBUG` is set with internal data to flag and use in the restart.
* The command-line and environment are [configured](#process-configuration) for the restart.
* The application is restarted in a new process.
* The restart settings are stored in the environment.
* `MYAPP_ALLOW_XDEBUG` is unset.
* The application runs and exits.
* The main process exits with the exit code from the restarted process.
#### Signal handling
Asynchronous signal handling is automatically enabled if the pcntl extension is loaded. `SIGINT` is set to `SIG_IGN` in the parent
process and restored to `SIG_DFL` in the restarted process (if no other handler has been set).
From PHP 7.4 on Windows, `CTRL+C` and `CTRL+BREAK` handling is automatically enabled in the restarted process and ignored in the parent process.
### Limitations
There are a few things to be aware of when running inside a restarted process.
* Extensions set on the command-line will not be loaded.
* Ini file locations will be reported as per the restart - see [getAllIniFiles()](#getallinifiles).
* Php sub-processes may be loaded with Xdebug enabled - see [Process configuration](#process-configuration).
### Helper methods
These static methods provide information from the current process, regardless of whether it has been restarted or not.
#### _getAllIniFiles(): array_
Returns an array of the original ini file locations. Use this instead of calling `php_ini_loaded_file` and `php_ini_scanned_files`, which will report the wrong values in a restarted process.
```php
use Composer\XdebugHandler\XdebugHandler;
$files = XdebugHandler::getAllIniFiles();
# $files[0] always exists, it could be an empty string
$loadedIni = array_shift($files);
$scannedInis = $files;
```
These locations are also available in the `MYAPP_ORIGINAL_INIS` environment variable. This is a path-separated string comprising the location returned from `php_ini_loaded_file`, which could be empty, followed by locations parsed from calling `php_ini_scanned_files`.
#### _getRestartSettings(): ?array_
Returns an array of settings that can be used with PHP [sub-processes](#sub-processes), or null if the process was not restarted.
```php
use Composer\XdebugHandler\XdebugHandler;
$settings = XdebugHandler::getRestartSettings();
/**
* $settings: array (if the current process was restarted,
* or called with the settings from a previous restart), or null
*
* 'tmpIni' => the temporary ini file used in the restart (string)
* 'scannedInis' => if there were any scanned inis (bool)
* 'scanDir' => the original PHP_INI_SCAN_DIR value (false|string)
* 'phprc' => the original PHPRC value (false|string)
* 'inis' => the original inis from getAllIniFiles (array)
* 'skipped' => the skipped version from getSkippedVersion (string)
*/
```
#### _getSkippedVersion(): string_
Returns the Xdebug version string that was skipped by the restart, or an empty string if there was no restart (or Xdebug is still loaded, perhaps by an extending class restarting for a reason other than removing Xdebug).
```php
use Composer\XdebugHandler\XdebugHandler;
$version = XdebugHandler::getSkippedVersion();
# $version: '3.1.1' (for example), or an empty string
```
#### _isXdebugActive(): bool_
Returns true if Xdebug is loaded and is running in an active mode (if it supports modes). Returns false if Xdebug is not loaded, or it is running with `xdebug.mode=off`.
### Setter methods
These methods implement a fluent interface and must be called before the main `check()` method.
#### _setLogger(LoggerInterface $logger): self_
Enables the output of status messages to an external PSR3 logger. All messages are reported with either `DEBUG` or `WARNING` log levels. For example (showing the level and message):
```
// No restart
DEBUG Checking MYAPP_ALLOW_XDEBUG
DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=off
DEBUG No restart (APP_ALLOW_XDEBUG=0) Allowed by xdebug.mode
// Restart overridden
DEBUG Checking MYAPP_ALLOW_XDEBUG
DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=coverage,debug,develop
DEBUG No restart (MYAPP_ALLOW_XDEBUG=1)
// Failed restart
DEBUG Checking MYAPP_ALLOW_XDEBUG
DEBUG The Xdebug extension is loaded (3.1.0)
WARNING No restart (Unable to create temp ini file at: ...)
```
Status messages can also be output with `XDEBUG_HANDLER_DEBUG`. See [Troubleshooting](#troubleshooting).
#### _setMainScript(string $script): self_
Sets the location of the main script to run in the restart. This is only needed in more esoteric use-cases, or if the `argv[0]` location is inaccessible. The script name `--` is supported for standard input.
#### _setPersistent(): self_
Configures the restart using [persistent settings](#persistent-settings), so that Xdebug is not loaded in any sub-process.
Use this method if your application invokes one or more PHP sub-process and the Xdebug extension is not needed. This avoids the overhead of implementing specific [sub-process](#sub-processes) strategies.
Alternatively, this method can be used to set up a default _Xdebug-free_ environment which can be changed if a sub-process requires Xdebug, then restored afterwards:
```php
function SubProcessWithXdebug()
{
$phpConfig = new Composer\XdebugHandler\PhpConfig();
# Set the environment to the original configuration
$phpConfig->useOriginal();
# run the process with Xdebug loaded
...
# Restore Xdebug-free environment
$phpConfig->usePersistent();
}
```
### Process configuration
The library offers two strategies to invoke a new PHP process without loading Xdebug, using either _standard_ or _persistent_ settings. Note that this is only important if the application calls a PHP sub-process.
#### Standard settings
Uses command-line options to remove Xdebug from the new process only.
* The -n option is added to the command-line. This tells PHP not to scan for additional inis.
* The temporary ini is added to the command-line with the -c option.
>_If the new process calls a PHP sub-process, Xdebug will be loaded in that sub-process (unless it implements xdebug-handler, in which case there will be another restart)._
This is the default strategy used in the restart.
#### Persistent settings
Uses environment variables to remove Xdebug from the new process and persist these settings to any sub-process.
* `PHP_INI_SCAN_DIR` is set to an empty string. This tells PHP not to scan for additional inis.
* `PHPRC` is set to the temporary ini.
>_If the new process calls a PHP sub-process, Xdebug will not be loaded in that sub-process._
This strategy can be used in the restart by calling [setPersistent()](#setpersistent).
#### Sub-processes
The `PhpConfig` helper class makes it easy to invoke a PHP sub-process (with or without Xdebug loaded), regardless of whether there has been a restart.
Each of its methods returns an array of PHP options (to add to the command-line) and sets up the environment for the required strategy. The [getRestartSettings()](#getrestartsettings) method is used internally.
* `useOriginal()` - Xdebug will be loaded in the new process.
* `useStandard()` - Xdebug will **not** be loaded in the new process - see [standard settings](#standard-settings).
* `userPersistent()` - Xdebug will **not** be loaded in the new process - see [persistent settings](#persistent-settings)
If there was no restart, an empty options array is returned and the environment is not changed.
```php
use Composer\XdebugHandler\PhpConfig;
$config = new PhpConfig;
$options = $config->useOriginal();
# $options: empty array
# environment: PHPRC and PHP_INI_SCAN_DIR set to original values
$options = $config->useStandard();
# $options: [-n, -c, tmpIni]
# environment: PHPRC and PHP_INI_SCAN_DIR set to original values
$options = $config->usePersistent();
# $options: empty array
# environment: PHPRC=tmpIni, PHP_INI_SCAN_DIR=''
```
### Troubleshooting
The following environment settings can be used to troubleshoot unexpected behavior:
* `XDEBUG_HANDLER_DEBUG=1` Outputs status messages to `STDERR`, if it is defined, irrespective of any PSR3 logger. Each message is prefixed `xdebug-handler[pid]`, where pid is the process identifier.
* `XDEBUG_HANDLER_DEBUG=2` As above, but additionally saves the temporary ini file and reports its location in a status message.
### Extending the library
The API is defined by classes and their accessible elements that are not annotated as @internal. The main class has two protected methods that can be overridden to provide additional functionality:
#### _requiresRestart(bool $default): bool_
By default the process will restart if Xdebug is loaded and not running with `xdebug.mode=off`. Extending this method allows an application to decide, by returning a boolean (or equivalent) value.
It is only called if `MYAPP_ALLOW_XDEBUG` is empty, so it will not be called in the restarted process (where this variable contains internal data), or if the restart has been overridden.
Note that the [setMainScript()](#setmainscriptscript) and [setPersistent()](#setpersistent) setters can be used here, if required.
#### _restart(array $command): void_
An application can extend this to modify the temporary ini file, its location given in the `tmpIni` property. New settings can be safely appended to the end of the data, which is `PHP_EOL` terminated.
The `$command` parameter is an array of unescaped command-line arguments that will be used for the new process.
Remember to finish with `parent::restart($command)`.
#### Example
This example demonstrates two ways to extend basic functionality:
* To avoid the overhead of spinning up a new process, the restart is skipped if a simple help command is requested.
* The application needs write-access to phar files, so it will force a restart if `phar.readonly` is set (regardless of whether Xdebug is loaded) and change this value in the temporary ini file.
```php
use Composer\XdebugHandler\XdebugHandler;
use MyApp\Command;
class MyRestarter extends XdebugHandler
{
private $required;
protected function requiresRestart(bool $default): bool
{
if (Command::isHelp()) {
# No need to disable Xdebug for this
return false;
}
$this->required = (bool) ini_get('phar.readonly');
return $this->required || $default;
}
protected function restart(array $command): void
{
if ($this->required) {
# Add required ini setting to tmpIni
$content = file_get_contents($this->tmpIni);
$content .= 'phar.readonly=0'.PHP_EOL;
file_put_contents($this->tmpIni, $content);
}
parent::restart($command);
}
}
```
## License
composer/xdebug-handler is licensed under the MIT License, see the LICENSE file for details.

View File

@ -1,44 +0,0 @@
{
"name": "composer/xdebug-handler",
"description": "Restarts a process without Xdebug.",
"type": "library",
"license": "MIT",
"keywords": [
"xdebug",
"performance"
],
"authors": [
{
"name": "John Stevenson",
"email": "john-stevenson@blueyonder.co.uk"
}
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/xdebug-handler/issues"
},
"require": {
"php": "^7.2.5 || ^8.0",
"psr/log": "^1 || ^2 || ^3",
"composer/pcre": "^1 || ^2 || ^3"
},
"require-dev": {
"symfony/phpunit-bridge": "^6.0",
"phpstan/phpstan": "^1.0",
"phpstan/phpstan-strict-rules": "^1.1"
},
"autoload": {
"psr-4": {
"Composer\\XdebugHandler\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Composer\\XdebugHandler\\Tests\\": "tests"
}
},
"scripts": {
"test": "@php vendor/bin/simple-phpunit",
"phpstan": "@php vendor/bin/phpstan analyse"
}
}

View File

@ -1,91 +0,0 @@
<?php
declare(strict_types=1);
/*
* This file is part of composer/xdebug-handler.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\XdebugHandler;
/**
* @author John Stevenson <john-stevenson@blueyonder.co.uk>
*
* @phpstan-type restartData array{tmpIni: string, scannedInis: bool, scanDir: false|string, phprc: false|string, inis: string[], skipped: string}
*/
class PhpConfig
{
/**
* Use the original PHP configuration
*
* @return string[] Empty array of PHP cli options
*/
public function useOriginal(): array
{
$this->getDataAndReset();
return [];
}
/**
* Use standard restart settings
*
* @return string[] PHP cli options
*/
public function useStandard(): array
{
$data = $this->getDataAndReset();
if ($data !== null) {
return ['-n', '-c', $data['tmpIni']];
}
return [];
}
/**
* Use environment variables to persist settings
*
* @return string[] Empty array of PHP cli options
*/
public function usePersistent(): array
{
$data = $this->getDataAndReset();
if ($data !== null) {
$this->updateEnv('PHPRC', $data['tmpIni']);
$this->updateEnv('PHP_INI_SCAN_DIR', '');
}
return [];
}
/**
* Returns restart data if available and resets the environment
*
* @phpstan-return restartData|null
*/
private function getDataAndReset(): ?array
{
$data = XdebugHandler::getRestartSettings();
if ($data !== null) {
$this->updateEnv('PHPRC', $data['phprc']);
$this->updateEnv('PHP_INI_SCAN_DIR', $data['scanDir']);
}
return $data;
}
/**
* Updates a restart settings value in the environment
*
* @param string $name
* @param string|false $value
*/
private function updateEnv(string $name, $value): void
{
Process::setEnv($name, false !== $value ? $value : null);
}
}

View File

@ -1,118 +0,0 @@
<?php
/*
* This file is part of composer/xdebug-handler.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Composer\XdebugHandler;
use Composer\Pcre\Preg;
/**
* Process utility functions
*
* @author John Stevenson <john-stevenson@blueyonder.co.uk>
*/
class Process
{
/**
* Escapes a string to be used as a shell argument.
*
* From https://github.com/johnstevenson/winbox-args
* MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
*
* @param string $arg The argument to be escaped
* @param bool $meta Additionally escape cmd.exe meta characters
* @param bool $module The argument is the module to invoke
*/
public static function escape(string $arg, bool $meta = true, bool $module = false): string
{
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
return "'".str_replace("'", "'\\''", $arg)."'";
}
$quote = strpbrk($arg, " \t") !== false || $arg === '';
$arg = Preg::replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
if ($meta) {
$meta = $dquotes || Preg::isMatch('/%[^%]+%/', $arg);
if (!$meta) {
$quote = $quote || strpbrk($arg, '^&|<>()') !== false;
} elseif ($module && !$dquotes && $quote) {
$meta = false;
}
}
if ($quote) {
$arg = '"'.(Preg::replace('/(\\\\*)$/', '$1$1', $arg)).'"';
}
if ($meta) {
$arg = Preg::replace('/(["^&|<>()%])/', '^$1', $arg);
}
return $arg;
}
/**
* Escapes an array of arguments that make up a shell command
*
* @param string[] $args Argument list, with the module name first
*/
public static function escapeShellCommand(array $args): string
{
$command = '';
$module = array_shift($args);
if ($module !== null) {
$command = self::escape($module, true, true);
foreach ($args as $arg) {
$command .= ' '.self::escape($arg);
}
}
return $command;
}
/**
* Makes putenv environment changes available in $_SERVER and $_ENV
*
* @param string $name
* @param ?string $value A null value unsets the variable
*/
public static function setEnv(string $name, ?string $value = null): bool
{
$unset = null === $value;
if (!putenv($unset ? $name : $name.'='.$value)) {
return false;
}
if ($unset) {
unset($_SERVER[$name]);
} else {
$_SERVER[$name] = $value;
}
// Update $_ENV if it is being used
if (false !== stripos((string) ini_get('variables_order'), 'E')) {
if ($unset) {
unset($_ENV[$name]);
} else {
$_ENV[$name] = $value;
}
}
return true;
}
}

View File

@ -1,203 +0,0 @@
<?php
/*
* This file is part of composer/xdebug-handler.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Composer\XdebugHandler;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* @author John Stevenson <john-stevenson@blueyonder.co.uk>
* @internal
*/
class Status
{
const ENV_RESTART = 'XDEBUG_HANDLER_RESTART';
const CHECK = 'Check';
const ERROR = 'Error';
const INFO = 'Info';
const NORESTART = 'NoRestart';
const RESTART = 'Restart';
const RESTARTING = 'Restarting';
const RESTARTED = 'Restarted';
/** @var bool */
private $debug;
/** @var string */
private $envAllowXdebug;
/** @var string|null */
private $loaded;
/** @var LoggerInterface|null */
private $logger;
/** @var bool */
private $modeOff;
/** @var float */
private $time;
/**
* @param string $envAllowXdebug Prefixed _ALLOW_XDEBUG name
* @param bool $debug Whether debug output is required
*/
public function __construct(string $envAllowXdebug, bool $debug)
{
$start = getenv(self::ENV_RESTART);
Process::setEnv(self::ENV_RESTART);
$this->time = is_numeric($start) ? round((microtime(true) - $start) * 1000) : 0;
$this->envAllowXdebug = $envAllowXdebug;
$this->debug = $debug && defined('STDERR');
$this->modeOff = false;
}
/**
* Activates status message output to a PSR3 logger
*
* @return void
*/
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
/**
* Calls a handler method to report a message
*
* @throws \InvalidArgumentException If $op is not known
*/
public function report(string $op, ?string $data): void
{
if ($this->logger !== null || $this->debug) {
$callable = [$this, 'report'.$op];
if (!is_callable($callable)) {
throw new \InvalidArgumentException('Unknown op handler: '.$op);
}
$params = $data !== null ? [$data] : [];
call_user_func_array($callable, $params);
}
}
/**
* Outputs a status message
*/
private function output(string $text, ?string $level = null): void
{
if ($this->logger !== null) {
$this->logger->log($level !== null ? $level: LogLevel::DEBUG, $text);
}
if ($this->debug) {
fwrite(STDERR, sprintf('xdebug-handler[%d] %s', getmypid(), $text.PHP_EOL));
}
}
/**
* Checking status message
*/
private function reportCheck(string $loaded): void
{
list($version, $mode) = explode('|', $loaded);
if ($version !== '') {
$this->loaded = '('.$version.')'.($mode !== '' ? ' xdebug.mode='.$mode : '');
}
$this->modeOff = $mode === 'off';
$this->output('Checking '.$this->envAllowXdebug);
}
/**
* Error status message
*/
private function reportError(string $error): void
{
$this->output(sprintf('No restart (%s)', $error), LogLevel::WARNING);
}
/**
* Info status message
*/
private function reportInfo(string $info): void
{
$this->output($info);
}
/**
* No restart status message
*/
private function reportNoRestart(): void
{
$this->output($this->getLoadedMessage());
if ($this->loaded !== null) {
$text = sprintf('No restart (%s)', $this->getEnvAllow());
if (!((bool) getenv($this->envAllowXdebug))) {
$text .= ' Allowed by '.($this->modeOff ? 'xdebug.mode' : 'application');
}
$this->output($text);
}
}
/**
* Restart status message
*/
private function reportRestart(): void
{
$this->output($this->getLoadedMessage());
Process::setEnv(self::ENV_RESTART, (string) microtime(true));
}
/**
* Restarted status message
*/
private function reportRestarted(): void
{
$loaded = $this->getLoadedMessage();
$text = sprintf('Restarted (%d ms). %s', $this->time, $loaded);
$level = $this->loaded !== null ? LogLevel::WARNING : null;
$this->output($text, $level);
}
/**
* Restarting status message
*/
private function reportRestarting(string $command): void
{
$text = sprintf('Process restarting (%s)', $this->getEnvAllow());
$this->output($text);
$text = 'Running '.$command;
$this->output($text);
}
/**
* Returns the _ALLOW_XDEBUG environment variable as name=value
*/
private function getEnvAllow(): string
{
return $this->envAllowXdebug.'='.getenv($this->envAllowXdebug);
}
/**
* Returns the Xdebug status and version
*/
private function getLoadedMessage(): string
{
$loaded = $this->loaded !== null ? sprintf('loaded %s', $this->loaded) : 'not loaded';
return 'The Xdebug extension is '.$loaded;
}
}

View File

@ -1,668 +0,0 @@
<?php
/*
* This file is part of composer/xdebug-handler.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Composer\XdebugHandler;
use Composer\Pcre\Preg;
use Psr\Log\LoggerInterface;
/**
* @author John Stevenson <john-stevenson@blueyonder.co.uk>
*
* @phpstan-import-type restartData from PhpConfig
*/
class XdebugHandler
{
const SUFFIX_ALLOW = '_ALLOW_XDEBUG';
const SUFFIX_INIS = '_ORIGINAL_INIS';
const RESTART_ID = 'internal';
const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS';
const DEBUG = 'XDEBUG_HANDLER_DEBUG';
/** @var string|null */
protected $tmpIni;
/** @var bool */
private static $inRestart;
/** @var string */
private static $name;
/** @var string|null */
private static $skipped;
/** @var bool */
private static $xdebugActive;
/** @var string|null */
private static $xdebugMode;
/** @var string|null */
private static $xdebugVersion;
/** @var bool */
private $cli;
/** @var string|null */
private $debug;
/** @var string */
private $envAllowXdebug;
/** @var string */
private $envOriginalInis;
/** @var bool */
private $persistent;
/** @var string|null */
private $script;
/** @var Status */
private $statusWriter;
/**
* Constructor
*
* The $envPrefix is used to create distinct environment variables. It is
* uppercased and prepended to the default base values. For example 'myapp'
* would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS.
*
* @param string $envPrefix Value used in environment variables
* @throws \RuntimeException If the parameter is invalid
*/
public function __construct(string $envPrefix)
{
if ($envPrefix === '') {
throw new \RuntimeException('Invalid constructor parameter');
}
self::$name = strtoupper($envPrefix);
$this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW;
$this->envOriginalInis = self::$name.self::SUFFIX_INIS;
self::setXdebugDetails();
self::$inRestart = false;
if ($this->cli = PHP_SAPI === 'cli') {
$this->debug = (string) getenv(self::DEBUG);
}
$this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug);
}
/**
* Activates status message output to a PSR3 logger
*/
public function setLogger(LoggerInterface $logger): self
{
$this->statusWriter->setLogger($logger);
return $this;
}
/**
* Sets the main script location if it cannot be called from argv
*/
public function setMainScript(string $script): self
{
$this->script = $script;
return $this;
}
/**
* Persist the settings to keep Xdebug out of sub-processes
*/
public function setPersistent(): self
{
$this->persistent = true;
return $this;
}
/**
* Checks if Xdebug is loaded and the process needs to be restarted
*
* This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG
* environment variable to 1. This variable is used internally so that
* the restarted process is created only once.
*/
public function check(): void
{
$this->notify(Status::CHECK, self::$xdebugVersion.'|'.self::$xdebugMode);
$envArgs = explode('|', (string) getenv($this->envAllowXdebug));
if (!((bool) $envArgs[0]) && $this->requiresRestart(self::$xdebugActive)) {
// Restart required
$this->notify(Status::RESTART);
if ($this->prepareRestart()) {
$command = $this->getCommand();
$this->restart($command);
}
return;
}
if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) {
// Restarted, so unset environment variable and use saved values
$this->notify(Status::RESTARTED);
Process::setEnv($this->envAllowXdebug);
self::$inRestart = true;
if (self::$xdebugVersion === null) {
// Skipped version is only set if Xdebug is not loaded
self::$skipped = $envArgs[1];
}
$this->tryEnableSignals();
// Put restart settings in the environment
$this->setEnvRestartSettings($envArgs);
return;
}
$this->notify(Status::NORESTART);
$settings = self::getRestartSettings();
if ($settings !== null) {
// Called with existing settings, so sync our settings
$this->syncSettings($settings);
}
}
/**
* Returns an array of php.ini locations with at least one entry
*
* The equivalent of calling php_ini_loaded_file then php_ini_scanned_files.
* The loaded ini location is the first entry and may be empty.
*
* @return string[]
*/
public static function getAllIniFiles(): array
{
if (self::$name !== null) {
$env = getenv(self::$name.self::SUFFIX_INIS);
if (false !== $env) {
return explode(PATH_SEPARATOR, $env);
}
}
$paths = [(string) php_ini_loaded_file()];
$scanned = php_ini_scanned_files();
if ($scanned !== false) {
$paths = array_merge($paths, array_map('trim', explode(',', $scanned)));
}
return $paths;
}
/**
* Returns an array of restart settings or null
*
* Settings will be available if the current process was restarted, or
* called with the settings from an existing restart.
*
* @phpstan-return restartData|null
*/
public static function getRestartSettings(): ?array
{
$envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS));
if (count($envArgs) !== 6
|| (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) {
return null;
}
return [
'tmpIni' => $envArgs[0],
'scannedInis' => (bool) $envArgs[1],
'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2],
'phprc' => '*' === $envArgs[3] ? false : $envArgs[3],
'inis' => explode(PATH_SEPARATOR, $envArgs[4]),
'skipped' => $envArgs[5],
];
}
/**
* Returns the Xdebug version that triggered a successful restart
*/
public static function getSkippedVersion(): string
{
return (string) self::$skipped;
}
/**
* Returns whether Xdebug is loaded and active
*
* true: if Xdebug is loaded and is running in an active mode.
* false: if Xdebug is not loaded, or it is running with xdebug.mode=off.
*/
public static function isXdebugActive(): bool
{
self::setXdebugDetails();
return self::$xdebugActive;
}
/**
* Allows an extending class to decide if there should be a restart
*
* The default is to restart if Xdebug is loaded and its mode is not "off".
*/
protected function requiresRestart(bool $default): bool
{
return $default;
}
/**
* Allows an extending class to access the tmpIni
*
* @param string[] $command *
*/
protected function restart(array $command): void
{
$this->doRestart($command);
}
/**
* Executes the restarted command then deletes the tmp ini
*
* @param string[] $command
* @phpstan-return never
*/
private function doRestart(array $command): void
{
$this->tryEnableSignals();
$this->notify(Status::RESTARTING, implode(' ', $command));
if (PHP_VERSION_ID >= 70400) {
$cmd = $command;
} else {
$cmd = Process::escapeShellCommand($command);
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
// Outer quotes required on cmd string below PHP 8
$cmd = '"'.$cmd.'"';
}
}
$process = proc_open($cmd, [], $pipes);
if (is_resource($process)) {
$exitCode = proc_close($process);
}
if (!isset($exitCode)) {
// Unlikely that php or the default shell cannot be invoked
$this->notify(Status::ERROR, 'Unable to restart process');
$exitCode = -1;
} else {
$this->notify(Status::INFO, 'Restarted process exited '.$exitCode);
}
if ($this->debug === '2') {
$this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni);
} else {
@unlink((string) $this->tmpIni);
}
exit($exitCode);
}
/**
* Returns true if everything was written for the restart
*
* If any of the following fails (however unlikely) we must return false to
* stop potential recursion:
* - tmp ini file creation
* - environment variable creation
*/
private function prepareRestart(): bool
{
$error = null;
$iniFiles = self::getAllIniFiles();
$scannedInis = count($iniFiles) > 1;
$tmpDir = sys_get_temp_dir();
if (!$this->cli) {
$error = 'Unsupported SAPI: '.PHP_SAPI;
} elseif (!$this->checkConfiguration($info)) {
$error = $info;
} elseif (!$this->checkMainScript()) {
$error = 'Unable to access main script: '.$this->script;
} elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) {
$error = $error !== null ? $error : 'Unable to create temp ini file at: '.$tmpDir;
} elseif (!$this->setEnvironment($scannedInis, $iniFiles)) {
$error = 'Unable to set environment variables';
}
if ($error !== null) {
$this->notify(Status::ERROR, $error);
}
return $error === null;
}
/**
* Returns true if the tmp ini file was written
*
* @param string[] $iniFiles All ini files used in the current process
*/
private function writeTmpIni(array $iniFiles, string $tmpDir, ?string &$error): bool
{
if (($tmpfile = @tempnam($tmpDir, '')) === false) {
return false;
}
$this->tmpIni = $tmpfile;
// $iniFiles has at least one item and it may be empty
if ($iniFiles[0] === '') {
array_shift($iniFiles);
}
$content = '';
$sectionRegex = '/^\s*\[(?:PATH|HOST)\s*=/mi';
$xdebugRegex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
foreach ($iniFiles as $file) {
// Check for inaccessible ini files
if (($data = @file_get_contents($file)) === false) {
$error = 'Unable to read ini: '.$file;
return false;
}
// Check and remove directives after HOST and PATH sections
if (Preg::isMatchWithOffsets($sectionRegex, $data, $matches, PREG_OFFSET_CAPTURE)) {
$data = substr($data, 0, $matches[0][1]);
}
$content .= Preg::replace($xdebugRegex, ';$1', $data).PHP_EOL;
}
// Merge loaded settings into our ini content, if it is valid
$config = parse_ini_string($content);
$loaded = ini_get_all(null, false);
if (false === $config || false === $loaded) {
$error = 'Unable to parse ini data';
return false;
}
$content .= $this->mergeLoadedConfig($loaded, $config);
// Work-around for https://bugs.php.net/bug.php?id=75932
$content .= 'opcache.enable_cli=0'.PHP_EOL;
return (bool) @file_put_contents($this->tmpIni, $content);
}
/**
* Returns the command line arguments for the restart
*
* @return string[]
*/
private function getCommand(): array
{
$php = [PHP_BINARY];
$args = array_slice($_SERVER['argv'], 1);
if (!$this->persistent) {
// Use command-line options
array_push($php, '-n', '-c', $this->tmpIni);
}
return array_merge($php, [$this->script], $args);
}
/**
* Returns true if the restart environment variables were set
*
* No need to update $_SERVER since this is set in the restarted process.
*
* @param string[] $iniFiles All ini files used in the current process
*/
private function setEnvironment(bool $scannedInis, array $iniFiles): bool
{
$scanDir = getenv('PHP_INI_SCAN_DIR');
$phprc = getenv('PHPRC');
// Make original inis available to restarted process
if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) {
return false;
}
if ($this->persistent) {
// Use the environment to persist the settings
if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$this->tmpIni)) {
return false;
}
}
// Flag restarted process and save values for it to use
$envArgs = [
self::RESTART_ID,
self::$xdebugVersion,
(int) $scannedInis,
false === $scanDir ? '*' : $scanDir,
false === $phprc ? '*' : $phprc,
];
return putenv($this->envAllowXdebug.'='.implode('|', $envArgs));
}
/**
* Logs status messages
*/
private function notify(string $op, ?string $data = null): void
{
$this->statusWriter->report($op, $data);
}
/**
* Returns default, changed and command-line ini settings
*
* @param mixed[] $loadedConfig All current ini settings
* @param mixed[] $iniConfig Settings from user ini files
*
*/
private function mergeLoadedConfig(array $loadedConfig, array $iniConfig): string
{
$content = '';
foreach ($loadedConfig as $name => $value) {
// Value will either be null, string or array (HHVM only)
if (!is_string($value)
|| strpos($name, 'xdebug') === 0
|| $name === 'apc.mmap_file_mask') {
continue;
}
if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) {
// Double-quote escape each value
$content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL;
}
}
return $content;
}
/**
* Returns true if the script name can be used
*/
private function checkMainScript(): bool
{
if ($this->script !== null) {
// Allow an application to set -- for standard input
return file_exists($this->script) || '--' === $this->script;
}
if (file_exists($this->script = $_SERVER['argv'][0])) {
return true;
}
// Use a backtrace to resolve Phar and chdir issues.
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$main = end($trace);
if ($main !== false && isset($main['file'])) {
return file_exists($this->script = $main['file']);
}
return false;
}
/**
* Adds restart settings to the environment
*
* @param string[] $envArgs
*/
private function setEnvRestartSettings(array $envArgs): void
{
$settings = [
php_ini_loaded_file(),
$envArgs[2],
$envArgs[3],
$envArgs[4],
getenv($this->envOriginalInis),
self::$skipped,
];
Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings));
}
/**
* Syncs settings and the environment if called with existing settings
*
* @phpstan-param restartData $settings
*/
private function syncSettings(array $settings): void
{
if (false === getenv($this->envOriginalInis)) {
// Called by another app, so make original inis available
Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis']));
}
self::$skipped = $settings['skipped'];
$this->notify(Status::INFO, 'Process called with existing restart settings');
}
/**
* Returns true if there are no known configuration issues
*/
private function checkConfiguration(?string &$info): bool
{
if (!function_exists('proc_open')) {
$info = 'proc_open function is disabled';
return false;
}
if (extension_loaded('uopz') && !((bool) ini_get('uopz.disable'))) {
// uopz works at opcode level and disables exit calls
if (function_exists('uopz_allow_exit')) {
@uopz_allow_exit(true);
} else {
$info = 'uopz extension is not compatible';
return false;
}
}
// Check UNC paths when using cmd.exe
if (defined('PHP_WINDOWS_VERSION_BUILD') && PHP_VERSION_ID < 70400) {
$workingDir = getcwd();
if ($workingDir === false) {
$info = 'unable to determine working directory';
return false;
}
if (0 === strpos($workingDir, '\\\\')) {
$info = 'cmd.exe does not support UNC paths: '.$workingDir;
return false;
}
}
return true;
}
/**
* Enables async signals and control interrupts in the restarted process
*
* Available on Unix PHP 7.1+ with the pcntl extension and Windows PHP 7.4+.
*/
private function tryEnableSignals(): void
{
if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) {
pcntl_async_signals(true);
$message = 'Async signals enabled';
if (!self::$inRestart) {
// Restarting, so ignore SIGINT in parent
pcntl_signal(SIGINT, SIG_IGN);
} elseif (is_int(pcntl_signal_get_handler(SIGINT))) {
// Restarted, no handler set so force default action
pcntl_signal(SIGINT, SIG_DFL);
}
}
if (!self::$inRestart && function_exists('sapi_windows_set_ctrl_handler')) {
// Restarting, so set a handler to ignore CTRL events in the parent.
// This ensures that CTRL+C events will be available in the child
// process without having to enable them there, which is unreliable.
sapi_windows_set_ctrl_handler(function ($evt) {});
}
}
/**
* Sets static properties $xdebugActive, $xdebugVersion and $xdebugMode
*/
private static function setXdebugDetails(): void
{
if (self::$xdebugActive !== null) {
return;
}
self::$xdebugActive = false;
if (!extension_loaded('xdebug')) {
return;
}
$version = phpversion('xdebug');
self::$xdebugVersion = $version !== false ? $version : 'unknown';
if (version_compare(self::$xdebugVersion, '3.1', '>=')) {
$modes = xdebug_info('mode');
self::$xdebugMode = count($modes) === 0 ? 'off' : implode(',', $modes);
self::$xdebugActive = self::$xdebugMode !== 'off';
return;
}
// See if xdebug.mode is supported in this version
$iniMode = ini_get('xdebug.mode');
if ($iniMode === false) {
self::$xdebugActive = true;
return;
}
// Environment value wins but cannot be empty
$envMode = (string) getenv('XDEBUG_MODE');
if ($envMode !== '') {
self::$xdebugMode = $envMode;
} else {
self::$xdebugMode = $iniMode !== '' ? $iniMode : 'off';
}
// An empty comma-separated list is treated as mode 'off'
if (Preg::isMatch('/^,+$/', str_replace(' ', '', self::$xdebugMode))) {
self::$xdebugMode = 'off';
}
self::$xdebugActive = self::$xdebugMode !== 'off';
}
}

View File

@ -1,19 +0,0 @@
Copyright (c) 2006-2013 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,24 +0,0 @@
⚠️ PHP 8 introduced
[attributes](https://www.php.net/manual/en/language.attributes.overview.php),
which are a native replacement for annotations. As such, this library is
considered feature complete, and should receive exclusively bugfixes and
security fixes.
# Doctrine Annotations
[![Build Status](https://github.com/doctrine/annotations/workflows/Continuous%20Integration/badge.svg?label=build)](https://github.com/doctrine/persistence/actions)
[![Dependency Status](https://www.versioneye.com/package/php--doctrine--annotations/badge.png)](https://www.versioneye.com/package/php--doctrine--annotations)
[![Reference Status](https://www.versioneye.com/php/doctrine:annotations/reference_badge.svg)](https://www.versioneye.com/php/doctrine:annotations/references)
[![Total Downloads](https://poser.pugx.org/doctrine/annotations/downloads.png)](https://packagist.org/packages/doctrine/annotations)
[![Latest Stable Version](https://img.shields.io/packagist/v/doctrine/annotations.svg?label=stable)](https://packagist.org/packages/doctrine/annotations)
Docblock Annotations Parser library (extracted from [Doctrine Common](https://github.com/doctrine/common)).
## Documentation
See the [doctrine-project website](https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html).
## Contributing
When making a pull request, make sure your changes follow the
[Coding Standard Guidelines](https://www.doctrine-project.org/projects/doctrine-coding-standard/en/current/reference/index.html#introduction).

View File

@ -1,72 +0,0 @@
{
"name": "doctrine/annotations",
"description": "Docblock Annotations Parser",
"license": "MIT",
"type": "library",
"keywords": [
"annotations",
"docblock",
"parser"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"homepage": "https://www.doctrine-project.org/projects/annotations.html",
"require": {
"php": "^7.1 || ^8.0",
"ext-tokenizer": "*",
"doctrine/lexer": "^1 || ^2",
"psr/cache": "^1 || ^2 || ^3"
},
"require-dev": {
"doctrine/cache": "^1.11 || ^2.0",
"doctrine/coding-standard": "^9 || ^10",
"phpstan/phpstan": "~1.4.10 || ^1.8.0",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"symfony/cache": "^4.4 || ^5.4 || ^6",
"vimeo/psalm": "^4.10"
},
"suggest": {
"php": "PHP 8.0 or higher comes with attributes, a native replacement for annotations"
},
"autoload": {
"psr-4": {
"Doctrine\\Common\\Annotations\\": "lib/Doctrine/Common/Annotations"
}
},
"autoload-dev": {
"psr-4": {
"Doctrine\\Performance\\Common\\Annotations\\": "tests/Doctrine/Performance/Common/Annotations",
"Doctrine\\Tests\\Common\\Annotations\\": "tests/Doctrine/Tests/Common/Annotations"
},
"files": [
"tests/Doctrine/Tests/Common/Annotations/Fixtures/functions.php",
"tests/Doctrine/Tests/Common/Annotations/Fixtures/SingleClassLOC1000.php"
]
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
},
"sort-packages": true
}
}

View File

@ -1,252 +0,0 @@
Handling Annotations
====================
There are several different approaches to handling annotations in PHP.
Doctrine Annotations maps docblock annotations to PHP classes. Because
not all docblock annotations are used for metadata purposes a filter is
applied to ignore or skip classes that are not Doctrine annotations.
Take a look at the following code snippet:
.. code-block:: php
namespace MyProject\Entities;
use Doctrine\ORM\Mapping AS ORM;
use Symfony\Component\Validator\Constraints AS Assert;
/**
* @author Benjamin Eberlei
* @ORM\Entity
* @MyProject\Annotations\Foobarable
*/
class User
{
/**
* @ORM\Id @ORM\Column @ORM\GeneratedValue
* @dummy
* @var int
*/
private $id;
/**
* @ORM\Column(type="string")
* @Assert\NotEmpty
* @Assert\Email
* @var string
*/
private $email;
}
In this snippet you can see a variety of different docblock annotations:
- Documentation annotations such as ``@var`` and ``@author``. These
annotations are ignored and never considered for throwing an
exception due to wrongly used annotations.
- Annotations imported through use statements. The statement ``use
Doctrine\ORM\Mapping AS ORM`` makes all classes under that namespace
available as ``@ORM\ClassName``. Same goes for the import of
``@Assert``.
- The ``@dummy`` annotation. It is not a documentation annotation and
not ignored. For Doctrine Annotations it is not entirely clear how
to handle this annotation. Depending on the configuration an exception
(unknown annotation) will be thrown when parsing this annotation.
- The fully qualified annotation ``@MyProject\Annotations\Foobarable``.
This is transformed directly into the given class name.
How are these annotations loaded? From looking at the code you could
guess that the ORM Mapping, Assert Validation and the fully qualified
annotation can just be loaded using
the defined PHP autoloaders. This is not the case however: For error
handling reasons every check for class existence inside the
``AnnotationReader`` sets the second parameter $autoload
of ``class_exists($name, $autoload)`` to false. To work flawlessly the
``AnnotationReader`` requires silent autoloaders which many autoloaders are
not. Silent autoloading is NOT part of the `PSR-0 specification
<https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md>`_
for autoloading.
This is why Doctrine Annotations uses its own autoloading mechanism
through a global registry. If you are wondering about the annotation
registry being global, there is no other way to solve the architectural
problems of autoloading annotation classes in a straightforward fashion.
Additionally if you think about PHP autoloading then you recognize it is
a global as well.
To anticipate the configuration section, making the above PHP class work
with Doctrine Annotations requires this setup:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerFile("/path/to/doctrine/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php");
AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "/path/to/symfony/src");
AnnotationRegistry::registerAutoloadNamespace("MyProject\Annotations", "/path/to/myproject/src");
$reader = new AnnotationReader();
AnnotationReader::addGlobalIgnoredName('dummy');
The second block with the annotation registry calls registers all the
three different annotation namespaces that are used.
Doctrine Annotations saves all its annotations in a single file, that is
why ``AnnotationRegistry#registerFile`` is used in contrast to
``AnnotationRegistry#registerAutoloadNamespace`` which creates a PSR-0
compatible loading mechanism for class to file names.
In the third block, we create the actual ``AnnotationReader`` instance.
Note that we also add ``dummy`` to the global list of ignored
annotations for which we do not throw exceptions. Setting this is
necessary in our example case, otherwise ``@dummy`` would trigger an
exception to be thrown during the parsing of the docblock of
``MyProject\Entities\User#id``.
Setup and Configuration
-----------------------
To use the annotations library is simple, you just need to create a new
``AnnotationReader`` instance:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
This creates a simple annotation reader with no caching other than in
memory (in php arrays). Since parsing docblocks can be expensive you
should cache this process by using a caching reader.
To cache annotations, you can create a ``Doctrine\Common\Annotations\PsrCachedReader``.
This reader decorates the original reader and stores all annotations in a PSR-6
cache:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\PsrCachedReader;
$cache = ... // instantiate a PSR-6 Cache pool
$reader = new PsrCachedReader(
new AnnotationReader(),
$cache,
$debug = true
);
The ``debug`` flag is used here as well to invalidate the cache files
when the PHP class with annotations changed and should be used during
development.
.. warning ::
The ``AnnotationReader`` works and caches under the
assumption that all annotations of a doc-block are processed at
once. That means that annotation classes that do not exist and
aren't loaded and cannot be autoloaded (using the
AnnotationRegistry) would never be visible and not accessible if a
cache is used unless the cache is cleared and the annotations
requested again, this time with all annotations defined.
By default the annotation reader returns a list of annotations with
numeric indexes. If you want your annotations to be indexed by their
class name you can wrap the reader in an ``IndexedReader``:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\IndexedReader;
$reader = new IndexedReader(new AnnotationReader());
.. warning::
You should never wrap the indexed reader inside a cached reader,
only the other way around. This way you can re-use the cache with
indexed or numeric keys, otherwise your code may experience failures
due to caching in a numerical or indexed format.
Registering Annotations
~~~~~~~~~~~~~~~~~~~~~~~
As explained in the introduction, Doctrine Annotations uses its own
autoloading mechanism to determine if a given annotation has a
corresponding PHP class that can be autoloaded. For annotation
autoloading you have to configure the
``Doctrine\Common\Annotations\AnnotationRegistry``. There are three
different mechanisms to configure annotation autoloading:
- Calling ``AnnotationRegistry#registerFile($file)`` to register a file
that contains one or more annotation classes.
- Calling ``AnnotationRegistry#registerNamespace($namespace, $dirs =
null)`` to register that the given namespace contains annotations and
that their base directory is located at the given $dirs or in the
include path if ``NULL`` is passed. The given directories should *NOT*
be the directory where classes of the namespace are in, but the base
directory of the root namespace. The AnnotationRegistry uses a
namespace to directory separator approach to resolve the correct path.
- Calling ``AnnotationRegistry#registerLoader($callable)`` to register
an autoloader callback. The callback accepts the class as first and
only parameter and has to return ``true`` if the corresponding file
was found and included.
.. note::
Loaders have to fail silently, if a class is not found even if it
matches for example the namespace prefix of that loader. Never is a
loader to throw a warning or exception if the loading failed
otherwise parsing doc block annotations will become a huge pain.
A sample loader callback could look like:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\ClassLoader\UniversalClassLoader;
AnnotationRegistry::registerLoader(function($class) {
$file = str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php";
if (file_exists("/my/base/path/" . $file)) {
// file_exists() makes sure that the loader fails silently
require "/my/base/path/" . $file;
}
});
$loader = new UniversalClassLoader();
AnnotationRegistry::registerLoader(array($loader, "loadClass"));
Ignoring missing exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default an exception is thrown from the ``AnnotationReader`` if an
annotation was found that:
- is not part of the list of ignored "documentation annotations";
- was not imported through a use statement;
- is not a fully qualified class that exists.
You can disable this behavior for specific names if your docblocks do
not follow strict requirements:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
AnnotationReader::addGlobalIgnoredName('foo');
PHP Imports
~~~~~~~~~~~
By default the annotation reader parses the use-statement of a php file
to gain access to the import rules and register them for the annotation
processing. Only if you are using PHP Imports can you validate the
correct usage of annotations and throw exceptions if you misspelled an
annotation. This mechanism is enabled by default.
To ease the upgrade path, we still allow you to disable this mechanism.
Note however that we will remove this in future versions:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$reader->setEnabledPhpImports(false);

View File

@ -1,443 +0,0 @@
Custom Annotation Classes
=========================
If you want to define your own annotations, you just have to group them
in a namespace and register this namespace in the ``AnnotationRegistry``.
Annotation classes have to contain a class-level docblock with the text
``@Annotation``:
.. code-block:: php
namespace MyCompany\Annotations;
/** @Annotation */
class Bar
{
// some code
}
Inject annotation values
------------------------
The annotation parser checks if the annotation constructor has arguments,
if so then it will pass the value array, otherwise it will try to inject
values into public properties directly:
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
*
* Some Annotation using a constructor
*/
class Bar
{
private $foo;
public function __construct(array $values)
{
$this->foo = $values['foo'];
}
}
/**
* @Annotation
*
* Some Annotation without a constructor
*/
class Foo
{
public $bar;
}
Optional: Constructors with Named Parameters
--------------------------------------------
Starting with Annotations v1.11 a new annotation instantiation strategy
is available that aims at compatibility of Annotation classes with the PHP 8
attribute feature. You need to declare a constructor with regular parameter
names that match the named arguments in the annotation syntax.
To enable this feature, you can tag your annotation class with
``@NamedArgumentConstructor`` (available from v1.12) or implement the
``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation`` interface
(available from v1.11 and deprecated as of v1.12).
When using the ``@NamedArgumentConstructor`` tag, the first argument of the
constructor is considered as the default one.
Usage with the ``@NamedArgumentConstructor`` tag
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @NamedArgumentConstructor
*/
class Bar implements NamedArgumentConstructorAnnotation
{
private $foo;
public function __construct(string $foo)
{
$this->foo = $foo;
}
}
/** Usable with @Bar(foo="baz") */
/** Usable with @Bar("baz") */
In combination with PHP 8's constructor property promotion feature
you can simplify this to:
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @NamedArgumentConstructor
*/
class Bar implements NamedArgumentConstructorAnnotation
{
public function __construct(private string $foo) {}
}
Usage with the
``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation``
interface (v1.11, deprecated as of v1.12):
.. code-block:: php
namespace MyCompany\Annotations;
use Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation;
/** @Annotation */
class Bar implements NamedArgumentConstructorAnnotation
{
private $foo;
public function __construct(private string $foo) {}
}
/** Usable with @Bar(foo="baz") */
Annotation Target
-----------------
``@Target`` indicates the kinds of class elements to which an annotation
type is applicable. Then you could define one or more targets:
- ``CLASS`` Allowed in class docblocks
- ``PROPERTY`` Allowed in property docblocks
- ``METHOD`` Allowed in the method docblocks
- ``FUNCTION`` Allowed in function dockblocks
- ``ALL`` Allowed in class, property, method and function docblocks
- ``ANNOTATION`` Allowed inside other annotations
If the annotations is not allowed in the current context, an
``AnnotationException`` is thrown.
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
*/
class Bar
{
// some code
}
/**
* @Annotation
* @Target("CLASS")
*/
class Foo
{
// some code
}
Attribute types
---------------
The annotation parser checks the given parameters using the phpdoc
annotation ``@var``, The data type could be validated using the ``@var``
annotation on the annotation properties or using the ``@Attributes`` and
``@Attribute`` annotations.
If the data type does not match you get an ``AnnotationException``
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
*/
class Bar
{
/** @var mixed */
public $mixed;
/** @var boolean */
public $boolean;
/** @var bool */
public $bool;
/** @var float */
public $float;
/** @var string */
public $string;
/** @var integer */
public $integer;
/** @var array */
public $array;
/** @var SomeAnnotationClass */
public $annotation;
/** @var array<integer> */
public $arrayOfIntegers;
/** @var array<SomeAnnotationClass> */
public $arrayOfAnnotations;
}
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
* @Attributes({
* @Attribute("stringProperty", type = "string"),
* @Attribute("annotProperty", type = "SomeAnnotationClass"),
* })
*/
class Foo
{
public function __construct(array $values)
{
$this->stringProperty = $values['stringProperty'];
$this->annotProperty = $values['annotProperty'];
}
// some code
}
Annotation Required
-------------------
``@Required`` indicates that the field must be specified when the
annotation is used. If it is not used you get an ``AnnotationException``
stating that this value can not be null.
Declaring a required field:
.. code-block:: php
/**
* @Annotation
* @Target("ALL")
*/
class Foo
{
/** @Required */
public $requiredField;
}
Usage:
.. code-block:: php
/** @Foo(requiredField="value") */
public $direction; // Valid
/** @Foo */
public $direction; // Required field missing, throws an AnnotationException
Enumerated values
-----------------
- An annotation property marked with ``@Enum`` is a field that accepts a
fixed set of scalar values.
- You should use ``@Enum`` fields any time you need to represent fixed
values.
- The annotation parser checks the given value and throws an
``AnnotationException`` if the value does not match.
Declaring an enumerated property:
.. code-block:: php
/**
* @Annotation
* @Target("ALL")
*/
class Direction
{
/**
* @Enum({"NORTH", "SOUTH", "EAST", "WEST"})
*/
public $value;
}
Annotation usage:
.. code-block:: php
/** @Direction("NORTH") */
public $direction; // Valid value
/** @Direction("NORTHEAST") */
public $direction; // Invalid value, throws an AnnotationException
Constants
---------
The use of constants and class constants is available on the annotations
parser.
The following usages are allowed:
.. code-block:: php
namespace MyCompany\Entity;
use MyCompany\Annotations\Foo;
use MyCompany\Annotations\Bar;
use MyCompany\Entity\SomeClass;
/**
* @Foo(PHP_EOL)
* @Bar(Bar::FOO)
* @Foo({SomeClass::FOO, SomeClass::BAR})
* @Bar({SomeClass::FOO_KEY = SomeClass::BAR_VALUE})
*/
class User
{
}
Be careful with constants and the cache !
.. note::
The cached reader will not re-evaluate each time an annotation is
loaded from cache. When a constant is changed the cache must be
cleaned.
Usage
-----
Using the library API is simple. Using the annotations described in the
previous section, you can now annotate other classes with your
annotations:
.. code-block:: php
namespace MyCompany\Entity;
use MyCompany\Annotations\Foo;
use MyCompany\Annotations\Bar;
/**
* @Foo(bar="foo")
* @Bar(foo="bar")
*/
class User
{
}
Now we can write a script to get the annotations above:
.. code-block:: php
$reflClass = new ReflectionClass('MyCompany\Entity\User');
$classAnnotations = $reader->getClassAnnotations($reflClass);
foreach ($classAnnotations AS $annot) {
if ($annot instanceof \MyCompany\Annotations\Foo) {
echo $annot->bar; // prints "foo";
} else if ($annot instanceof \MyCompany\Annotations\Bar) {
echo $annot->foo; // prints "bar";
}
}
You have a complete API for retrieving annotation class instances from a
class, property or method docblock:
Reader API
~~~~~~~~~~
Access all annotations of a class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getClassAnnotations(\ReflectionClass $class);
Access one annotation of a class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getClassAnnotation(\ReflectionClass $class, $annotationName);
Access all annotations of a method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getMethodAnnotations(\ReflectionMethod $method);
Access one annotation of a method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getMethodAnnotation(\ReflectionMethod $method, $annotationName);
Access all annotations of a property
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getPropertyAnnotations(\ReflectionProperty $property);
Access one annotation of a property
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName);
Access all annotations of a function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getFunctionAnnotations(\ReflectionFunction $property);
Access one annotation of a function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getFunctionAnnotation(\ReflectionFunction $property, $annotationName);

View File

@ -1,110 +0,0 @@
Deprecation notice
==================
PHP 8 introduced `attributes
<https://www.php.net/manual/en/language.attributes.overview.php>`_,
which are a native replacement for annotations. As such, this library is
considered feature complete, and should receive exclusively bugfixes and
security fixes.
Introduction
============
Doctrine Annotations allows to implement custom annotation
functionality for PHP classes and functions.
.. code-block:: php
class Foo
{
/**
* @MyAnnotation(myProperty="value")
*/
private $bar;
}
Annotations aren't implemented in PHP itself which is why this component
offers a way to use the PHP doc-blocks as a place for the well known
annotation syntax using the ``@`` char.
Annotations in Doctrine are used for the ORM configuration to build the
class mapping, but it can be used in other projects for other purposes
too.
Installation
============
You can install the Annotation component with composer:
.. code-block::
  $ composer require doctrine/annotations
Create an annotation class
==========================
An annotation class is a representation of the later used annotation
configuration in classes. The annotation class of the previous example
looks like this:
.. code-block:: php
/**
* @Annotation
*/
final class MyAnnotation
{
public $myProperty;
}
The annotation class is declared as an annotation by ``@Annotation``.
:ref:`Read more about custom annotations. <custom>`
Reading annotations
===================
The access to the annotations happens by reflection of the class or function
containing them. There are multiple reader-classes implementing the
``Doctrine\Common\Annotations\Reader`` interface, that can access the
annotations of a class. A common one is
``Doctrine\Common\Annotations\AnnotationReader``:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
// Deprecated and will be removed in 2.0 but currently needed
AnnotationRegistry::registerLoader('class_exists');
$reflectionClass = new ReflectionClass(Foo::class);
$property = $reflectionClass->getProperty('bar');
$reader = new AnnotationReader();
$myAnnotation = $reader->getPropertyAnnotation(
$property,
MyAnnotation::class
);
echo $myAnnotation->myProperty; // result: "value"
Note that ``AnnotationRegistry::registerLoader('class_exists')`` only works
if you already have an autoloader configured (i.e. composer autoloader).
Otherwise, :ref:`please take a look to the other annotation autoload mechanisms <annotations>`.
A reader has multiple methods to access the annotations of a class or
function.
:ref:`Read more about handling annotations. <annotations>`
IDE Support
-----------
Some IDEs already provide support for annotations:
- Eclipse via the `Symfony2 Plugin <https://github.com/pulse00/Symfony-2-Eclipse-Plugin>`_
- PhpStorm via the `PHP Annotations Plugin <https://plugins.jetbrains.com/plugin/7320-php-annotations>`_ or the `Symfony Plugin <https://plugins.jetbrains.com/plugin/7219-symfony-support>`_
.. _Read more about handling annotations.: annotations
.. _Read more about custom annotations.: custom

View File

@ -1,6 +0,0 @@
.. toctree::
:depth: 3
index
annotations
custom

View File

@ -1,57 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use BadMethodCallException;
use function sprintf;
/**
* Annotations class.
*/
class Annotation
{
/**
* Value property. Common among all derived classes.
*
* @var mixed
*/
public $value;
/** @param array<string, mixed> $data Key-value for properties to be defined in this class. */
final public function __construct(array $data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
/**
* Error handler for unknown property accessor in Annotation class.
*
* @param string $name Unknown property name.
*
* @throws BadMethodCallException
*/
public function __get($name)
{
throw new BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)
);
}
/**
* Error handler for unknown property mutator in Annotation class.
*
* @param string $name Unknown property name.
* @param mixed $value Property value.
*
* @throws BadMethodCallException
*/
public function __set($name, $value)
{
throw new BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)
);
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that can be used to signal to the parser
* to check the attribute type during the parsing process.
*
* @Annotation
*/
final class Attribute
{
/** @var string */
public $name;
/** @var string */
public $type;
/** @var bool */
public $required = false;
}

View File

@ -1,15 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that can be used to signal to the parser
* to check the types of all declared attributes during the parsing process.
*
* @Annotation
*/
final class Attributes
{
/** @var array<Attribute> */
public $value;
}

View File

@ -1,69 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
use InvalidArgumentException;
use function get_class;
use function gettype;
use function in_array;
use function is_object;
use function is_scalar;
use function sprintf;
/**
* Annotation that can be used to signal to the parser
* to check the available values during the parsing process.
*
* @Annotation
* @Attributes({
* @Attribute("value", required = true, type = "array"),
* @Attribute("literal", required = false, type = "array")
* })
*/
final class Enum
{
/** @phpstan-var list<scalar> */
public $value;
/**
* Literal target declaration.
*
* @var mixed[]
*/
public $literal;
/**
* @phpstan-param array{literal?: mixed[], value: list<scalar>} $values
*
* @throws InvalidArgumentException
*/
public function __construct(array $values)
{
if (! isset($values['literal'])) {
$values['literal'] = [];
}
foreach ($values['value'] as $var) {
if (! is_scalar($var)) {
throw new InvalidArgumentException(sprintf(
'@Enum supports only scalar values "%s" given.',
is_object($var) ? get_class($var) : gettype($var)
));
}
}
foreach ($values['literal'] as $key => $var) {
if (! in_array($key, $values['value'])) {
throw new InvalidArgumentException(sprintf(
'Undefined enumerator value "%s" for literal "%s".',
$key,
$var
));
}
}
$this->value = $values['value'];
$this->literal = $values['literal'];
}
}

Some files were not shown because too many files have changed in this diff Show More