repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/controllers/about.php | demo/app/controllers/about.php | <?php
class AboutController extends Controller
{
function init($ctx){
}
function index($ctx){
}
function us($ctx){
}
}
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/controllers/index.php | demo/app/controllers/index.php | <?php
class IndexController extends Controller
{
function init($ctx){
}
function index($ctx){
$page = 1;
$size = 16;
$where = '';
#$ctx->page = Post::paginate($page, $size, $where, 'id desc');
$ctx->var = 'hello! ' . date('Y-m-d H:i:s'); // 在 View 中可以直接使用的变量: $var
}
}
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/controllers/about/job.php | demo/app/controllers/about/job.php | <?php
class JobController extends Controller
{
function init($ctx){
}
function index($ctx){
}
}
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/controllers/api/test.php | demo/app/controllers/api/test.php | <?php
class TestController extends Controller
{
function init($ctx){
$this->layout = false;
}
function index($ctx){
$data = array(
'a' => 1,
'b' => 2,
);
echo json_encode($data);
}
}
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/console/test.php | demo/app/console/test.php | <?php
error_reporting(E_ALL & ~E_NOTICE);
define('APP_PATH', dirname(__FILE__) . '/..');
require_once('/data/lib/iphp/loader.php');
Logger::debug('running...');
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/console/test_master_worker.php | demo/app/console/test_master_worker.php | <?php
error_reporting(E_ALL & ~E_NOTICE);
define('APP_PATH', dirname(__FILE__) . '/..');
require_once('/data/lib/iphp/loader.php');
class MyMasterWorker extends MasterWorker
{
function master(){
for($i=0; $i<100; $i++){
#Logger::debug("add job $i");
$this->add_job($i);
#$this->wait(); // 如果每添加一个任务便 wait 的话, 将无法实现并发!
#Logger::debug("");
}
Logger::debug("master added all $i jobs");
// 当需要在确保所有任务处理完毕后再做其它操作时, 才需要调用 wait
$this->wait();
sleep(2);
// ...
Logger::debug("all job done");
}
function worker($job){
usleep(mt_rand(1, 6) * 100 * 1000);
// ...
$pid = posix_getpid();
Logger::debug("[$pid] process job: " . json_encode($job));
return true;
}
}
$mw = new MyMasterWorker();
$mw->set_num_workers(3);
$mw->run();
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/models/Post.php | demo/app/models/Post.php | <?php
class Post extends Model
{
static $table_name = 'posts';
}
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/layout.tpl.php | demo/app/views/layout.tpl.php | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iphp - A fast and simple PHP framework for web development</title>
<meta name="description" content="iphp framework">
<meta name="keywords" content="iphp framework">
<link href="<?= _url('/css/bootstrap.min.css') ?>" rel="stylesheet">
<link href="<?= _url('/css/main.css') ?>" rel="stylesheet">
<script src="<?= _url('/js/jquery-1.9.1.min.js') ?>"></script>
<script src="<?= _url('/js/bootstrap.min.js') ?>"></script>
</head>
<body>
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="http://www.ideawu.com/iphp/">iphp</a>
</div>
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li class="active">
<a href="<?=_url('/')?>">
<i class="glyphicon glyphicon-home"></i> 首页
</a>
</li>
<li class="divider-vertical"></li>
<li>
<a href="https://github.com/ideawu/iphp">
<i class="glyphicon glyphicon-share-alt"></i> GitHub
</a>
</li>
</ul>
</div>
</div>
<div class="container">
<?php _view(); ?>
<hr>
<div class="footer">
Copyright © 2014 <a href="http://www.ideawu.net/">ideawu</a>. All rights reserved.
</div>
</div>
<!-- /container -->
</body>
</html>
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/index.tpl.php | demo/app/views/index.tpl.php |
<h3>演示</h3>
<p>从 Controller 传来的变量 <code>$var</code>: <?=$var?> </p>
<table class="table table-striped">
<thead>
<tr>
<th>Path</th>
<th>Controller File</th>
<th>Controller#action</th>
<th>View</th>
<th>Full URL</th>
</tr>
</thead>
<tbody>
<tr>
<td><?=str_replace(_url(''), '', _url('about'))?></td>
<td>about.php</td>
<td>AboutController#index</td>
<td>about.tpl.php</td>
<td><a target="_blank" href="<?=_url('about')?>"><?=_url('about')?></a></td>
</tr>
<tr>
<td><?=str_replace(_url(''), '', _url('about/us'))?></td>
<td>about.php</td>
<td>AboutController#us</td>
<td>about/us.tpl.php</td>
<td><a target="_blank" href="<?=_url('about/us')?>"><?=_url('about/us')?></a></td>
</tr>
<tr>
<td><?=str_replace(_url(''), '', _url('about/job'))?></td>
<td>about/job.php</td>
<td>JobController#index</td>
<td>about/job.tpl.php</td>
<td><a target="_blank" href="<?=_url('about/job')?>"><?=_url('about/job')?></a></td>
</tr>
<tr>
<td><?=str_replace(_url(''), '', _url('api/test'))?></td>
<td>api/test.php</td>
<td>TestController#index</td>
<td>None</td>
<td><a target="_blank" href="<?=_url('api/test')?>"><?=_url('api/test')?></a></td>
</tr>
</tbody>
</table>
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/about.tpl.php | demo/app/views/about.tpl.php | <h1>About</h1> | php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/_error/ajax.tpl.php | demo/app/views/_error/ajax.tpl.php | <?php
$msg = htmlspecialchars($_e->getMessage());
if(strpos($msg, 'in SQL:') !== false || strpos($msg, 'db error') !== false || get_class($_e) == 'SSDBException'){
Logger::error($_e);
$msg = 'db error';
}
iphp_Response::ajax($_e->getCode(), $msg);
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/_error/404.tpl.php | demo/app/views/_error/404.tpl.php | <h1>404 - Not Found!</h1>
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/_error/default.tpl.php | demo/app/views/_error/default.tpl.php | <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($_e->getMessage()) ?></title>
<style>body{font-size: 14px; font-family: monospace;}</style>
</head>
<body>
<h1 style="text-align: center;"><?= htmlspecialchars($_e->getMessage()) ?></h1>
<div>
<?php
if(App::$env == 'dev'){
$ts = $_e->getTrace();
$html = '';
foreach($ts as $t){
$html .= "{$t['file']}:{$t['line']} {$t['function']}()<br/>\n";
}
echo $html;
}
?>
</div>
<p style="margin-top: 20px;
padding-top: 10px;
border-top: 1px solid #ccc;
text-align: center;">iphp</p>
</body>
</html>
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/about/us.tpl.php | demo/app/views/about/us.tpl.php | <h1>About Us</h1> | php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/views/about/job.tpl.php | demo/app/views/about/job.tpl.php | <h1>Jobs</h1>
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/config/config_dev.php | demo/app/config/config_dev.php | <?php
define('ENV', 'dev');
return array(
'env' => ENV,
'logger' => array(
'level' => 'all', // none/off|(LEVEL)
'dump' => 'file', // none|html|file, 可用'|'组合
'files' => array( // ALL|(LEVEL)
'ALL' => dirname(__FILE__) . '/../../logs/' . date('Y-m') . '.log',
),
),
'db' => array(
'host' => 'localhost',
'dbname' => 'db',
'username' => 'u',
'password' => '123456',
'charset' => 'utf8',
// call Db::readonly(true) to enable readonly_db
'readonly_db' => array(
'host' => '127.0.0.1',
'dbname' => 'db',
'username' => 'u2',
'password' => '123456',
'charset' => 'utf8',
),
),
// usage: Db::use_db('my');
//'db_my' => ...
);
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/config/config.php | demo/app/config/config.php | <?php
define('ENV', 'dev');
return array(
'env' => ENV,
'logger' => array(
'level' => 'all', // none/off|(LEVEL)
'dump' => 'file', // none|html|file, 可用'|'组合
'files' => array( // ALL|(LEVEL)
'ALL' => dirname(__FILE__) . '/../../logs/' . date('Y-m') . '.log',
),
),
'db' => array(
'host' => 'localhost',
'dbname' => 'db',
'username' => 'u',
'password' => '123456',
'charset' => 'utf8',
// call Db::readonly(true) to enable readonly_db
'readonly_db' => array(
'host' => '127.0.0.1',
'dbname' => 'db',
'username' => 'u2',
'password' => '123456',
'charset' => 'utf8',
),
),
// usage: Db::use_db('my');
//'db_my' => ...
);
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
ideawu/iphp | https://github.com/ideawu/iphp/blob/47d322cd119dcbe5e5f246146c1bfb6d440fe51b/demo/app/config/config_online.php | demo/app/config/config_online.php | <?php
define('ENV', 'online');
return array(
'env' => ENV,
'logger' => array(
'level' => 'all', // none/off|(LEVEL)
'dump' => 'file', // none|html|file, 可用'|'组合
'files' => array( // ALL|(LEVEL)
'ALL' => "/data/applogs/demo/" . date('Y-m-d') . '.log',
),
),
'db' => array(
'host' => 'localhost',
'dbname' => 'db',
'username' => 'u',
'password' => 'p',
'charset' => 'utf8',
),
// usage: Db::use_db('my');
//'db_my' => ...
);
| php | BSD-3-Clause | 47d322cd119dcbe5e5f246146c1bfb6d440fe51b | 2026-01-05T05:02:00.171683Z | false |
jcnewell/ergast-f1-api | https://github.com/jcnewell/ergast-f1-api/blob/eff8af1c873f09b5e037e46581d17937e87a04e6/webroot/php/api/index.php | webroot/php/api/index.php | <?php
include("functions.inc");
$urlComponents = parse_url($_SERVER['REQUEST_URI']);
$path = strtolower(urldecode($urlComponents['path']));
$url = "http://ergast.com" . $path;
$period = strrpos($path, ".");
if($period !== FALSE) {
$format = substr($path, $period + 1);
$path = substr($path, 0, $period);
if(strcmp($format, "xml") != 0 && strcmp($format, "json") != 0) error(404, "Format not found.");
} else {
$format = "xml"; // Default.
}
if(array_key_exists('query', $urlComponents)) {
parse_str($urlComponents['query'], $fields);
} else {
$fields = array();
}
if(array_key_exists('limit', $fields)) {
$limit = intval($fields['limit']);
}
if(array_key_exists('offset', $fields)) {
$offset = intval($fields['offset']);
}
if(!isset($limit)) $limit = 30;
#if($limit > 1000) $limit = 1000;
if(!isset($offset)) $offset = 0;
$callback = NULL;
if(array_key_exists('callback', $fields)) {
$callback = $fields['callback'];
}
if(isset($callback)) {
if(!isValidCallback($callback)) {
error(400, "Bad Request");
}
}
$segments = explode("/", $path);
$series = $segments[2];
if(strcmp($series, "f1") == 0) {
include("f1dbro.inc");
} else if(strcmp($series, "fe") == 0) {
include("fedbro.inc");
} else {
error(404, "Series Not Found: $series");
}
$n = 3;
$key = "races";
$year = NULL;
$round = NULL;
if(isset($segments[3])) {
if(strcmp($segments[3], "current") == 0) {
$year = currentYear();
$n = 4;
$key = "races";
} elseif(strlen($segments[3]) == 4 && is_numeric($segments[3])) {
$year = intval($segments[3]);
$n = 4;
$key = "races";
}
}
if(isset($segments[4])) {
if($n == 4) {
if(strcmp($segments[4], "last") == 0) {
$round = lastRound($year);
//$next = lastRound($year);
//$year = $last['year'];
//$round = $last['round'];
if(!$round) error(404, "Round Not Found");
$n = 5;
} elseif(strcmp($segments[4], "next") == 0) {
$next = nextRound($year);
$year = $next['year'];
$round = $next['round'];
if(!$round) error(404, "Round Not Found");
$n = 5;
} elseif(strlen($segments[4]) < 3 && is_numeric($segments[4])) {
$round = intval($segments[4]);
$n = 5;
}
}
}
$driver = NULL;
$constructor = NULL;
$circuit = NULL;
$status = NULL;
$results = NULL;
$laps = NULL;
$pitstops = NULL;
$driverStandings = NULL;
$constructorStandings = NULL;
$grid = NULL;
$fastest = NULL;
$qualifying = NULL;
$sprint = NULL;
for($i=$n; $i<$n+17; $i+=2) {
if(isset($segments[$i])) {
$key = $segments[$i];
switch($key) {
case "drivers":
if($driver) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$driver = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "constructors":
if($constructor) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$constructor = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "circuits":
if($circuit) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$circuit = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "status":
if($status) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$status = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "results":
if($results) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$results = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "laps":
if($laps) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
if(is_numeric($segments[$i+1])) {
$laps = intval($segments[$i+1]);
} else {
error(400, "Bad Request");
}
} else {
break 2;
}
}
break;
case "pitstops":
if($pitstops) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
if(is_numeric($segments[$i+1])) {
$pitstops = intval($segments[$i+1]);
} else {
error(400, "Bad Request");
}
} else {
break 2;
}
}
break;
case "driverstandings":
if($driverStandings) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
if(is_numeric($segments[$i+1])) {
$driverStandings = intval($segments[$i+1]);
} else {
error(400, "Bad Request");
}
} else {
break 2;
}
}
break;
case "constructorstandings":
if($constructorStandings) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
if(is_numeric($segments[$i+1])) {
$constructorStandings = intval($segments[$i+1]);
} else {
error(400, "Bad Request");
}
} else {
break 2;
}
}
break;
case "grid":
if($grid) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1]) && is_numeric($segments[$i+1])) {
$grid = intval($segments[$i+1]);
} else {
// "grid" cannot be last element.
error(400, "Bad Request");
}
}
break;
case "fastest":
if($fastest) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1]) && is_numeric($segments[$i+1])) {
$fastest = intval($segments[$i+1]);
} else {
// "fastest" cannot be last element.
error(400, "Bad Request");
}
}
break;
case "qualifying":
if($qualifying) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
if(is_numeric($segments[$i+1])) {
$qualifying = intval($segments[$i+1]);
} else {
error(400, "Bad Request");
}
} else {
break 2;
}
}
break;
// if(isset($segments[$i+1])) {
// // "qualifying" can only be last segment.
// error(400, "Bad Request");
// } else {
// break 2;
// }
// break;
case "sprint":
if($sprint) {
error(400, "Bad Request");
} else {
if(isset($segments[$i+1])) {
$sprint = clean($segments[$i+1]);
} else {
break 2;
}
}
break;
case "seasons":
if(isset($segments[$i+1])) {
// "seasons" can only be last segment.
error(400, "Bad Request");
} else {
break 2;
}
break;
case "races":
if(isset($segments[$i+1])) {
// "races" can only be last segment.
error(400, "Bad Request");
} else {
break 2;
}
break;
default:
error(400, "Bad Request");
}
} else {
break;
}
}
//echo "year=$year round=$round key=$key<br>\n";
//echo "driver=$driver<br>\n";
//echo "constructor=$constructor<br>\n";
//echo "circuit=$circuit<br>\n";
//echo "status=$status<br>\n";
if($limit > 1000) {
if(strcmp($key, "laps") == 0) {
$limit = 2000;
} else {
$limit = 1000;
}
}
switch($key) {
case "drivers":
include("DriverTable.inc");
break;
case "constructors":
include("ConstructorTable.inc");
break;
case "circuits":
include("CircuitTable.inc");
break;
case "status":
include("StatusTable.inc");
break;
case "races":
include("RaceTable.inc");
break;
case "results":
include("RaceResults.inc");
break;
case "laps":
include("LapTimes.inc");
break;
case "pitstops":
include("PitStops.inc");
break;
case "qualifying":
include("Qualifying.inc");
break;
case "sprint":
include("SprintResults.inc");
break;
case "driverstandings":
include("DriverStandings.inc");
break;
case "constructorstandings":
include("ConstructorStandings.inc");
break;
case "seasons":
include("SeasonTable.inc");
break;
default:
error(400, "Bad Request");
}
exit();
?>
| php | Apache-2.0 | eff8af1c873f09b5e037e46581d17937e87a04e6 | 2026-01-05T05:02:19.752675Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/registration.php | registration.php | <?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Creatuity_Interception',
__DIR__
); | php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/CompiledInterceptorTest.php | Test/Integration/CompiledInterceptor/CompiledInterceptorTest.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor;
use Creatuity\Interception\Generator\AreasPluginList;
use Creatuity\Interception\Generator\FileCache;
use Creatuity\Interception\Generator\StaticScope;
use Magento\Framework\App\AreaList;
use Magento\Framework\Code\Generator\Io;
use Creatuity\Interception\Generator\CompiledInterceptor;
use Creatuity\Interception\Generator\CompiledPluginList;
use Magento\Framework\App\ObjectManager;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\SecondItem;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ComplexItem;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ComplexItemTyped;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\Item;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\NullLogger;
/**
* Class CompiledInterceptorTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CompiledInterceptorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Io|MockObject
*/
private $ioGenerator;
/**
* @var AreaList|MockObject
*/
private $areaList;
/**
* @inheritdoc
*/
protected function setUp()
{
$this->ioGenerator = $this->getMockBuilder(Io::class)
->disableOriginalConstructor()
->getMock();
$this->areaList = $this->getMockBuilder(AreaList::class)
->disableOriginalConstructor()
->getMock();
}
/**
* @return array
*/
public function createScopeReaders()
{
$readerMap = include __DIR__ . '/../_files/reader_mock_map.php';
$readerMock = $this->createMock(\Magento\Framework\ObjectManager\Config\Reader\Dom::class);
$readerMock->expects($this->any())->method('read')->will($this->returnValueMap($readerMap));
$omMock = $this->createMock(ObjectManager::class);
$omMock->method('get')->with(\Psr\Log\LoggerInterface::class)->willReturn(new NullLogger());
$omConfigMock = $this->getMockForAbstractClass(
\Magento\Framework\Interception\ObjectManager\ConfigInterface::class
);
$omConfigMock->expects($this->any())->method('getOriginalInstanceType')->will($this->returnArgument(0));
$ret = [];
$objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
//clear static cache
(new FileCache())->clean();
foreach ($readerMap as $readerLine) {
$ret[$readerLine[0]] = $objectManagerHelper->getObject(
CompiledPluginList::class,
[
'objectManager' => $omMock,
'scope' => new StaticScope($readerLine[0]),
'reader' => $readerMock,
'omConfig' => $omConfigMock
]
);
}
return $ret;
}
/**
* Checks a test case when interceptor generates code for the specified class.
*
* @param string $className
* @param string $resultClassName
* @param string $fileName
* @dataProvider interceptorDataProvider
*/
public function testGenerate($className, $resultClassName, $fileName)
{
$objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
/** @var AreasPluginList $areaPlugins */
$areaPlugins = $objectManagerHelper->getObject(
AreasPluginList::class,
[
'areaList' => $this->areaList,
'plugins' => $this->createScopeReaders()
]
);
/** @var CompiledInterceptor|MockObject $interceptor */
$interceptor = $this->getMockBuilder(CompiledInterceptor::class)
->setMethods(['_validateData'])
->setConstructorArgs(
[
$areaPlugins,
$className,
$resultClassName,
$this->ioGenerator,
null,
null
]
)
->getMock();
$this->ioGenerator->method('generateResultFileName')->with('\\' . $resultClassName)
->willReturn($fileName . '.php');
$code = file_get_contents(__DIR__ . '/_out_interceptors/' . $fileName . '.txt');
$this->ioGenerator->method('writeResultFile')->with($fileName . '.php', $code);
$interceptor->method('_validateData')->willReturn(true);
$generated = $interceptor->generate();
$this->assertEquals($fileName . '.php', $generated, 'Generated interceptor is invalid.');
/*
eval( $code );
$className = "\\$resultClassName";
$interceptor = new $className(
??,
new StaticScope('frontend')
);
$interceptor->getName();
*/
}
/**
* Gets list of interceptor samples.
*
* @return array
*/
public function interceptorDataProvider()
{
return [
[
Item::class,
Item::class . '\Interceptor',
'Item'
],
[
ComplexItem::class,
ComplexItem::class . '\Interceptor',
'ComplexItem'
],
[
ComplexItemTyped::class,
ComplexItemTyped::class . '\Interceptor',
'ComplexItemTyped'
],
[
SecondItem::class,
SecondItem::class . '\Interceptor',
'SecondItem'
],
];
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/ComplexItemTyped.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/ComplexItemTyped.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model;
class ComplexItemTyped
{
private $value;
private $variadicValue;
public function returnVoid(): void
{
// Nothing to do here
}
/**
* @return null|string
*/
public function getNullableValue(): ?string
{
return null;
}
/**
* @return string
*/
public function getName(): string
{
return $this->value;
}
/**
* @param string $value
*/
public function setValue(string $value)
{
$this->value = $value;
}
/**
* @param string ...$variadicValue
*/
public function firstVariadicParameter(string ...$variadicValue)
{
$this->variadicValue = $variadicValue;
}
/**
* @param string $value
* @param string ...$variadicValue
*/
public function secondVariadicParameter(string $value, string ...$variadicValue)
{
$this->value = $value;
$this->variadicValue = $variadicValue;
}
/**
* @param string ...$variadicValue
*/
public function byRefVariadic(string & ...$variadicValue)
{
$this->variadicValue = $variadicValue;
}
/**
*
*/
public function returnsSelf(): self
{
return $this;
}
/**
*
*/
public function returnsType(): \Magento\Framework\Something
{
return null;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/ComplexItem.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/ComplexItem.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model;
class ComplexItem
{
private $attribute;
private $variadicAttribute;
public function getName()
{
return $this->attribute;
}
/**
* @param $value
*/
public function setValue($value)
{
$this->attribute = $value;
}
public function & getReference()
{
}
/**
* @param mixed ...$variadicValue
*/
public function firstVariadicParameter(...$variadicValue)
{
$this->variadicAttribute = $variadicValue;
}
/**
* @param $value
* @param mixed ...$variadicValue
*/
public function secondVariadicParameter($value, ...$variadicValue)
{
$this->attribute = $value;
$this->variadicAttribute = $variadicValue;
}
/**
* @param mixed ...$variadicValue
*/
public function byRefVariadic(& ...$variadicValue)
{
$this->variadicAttribute = $variadicValue;
}
/**
*
*/
public function returnsSelf()
{
return $this;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/Item.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/Item.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model;
class Item
{
/**
* @return string
*/
public function getName()
{
return 'item';
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/SecondItem.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/SecondItem.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model;
class SecondItem
{
/**
* @return string
*/
public function getName()
{
return 'item';
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/Item/Enhanced.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/Item/Enhanced.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\Item;
class Enhanced extends \Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\Item
{
/**
* @return string
*/
public function getName()
{
return ucfirst(parent::getName());
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Advanced.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Advanced.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin;
class Advanced
{
/**
* @param $subject
* @param $proceed
* @param $argument
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundGetName($subject, $proceed, $argument)
{
return '[' . $proceed($argument) . ']';
}
/**
* @param $subject
* @param $result
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetName($subject, $result)
{
return $result . '%';
}
/**
* @param $subject
* @param $result
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeGetName($subject)
{
//
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Complex.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Complex.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin;
class Complex
{
/**
* @param $subject
* @param $proceed
* @param $arg
* @return string
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundGetName($subject, $proceed, $arg)
{
return '[' . $proceed($arg) . ']';
}
/**
* @param $subject
* @param $result
* @return string
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetName($subject, $result)
{
return $result . '%';
}
/**
* @param $subject
* @param $proceed
* @param $arg
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundSetValue($subject, $proceed, $arg)
{
return $proceed('[' . $arg . ']');
}
/**
* @param $subject
* @param $arg
* @return string
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeSetValue($subject, $arg)
{
return '%' . $arg;
}
/**
* @param $subject
* @param $proceed
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundGetReference($subject, $proceed)
{
return $proceed();
}
/**
* @param $subject
* @param $proceed
* @param mixed ...$variadicValue
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundFirstVariadicParameter($subject, $proceed, ...$variadicValue)
{
return $proceed();
}
/**
* @param $subject
* @param $proceed
* @param $value
* @param mixed ...$variadicValue
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundSecondVariadicParameter($subject, $proceed, $value, ...$variadicValue)
{
return $proceed();
}
/**
* @param $subject
* @param $proceed
* @param mixed ...$variadicValue
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundByRefVariadic($subject, $proceed, & ...$variadicValue)
{
return $proceed();
}
/**
* @param $subject
* @param $ret
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterReturnVoid($subject, $ret)
{
}
/**
* @param $subject
* @param $ret
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetNullableValue($subject, $ret)
{
}
/**
*
*/
public function beforeReturnsSelf()
{
}
/**
*
*/
public function beforeReturnsType()
{
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Simple.php | Test/Integration/CompiledInterceptor/Custom/Module/Model/ItemPlugin/Simple.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin;
class Simple
{
/**
* @param $subject
* @param $invocationResult
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetName($subject, $invocationResult)
{
return $invocationResult . '!';
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Integration/_files/reader_mock_map.php | Test/Integration/_files/reader_mock_map.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ComplexItem;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ComplexItemTyped;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\Item;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\Item\Enhanced;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin\Advanced;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin\Complex;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\ItemPlugin\Simple;
use Creatuity\Interception\Test\Integration\CompiledInterceptor\Custom\Module\Model\SecondItem;
return [
[
'global',
[
Item::class => [
'plugins' => [
'simple_plugin' => [
'sortOrder' => 10,
'instance' => Simple::class,
],
],
],
ComplexItem::class => [
'plugins' => [
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
],
],
[
'backend',
[
Item::class => [
'plugins' => [
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
ComplexItem::class => [
'plugins' => [
'complex_plugin' => [
'sortOrder' => 15,
'instance' => Complex::class,
],
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
ComplexItemTyped::class => [
'plugins' => [
'complex_plugin' => [
'sortOrder' => 25,
'instance' => Complex::class,
],
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
]
],
[
'frontend',
[
Item::class => [
'plugins' => ['simple_plugin' => ['disabled' => true]],
],
Enhanced::class => [
'plugins' => [
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
'SomeType' => [
'plugins' => [
'simple_plugin' => [
'instance' => 'NonExistingPluginClass',
],
],
],
'typeWithoutInstance' => [
'plugins' => [
'simple_plugin' => [],
],
],
SecondItem::class => [
'plugins' => [
'simple_plugin1' => [
'sortOrder' => 5,
'instance' => Simple::class,
],
'advanced_plugin1' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
'advanced_plugin2' => [
'sortOrder' => 10,
'instance' => Advanced::class,
],
'simple_plugin2' => [
'sortOrder' => 11,
'instance' => Simple::class,
],
'simple_plugin3' => [
'sortOrder' => 12,
'instance' => Simple::class,
],
'advanced_plugin3' => [
'sortOrder' => 15,
'instance' => Advanced::class,
],
'advanced_plugin4' => [
'sortOrder' => 25,
'instance' => Advanced::class,
],
],
]
]
],
[
'emptyscope',
[
]
]
];
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/Custom/Module/Model/Item.php | Test/Unit/Custom/Module/Model/Item.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Unit\Custom\Module\Model;
class Item
{
/**
* @return string
*/
public function getName()
{
return 'item';
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/Custom/Module/Model/Item/Enhanced.php | Test/Unit/Custom/Module/Model/Item/Enhanced.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Unit\Custom\Module\Model\Item;
class Enhanced extends \Creatuity\Interception\Test\Unit\Custom\Module\Model\Item
{
/**
* @return string
*/
public function getName()
{
return ucfirst(parent::getName());
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/Custom/Module/Model/ItemPlugin/Advanced.php | Test/Unit/Custom/Module/Model/ItemPlugin/Advanced.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin;
class Advanced
{
/**
* @param $subject
* @param $proceed
* @param $argument
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundGetName($subject, $proceed, $argument)
{
return '[' . $proceed($argument) . ']';
}
/**
* @param $subject
* @param $result
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetName($subject, $result)
{
return $result . '%';
}
/**
* @param $subject
* @param $result
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeGetName($subject)
{
//
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/Custom/Module/Model/ItemPlugin/Simple.php | Test/Unit/Custom/Module/Model/ItemPlugin/Simple.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin;
class Simple
{
/**
* @param $subject
* @param $invocationResult
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetName($subject, $invocationResult)
{
return $invocationResult . '!';
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/CompiledPluginList/CompiledPluginListTest.php | Test/Unit/CompiledPluginList/CompiledPluginListTest.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Creatuity\Interception\Test\Unit\CompiledPluginList;
use Creatuity\Interception\Generator\StaticScope;
use Magento\Framework\App\ObjectManager;
use Creatuity\Interception\Generator\CompiledPluginList;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\Item;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\Item\Enhanced;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Advanced;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Simple;
use Psr\Log\NullLogger;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CompiledPluginListTest extends \PHPUnit\Framework\TestCase
{
/**
* @var CompiledPluginList[]
*/
private $objects;
protected function setUp()
{
$this->objects = $this->createScopeReaders();
}
public function createScopeReaders()
{
$readerMap = include __DIR__ . '/../_files/reader_mock_map.php';
$readerMock = $this->createMock(\Magento\Framework\ObjectManager\Config\Reader\Dom::class);
$readerMock->expects($this->any())->method('read')->will($this->returnValueMap($readerMap));
$omMock = $this->createMock(ObjectManager::class);
$omMock->method('get')->with(\Psr\Log\LoggerInterface::class)->willReturn(new NullLogger());
$omConfigMock = $this->getMockForAbstractClass(
\Magento\Framework\Interception\ObjectManager\ConfigInterface::class
);
$omConfigMock->expects($this->any())->method('getOriginalInstanceType')->will($this->returnArgument(0));
$ret = [];
$objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
foreach ($readerMap as $readerLine) {
$ret[$readerLine[0]] = $objectManagerHelper->getObject(
CompiledPluginList::class,
[
'objectManager' => $omMock,
'scope' => new StaticScope($readerLine[0]),
'reader' => $readerMock,
'omConfig' => $omConfigMock,
'cachePath' => false
]
);
}
return $ret;
}
public function testGetPlugin()
{
$this->objects['backend']->getNext(Item::class, 'getName');
$this->assertEquals(
Simple::class,
$this->objects['backend']->getPluginType(
Item::class,
'simple_plugin'
)
);
$this->assertEquals(
Advanced::class,
$this->objects['backend']->getPluginType(
Item::class,
'advanced_plugin'
)
);
}
/**
* @param $expectedResult
* @param $type
* @param $method
* @param $scopeCode
* @param string $code
* @dataProvider getPluginsDataProvider
*/
public function testGetPlugins($expectedResult, $type, $method, $scopeCode, $code = '__self')
{
$this->assertEquals($expectedResult, $this->objects[$scopeCode]->getNext($type, $method, $code));
}
/**
* @return array
*/
public function getPluginsDataProvider()
{
return [
[
[4 => ['simple_plugin']], Item::class,
'getName',
'global',
],
[
// advanced plugin has lower sort order
[2 => 'advanced_plugin', 4 => ['advanced_plugin'], 1 => ['advanced_plugin']],
Item::class,
'getName',
'backend'
],
[
// advanced plugin has lower sort order
[4 => ['simple_plugin']],
Item::class,
'getName',
'backend',
'advanced_plugin'
],
// simple plugin is disabled in configuration for
// \Creatuity\Interception\Test\Unit\Custom\Module\Model\Item in frontend
[null, Item::class, 'getName', 'frontend'],
// test plugin inheritance
[
[4 => ['simple_plugin']],
Enhanced::class,
'getName',
'global'
],
[
// simple plugin is disabled in configuration for parent
[2 => 'advanced_plugin', 4 => ['advanced_plugin'], 1 => ['advanced_plugin']],
Enhanced::class,
'getName',
'frontend'
]
];
}
/**
* @expectedException \InvalidArgumentException
* @covers \Magento\Framework\Interception\PluginList\PluginList::getNext
* @covers \Magento\Framework\Interception\PluginList\PluginList::_inheritPlugins
*/
public function testInheritPluginsWithNonExistingClass()
{
$this->objects['frontend']->getNext('SomeType', 'someMethod');
}
/**
* @covers \Magento\Framework\Interception\PluginList\PluginList::getNext
* @covers \Magento\Framework\Interception\PluginList\PluginList::_inheritPlugins
*/
public function testInheritPluginsWithNotExistingPlugin()
{
$this->assertNull($this->objects['frontend']->getNext('typeWithoutInstance', 'someMethod'));
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Test/Unit/_files/reader_mock_map.php | Test/Unit/_files/reader_mock_map.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Creatuity\Interception\Test\Unit\Custom\Module\Model\Item;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\Item\Enhanced;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Advanced;
use Creatuity\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Simple;
return [
[
'global',
[
Item::class => [
'plugins' => [
'simple_plugin' => [
'sortOrder' => 10,
'instance' => Simple::class,
],
],
],
],
],
[
'backend',
[
Item::class => [
'plugins' => [
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
]
],
[
'frontend',
[
Item::class => [
'plugins' => ['simple_plugin' => ['disabled' => true]],
],
Enhanced::class => [
'plugins' => [
'advanced_plugin' => [
'sortOrder' => 5,
'instance' => Advanced::class,
],
],
],
'SomeType' => [
'plugins' => [
'simple_plugin' => [
'instance' => 'NonExistingPluginClass',
],
],
],
'typeWithoutInstance' => [
'plugins' => [
'simple_plugin' => [],
],
]
]
],
[
'emptyscope',
[
]
]
];
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/AreasPluginList.php | Generator/AreasPluginList.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Config\Scope;
/**
* Class AreasPluginList
*/
class AreasPluginList
{
/** @var Scope */
private $scope;
/** @var array */
private $plugins;
/**
* AreasPluginList constructor.
* @param Scope $scope
* @param array|null $plugins
*/
public function __construct(
Scope $scope,
$plugins = null
) {
$this->scope = $scope;
$this->plugins = $plugins;
}
/**
* Get array of plugns config indexed by scope code
*
* @return array
*/
public function getPluginsConfigForAllAreas()
{
if ($this->plugins === null) {
$this->plugins = [];
//this is to emulate order M2 is reading scopes config to use scope cache
//"global|primary" should be loaded first and then "global|primary|frontend" etc.
$defaultScopePluginList = $defaultScope = null;
foreach ($this->scope->getAllScopes() as $scope) {
if ($defaultScopePluginList === null) {
$defaultScopePluginList = new CompiledPluginList(
ObjectManager::getInstance(),
new StaticScope($scope)
);
$defaultScopePluginList->getNext('dummy', 'dummy');
$defaultScope = $scope;
} else {
$this->plugins[$scope] = clone $defaultScopePluginList;
$this->plugins[$scope]->setScope(new StaticScope($scope));
//$this->plugins[$scope]->getNext('dummy', 'dummy');
}
}
$this->plugins[$defaultScope] = $defaultScopePluginList;
}
return $this->plugins;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/CompiledInterceptorSubstitution.php | Generator/CompiledInterceptorSubstitution.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Setup\Module\Di\Compiler\Config\Chain\InterceptorSubstitution;
use function array_merge;
use function substr;
/**
* Class CompiledInterceptorSubstitution adds required parameters to interceptor constructor
*/
class CompiledInterceptorSubstitution extends InterceptorSubstitution
{
/**
* Modifies input config
*
* @param array $config
* @return array
*/
public function modify(array $config)
{
$config = parent::modify($config);
foreach ($config['arguments'] as $instanceName => &$arguments) {
$finalInstance = isset($config['instanceTypes'][$instanceName]) ? $config['instanceTypes'][$instanceName] : $instanceName;
if (substr($finalInstance, -12) === '\Interceptor') {
foreach (CompiledInterceptor::propertiesToInjectToConstructor() as $type => $name) {
$preference = isset($config['preferences'][$type]) ? $config['preferences'][$type] : $type;
foreach ($arguments as $argument) {
if (isset($argument['_i_'])) {
//get real type of argument (for cases where there is a virtual type set for injected argument)
$argumentType = isset($config['instanceTypes'][$argument['_i_']]) ? $config['instanceTypes'][$argument['_i_']] : $argument['_i_'];
if ($argumentType == $preference) {
continue 2;
}
}
}
$arguments = array_merge([$name => ['_i_' => $preference]], $arguments);
}
}
}
return $config;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/NoSerialize.php | Generator/NoSerialize.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Framework\Serialize\SerializerInterface;
/**
* Class NoSerialize
*/
class NoSerialize implements SerializerInterface
{
/**
* Serialize data into string
*
* @param string|int|float|bool|array|null $data
* @return string|bool
* @throws \InvalidArgumentException
* @since 101.0.0
*/
public function serialize($data)
{
return $data;
}
/**
* Unserialize the given string
*
* @param string $string
* @return string|int|float|bool|array|null
* @throws \InvalidArgumentException
* @since 101.0.0
*/
public function unserialize($string)
{
return $string;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/CompiledInterceptor.php | Generator/CompiledInterceptor.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Framework\Code\Generator\CodeGeneratorInterface;
use Magento\Framework\Code\Generator\DefinedClasses;
use Magento\Framework\Code\Generator\Io;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Code\Generator\EntityAbstract;
use Magento\Framework\Config\ScopeInterface;
use Magento\Framework\Interception\DefinitionInterface;
use Magento\Setup\Module\Di\App\Task\Operation\Area;
use ReflectionClass;
use ReflectionException;
use ReflectionIntersectionType;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionUnionType;
use function array_combine;
use function array_map;
use function array_merge;
use function array_unshift;
use function count;
use function implode;
use function in_array;
use function ltrim;
use function str_repeat;
use function strrchr;
use function substr;
use function ucfirst;
/**
* Compiled interceptors generator, please see ../README.md for details
*/
class CompiledInterceptor extends EntityAbstract
{
/**
* Entity type
*/
const ENTITY_TYPE = 'interceptor';
private $classMethods;
private $classProperties;
/**
* @var ReflectionClass
*/
private $baseReflection;
/**
* @var AreasPluginList
*/
private $areasPlugins;
/**
* Intercepted methods list
*
* @var array
*/
private $interceptedMethods = [];
/**
* CompiledInterceptor constructor.
* @param AreasPluginList $areasPlugins
* @param null|string $sourceClassName
* @param null|string $resultClassName
* @param Io|null $ioObject
* @param CodeGeneratorInterface|null $classGenerator
* @param DefinedClasses|null $definedClasses
*/
public function __construct(
AreasPluginList $areasPlugins,
$sourceClassName = null,
$resultClassName = null,
?Io $ioObject = null,
?CodeGeneratorInterface $classGenerator = null,
?DefinedClasses $definedClasses = null
) {
parent::__construct(
$sourceClassName,
$resultClassName,
$ioObject,
$classGenerator,
$definedClasses
);
$this->areasPlugins = $areasPlugins;
}
/**
* Unused function required by production mode interface
*
* @param mixed $interceptedMethods
*/
public function setInterceptedMethods($interceptedMethods)
{
//this is not used as methods are read from reflection
$this->interceptedMethods = $interceptedMethods;
}
/**
* Get all class methods
*
* @return array|null
* @throws ReflectionException
*/
protected function _getClassMethods()
{
$this->generateMethodsAndProperties();
return $this->classMethods;
}
/**
* Get all class properties
*
* @return array|null
* @throws ReflectionException
*/
protected function _getClassProperties()
{
$this->generateMethodsAndProperties();
return $this->classProperties;
}
/**
* Get default constructor definition for generated class
*
* @return array
* @throws ReflectionException
*/
protected function _getDefaultConstructorDefinition()
{
return $this->injectPropertiesSettersToConstructor(
$this->getSourceClassReflection()->getConstructor(),
static::propertiesToInjectToConstructor()
);
}
/**
* Generate class source
*
* @return bool|string
* @throws ReflectionException
*/
protected function _generateCode()
{
if ($this->getSourceClassReflection()->isInterface()) {
return false;
} else {
$this->_classGenerator->setExtendedClass($this->getSourceClassName());
}
$this->generateMethodsAndProperties();
return parent::_generateCode();
}
/**
* Generate all methods and properties
*
* @throws ReflectionException
*/
private function generateMethodsAndProperties()
{
if ($this->classMethods === null) {
$this->classMethods = [];
$this->classProperties = [];
foreach (static::propertiesToInjectToConstructor() as $type => $name) {
$this->_classGenerator->addUse($type);
$this->classProperties[] = [
'name' => $name,
'visibility' => 'private',
'docblock' => [
'tags' => [['name' => 'var', 'description' => substr(strrchr($type, "\\"), 1)]],
]
];
}
$this->classMethods[] = $this->_getDefaultConstructorDefinition();
$this->overrideMagicMethods($this->getSourceClassReflection());
$this->overrideMethodsAndGeneratePluginGetters($this->getSourceClassReflection());
}
}
/**
* Get properties to be injected from DI
*
* @return array
*/
public static function propertiesToInjectToConstructor()
{
return [
ScopeInterface::class => '____scope',
ObjectManagerInterface::class => '____om',
];
}
/**
* Get reflection of source class
*
* @return ReflectionClass
* @throws ReflectionException
*/
private function getSourceClassReflection()
{
if ($this->baseReflection === null) {
$this->baseReflection = new ReflectionClass($this->getSourceClassName());
}
return $this->baseReflection;
}
/**
* Whether method is intercepted
*
* @param ReflectionMethod $method
* @return bool
*/
protected function isInterceptedMethod(ReflectionMethod $method)
{
return !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()) &&
!in_array($method->getName(), ['__sleep', '__wakeup', '__clone']);
}
/**
* Generate compiled magic methods (if needed)
*
* @param ReflectionClass $reflection
* @return void
*/
protected function overrideMagicMethods(ReflectionClass $reflection)
{
if ($reflection->hasMethod('__sleep')) {
$this->classMethods[] = $this->compileSleep($reflection->getMethod('__sleep'));
}
if ($reflection->hasMethod('__wakeup')) {
$this->classMethods[] = $this->compileWakeup($reflection->getMethod('__wakeup'));
}
}
/**
* Generate compiled methods and plugin getters
*
* @param ReflectionClass $reflection
*/
private function overrideMethodsAndGeneratePluginGetters(ReflectionClass $reflection)
{
$publicMethods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
$allPlugins = [];
foreach ($publicMethods as $method) {
if ($this->isInterceptedMethod($method)) {
$config = $this->getPluginsConfig($method, $allPlugins);
if (!empty($config)) {
$this->classMethods[] = $this->getCompiledMethodInfo($method, $config);
}
}
}
foreach ($allPlugins as $plugins) {
foreach ($plugins as $plugin) {
$this->classMethods[] = $this->getPluginGetterInfo($plugin);
$this->classProperties[] = $this->getPluginPropertyInfo($plugin);
}
}
}
/**
* Generate class constructor adding required properties when types are not present in parent constructor
*
* @param ReflectionMethod|null $parentConstructor
* @param array $properties
* @return array
*/
private function injectPropertiesSettersToConstructor(
?ReflectionMethod $parentConstructor = null,
$properties = []
) {
if ($parentConstructor == null) {
$parameters = [];
$body = [];
} else {
$parameters = $parentConstructor->getParameters();
$parentCallParams = [];
foreach ($parameters as $parameter) {
$parentCallParams[] = '$' . $parameter->getName();
}
$body = ["parent::__construct(" . implode(', ', $parentCallParams) . ");"];
}
$extraParams = $properties;
$extraSetters = array_combine($properties, $properties);
foreach ($parameters as $parameter) {
if ($parameter->getType()) {
$type = $parameter->getType()->getName();
if (isset($properties[$type])) {
$extraSetters[$properties[$type]] = $parameter->getName();
unset($extraParams[$type]);
}
}
}
$parameters = array_map([$this, '_getMethodParameterInfo'], $parameters);
foreach ($extraParams as $type => $name) {
array_unshift(
$parameters,
[
'name' => $name,
'type' => $type
]
);
}
foreach ($extraSetters as $name => $paramName) {
array_unshift($body, "\$this->$name = \$$paramName;");
}
return [
'name' => '__construct',
'parameters' => $parameters,
'body' => implode("\n", $body),
'docblock' => ['shortDescription' => '{@inheritdoc}'],
];
}
/**
* Adds tabulation to nested code block
*
* @param array $body
* @param array $sub
* @param int $indent
*/
private function addCodeSubBlock(&$body, $sub, $indent = 1)
{
foreach ($sub as $line) {
$body[] = str_repeat("\t", $indent) . $line;
}
}
/**
* Generate source of magic method __sleep
*
* @param ReflectionMethod $parentSleepMethod
* @return array
*/
private function compileSleep(ReflectionMethod $parentSleepMethod)
{
$body = [
'$properties = parent::__sleep();',
'return \array_diff(',
"\t" . '$properties,',
"\t" . '[',
];
foreach (static::propertiesToInjectToConstructor() as $name) {
$body[] = "\t\t'$name',";
}
$body[] = "\t" . ']';
$body[] = ');';
return [
'name' => '__sleep',
'parameters' => [],
'body' => implode("\n", $body),
'docblock' => ['shortDescription' => '{@inheritdoc}'],
];
}
/**
* Generate source of magic method __wakeup
*
* @param ReflectionMethod $parentSleepMethod
* @return array
*/
private function compileWakeup(ReflectionMethod $parentSleepMethod)
{
$body = [
'parent::__wakeup();',
'$objectManager = \Magento\Framework\App\ObjectManager::getInstance();',
];
foreach (static::propertiesToInjectToConstructor() as $type => $name) {
$body[] = '$this->' . $name . ' = $objectManager->get(\\' . $type . '::class);';
}
return [
'name' => '__wakeup',
'parameters' => [],
'body' => implode("\n", $body),
'docblock' => ['shortDescription' => '{@inheritdoc}'],
];
}
/**
* Generate source of before plugins
*
* @param array $plugins
* @param string $methodName
* @param string $extraParams
* @param string $parametersList
* @return array
*/
private function compileBeforePlugins($plugins, $methodName, $extraParams, $parametersList)
{
$lines = [];
foreach ($plugins as $plugin) {
$call = "\$this->" . $this->getGetterName($plugin) . "()->$methodName(\$this, ...\array_values(\$arguments));";
if (!empty($parametersList)) {
$lines[] = "\$beforeResult = " . $call;
$lines[] = "if (\$beforeResult !== null) \$arguments = (array)\$beforeResult;";
} else {
$lines[] = $call;
}
$lines[] = "";
}
return $lines;
}
/**
* Generate source of around plugin
*
* @param string $methodName
* @param array $plugin
* @param string $capitalizedName
* @param string $extraParams
* @param array $parameters
* @param bool $returnVoid
* @return array
*/
private function compileAroundPlugin($methodName, $plugin, $capitalizedName, $extraParams, $parameters, $returnVoid)
{
$lines = [];
$lines[] = "\$this->{$this->getGetterName($plugin)}()->around$capitalizedName" .
"(\$this, function(...\$arguments){";
$this->addCodeSubBlock(
$lines,
$this->getMethodSourceFromConfig($methodName, $plugin['next'] ?: [], $parameters, $returnVoid)
);
$lines[] = "}, ...\array_values(\$arguments));";
return $lines;
}
/**
* Generate source of after plugins
*
* @param array $plugins
* @param string $methodName
* @param string $extraParams
* @param bool $returnVoid
* @return array
*/
private function compileAfterPlugins($plugins, $methodName, $extraParams, $returnVoid)
{
$lines = [];
foreach ($plugins as $plugin) {
$call = "\$this->" . $this->getGetterName($plugin) . "()->$methodName(\$this, ";
if (!$returnVoid) {
$lines[] = ["((\$tmp = $call\$result, ...\array_values(\$arguments))) !== null) ? \$tmp : \$result;"];
} else {
$lines[] = ["{$call}null, ...\array_values(\$arguments));"];
}
}
return $lines;
}
/**
* Generate interceptor source using config
*
* @param string $methodName
* @param array $conf
* @param array $parameters
* @param bool $returnVoid
* @return array
*/
private function getMethodSourceFromConfig($methodName, $conf, $parameters, $returnVoid)
{
$capitalizedName = ucfirst($methodName);
$parametersList = $this->getParameterList($parameters);
$extraParams = empty($parameters) ? '' : (', ' . $parametersList);
if (isset($conf[DefinitionInterface::LISTENER_BEFORE])) {
$body = $this->compileBeforePlugins(
$conf[DefinitionInterface::LISTENER_BEFORE],
'before' . $capitalizedName,
$extraParams,
$parametersList
);
} else {
$body = [];
}
array_unshift($body, '$arguments = \func_get_args();');
$resultChain = [];
if (isset($conf[DefinitionInterface::LISTENER_AROUND])) {
$resultChain[] = $this->compileAroundPlugin(
$methodName,
$conf[DefinitionInterface::LISTENER_AROUND],
$capitalizedName,
$extraParams,
$parameters,
$returnVoid
);
} else {
$resultChain[] = ["parent::{$methodName}(...\array_values(\$arguments));"];
}
if (isset($conf[DefinitionInterface::LISTENER_AFTER])) {
$resultChain = array_merge(
$resultChain,
$this->compileAfterPlugins(
$conf[DefinitionInterface::LISTENER_AFTER],
'after' . $capitalizedName,
$extraParams,
$returnVoid
)
);
}
return array_merge($body, $this->getResultChainLines($resultChain, $returnVoid));
}
/**
* Implode result chain into list of assignments
*
* @param array $resultChain
* @param bool $returnVoid
* @return array
*/
private function getResultChainLines($resultChain, $returnVoid)
{
$lines = [];
$first = true;
foreach ($resultChain as $lp => $piece) {
if ($first) {
$first = false;
} else {
$lines[] = "";
}
if (!$returnVoid) {
$piece[0] = (($lp + 1 == count($resultChain)) ? "return " : "\$result = ") . $piece[0];
}
foreach ($piece as $line) {
$lines[] = $line;
}
}
return $lines;
}
/**
* Implodes parameters into list for call
*
* @param array(\ReflectionParameter) $parameters
* @return string
*/
private function getParameterList(array $parameters)
{
$ret = [];
foreach ($parameters as $parameter) {
$ret [] = "\${$parameter->getName()}";
}
return implode(', ', $ret);
}
/**
* Get plugin getter name
*
* @param array $plugin
* @return string
*/
private function getGetterName($plugin)
{
return '____plugin_' . $plugin['clean_name'];
}
/**
* Get plugin property cache attribute
*
* @param array $plugin
* @return array
*/
private function getPluginPropertyInfo($plugin)
{
return [
'name' => '____plugin_' . $plugin['clean_name'],
'visibility' => 'private',
'docblock' => [
'tags' => [['name' => 'var', 'description' => '\\' . $plugin['class']]],
]
];
}
/**
* Prepares plugin getter for code generator
*
* @param array $plugin
* @return array
*/
private function getPluginGetterInfo($plugin)
{
$body = [];
$varName = "\$this->____plugin_" . $plugin['clean_name'];
$body[] = "if ($varName === null) {";
$body[] = "\t$varName = \$this->____om->get(\\" . "{$plugin['class']}::class);";
$body[] = "}";
$body[] = "return $varName;";
return [
'name' => $this->getGetterName($plugin),
'visibility' => 'private',
'parameters' => [],
'body' => implode("\n", $body),
'docblock' => [
'shortDescription' => 'plugin "' . $plugin['code'] . '"' . "\n" . '@return \\' . $plugin['class']
],
];
}
/**
* Get compiled method data for code generator
*
* @param ReflectionMethod $method
* @param array $config
* @return array
*/
private function getCompiledMethodInfo(ReflectionMethod $method, $config)
{
$parameters = $method->getParameters();
$returnsVoid = ($method->hasReturnType() && $method->getReturnType() instanceof ReflectionNamedType && $method->getReturnType()->getName() == 'void');
$cases = $this->getScopeCasesFromConfig($config);
if (count($cases) == 1) {
$body = $this->getMethodSourceFromConfig($method->getName(), $cases[0]['conf'], $parameters, $returnsVoid);
} else {
$body = [
'switch ($this->____scope->getCurrentScope()) {'
];
foreach ($cases as $case) {
$body = array_merge($body, $case['cases']);
$this->addCodeSubBlock(
$body,
$this->getMethodSourceFromConfig($method->getName(), $case['conf'], $parameters, $returnsVoid),
2
);
if ($returnsVoid) {
$body[] = "\t\tbreak;";
}
}
$body[] = "}";
}
$returnTypeValue = null;
$returnType = $method->getReturnType();
$isUnionReturnType = ($method->hasReturnType() && $method->getReturnType() instanceof ReflectionUnionType);
if ($isUnionReturnType) {
foreach ($method->getReturnType()->getTypes() as $methodReturnTypesItem) {
$methodReturnTypeValue = $methodReturnTypesItem
? ($methodReturnTypesItem->getName() !== 'null' && $methodReturnTypesItem->allowsNull() ? '?' : '') . $methodReturnTypesItem->getName()
: null;
if ($methodReturnTypeValue === 'self') {
$methodReturnTypeValue = $methodReturnTypesItem->getDeclaringClass()->getName();
}
if (!$returnTypeValue) {
$returnTypeValue = $methodReturnTypeValue;
} else {
$returnTypeValue .= '|' . $methodReturnTypeValue;
}
}
}
$isIntersectionType = ($method->hasReturnType() && $method->getReturnType() instanceof ReflectionIntersectionType);
if ($isIntersectionType) {
foreach ($method->getReturnType()->getTypes() as $methodReturnTypesItem) {
$methodReturnTypeValue = $methodReturnTypesItem
? ($methodReturnTypesItem->getName() !== 'null' && $methodReturnTypesItem->allowsNull() ? '?' : '') . $methodReturnTypesItem->getName()
: null;
if ($methodReturnTypeValue === 'self') {
$methodReturnTypeValue = $methodReturnTypesItem->getDeclaringClass()->getName();
}
if (!$returnTypeValue) {
$returnTypeValue = $methodReturnTypeValue;
} else {
$returnTypeValue .= '&' . $methodReturnTypeValue;
}
}
}
if (!$returnTypeValue) {
$returnTypeValue = $returnType
? ($returnType->allowsNull() ? '?' : '') . $returnType->getName()
: null;
if ($returnTypeValue === 'self') {
$returnTypeValue = $method->getDeclaringClass()->getName();
}
if ($returnType && $returnType->getName() === 'mixed') {
$returnTypeValue = 'mixed';
}
}
return [
'name' => ($method->returnsReference() ? '& ' : '') . $method->getName(),
'parameters' => array_map([$this, '_getMethodParameterInfo'], $parameters),
'body' => implode("\n", $body),
'returnType' => $returnTypeValue,
'docblock' => ['shortDescription' => '{@inheritdoc}'],
];
}
/**
* Get scope cases from config
*
* @param array $config
* @return array
*/
private function getScopeCasesFromConfig($config)
{
$cases = [];
//group cases by config
foreach ($config as $scope => $conf) {
$caseStr = "\tcase '$scope':";
foreach ($cases as &$case) {
if ($case['conf'] == $conf) {
$case['cases'][] = $caseStr;
continue 2;
}
}
$cases[] = ['cases'=>[$caseStr], 'conf'=>$conf];
}
$cases[count($cases) - 1]['cases'] = ["\tdefault:"];
return $cases;
}
/**
* Generate array with plugin info
*
* @param CompiledPluginList $plugins
* @param string $code
* @param string $className
* @param array $allPlugins
* @param null|string $next
* @return mixed
*/
private function getPluginInfo(CompiledPluginList $plugins, $code, $className, &$allPlugins, $next = null)
{
$className = $plugins->getPluginType($className, $code);
if (!isset($allPlugins[$code])) {
$allPlugins[$code] = [];
}
if (empty($allPlugins[$code][$className])) {
$suffix = count($allPlugins[$code]) ? count($allPlugins[$code]) + 1 : '';
$allPlugins[$code][$className] = [
'code' => $code,
'class' => $className,
'clean_name' => preg_replace("/[^A-Za-z0-9_]/", '_', $code . $suffix)
];
}
$result = $allPlugins[$code][$className];
$result['next'] = $next;
return $result;
}
/**
* Get next set of plugins
*
* @param CompiledPluginList $plugins
* @param string $className
* @param string $method
* @param array $allPlugins
* @param string $next
* @return array
*/
private function getPluginsChain(CompiledPluginList $plugins, $className, $method, &$allPlugins, $next = '__self')
{
$result = $plugins->getNext($className, $method, $next);
if (!empty($result[DefinitionInterface::LISTENER_BEFORE])) {
foreach ($result[DefinitionInterface::LISTENER_BEFORE] as $k => $code) {
$result[DefinitionInterface::LISTENER_BEFORE][$k] = $this->getPluginInfo(
$plugins,
$code,
$className,
$allPlugins
);
}
}
if (!empty($result[DefinitionInterface::LISTENER_AFTER])) {
foreach ($result[DefinitionInterface::LISTENER_AFTER] as $k => $code) {
$result[DefinitionInterface::LISTENER_AFTER][$k] = $this->getPluginInfo(
$plugins,
$code,
$className,
$allPlugins
);
}
}
if (isset($result[DefinitionInterface::LISTENER_AROUND])) {
$result[DefinitionInterface::LISTENER_AROUND] = $this->getPluginInfo(
$plugins,
$result[DefinitionInterface::LISTENER_AROUND],
$className,
$allPlugins,
$this->getPluginsChain(
$plugins,
$className,
$method,
$allPlugins,
$result[DefinitionInterface::LISTENER_AROUND]
)
);
}
return $result;
}
/**
* Generates recursive maps of plugins for given method
*
* @param ReflectionMethod $method
* @param array $allPlugins
* @return array
*/
private function getPluginsConfig(ReflectionMethod $method, &$allPlugins)
{
$className = ltrim($this->getSourceClassName(), '\\');
$result = [];
$hasEmptyScopes = false;
foreach ($this->areasPlugins->getPluginsConfigForAllAreas() as $scope => $pluginsList) {
$pluginChain = $this->getPluginsChain($pluginsList, $className, $method->getName(), $allPlugins);
if ($pluginChain) {
$result[$scope] = $pluginChain;
} else {
$hasEmptyScopes = true;
}
}
//if plugins are not empty and there are scopes with no plugins make sure default/empty case will be handled
if (!empty($result) && $hasEmptyScopes) {
$result['_empty'] = [];
}
return $result;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/StaticScope.php | Generator/StaticScope.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Framework\Config\ScopeInterface;
/**
* Class StaticScope
*/
class StaticScope implements ScopeInterface
{
/**
* @var string
*/
protected $scope;
/**
* StaticScope constructor.
*
* @param string $scope
*/
public function __construct($scope)
{
$this->scope = $scope;
}
/**
* Get current configuration scope identifier
*
* @return string
*/
public function getCurrentScope()
{
return $this->scope;
}
/**
* Unused interface method
*
* @param string $scope
*/
public function setCurrentScope($scope)
{
$this->scope = $scope;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/FileCache.php | Generator/FileCache.php | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Creatuity\Interception\Generator;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Config\CacheInterface;
use function dirname;
use function file_exists;
use function file_put_contents;
use function glob;
use function is_dir;
use function is_file;
use function mkdir;
use function str_replace;
use function unlink;
use function var_export;
use const BP;
use const DIRECTORY_SEPARATOR;
/**
* Class FileCache
*/
class FileCache implements CacheInterface
{
private $cachePath;
/**
* FileCache constructor.
* @param null|string $cachePath
*/
public function __construct($cachePath = null)
{
if ($cachePath === null) {
$this->cachePath = BP . DIRECTORY_SEPARATOR .
DirectoryList::GENERATED . DIRECTORY_SEPARATOR .
'staticcache';
} else {
$this->cachePath = $cachePath;
}
}
/**
* Get cache path
*
* @param string $identifier
* @return string
*/
private function getCachePath($identifier)
{
$identifier = str_replace('|', '_', $identifier);
return $this->cachePath . DIRECTORY_SEPARATOR . $identifier . '.php';
}
/**
* Test if a cache is available for the given id
*
* @param string $identifier Cache id
* @return int|bool Last modified time of cache entry if it is available, false otherwise
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function test($identifier)
{
return file_exists($this->getCachePath($identifier));
}
/**
* Load cache record by its unique identifier
*
* @param string $identifier
* @return string|bool
* @SuppressWarnings(PHPMD)
*/
public function load($identifier)
{
// @codingStandardsIgnoreLine
return $this->cachePath ? @include $this->getCachePath($identifier) : false;
}
/**
* Save cache record
*
* @param string $data
* @param string $identifier
* @param array $tags
* @param int|bool|null $lifeTime
* @return bool
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function save($data, $identifier, array $tags = [], $lifeTime = null)
{
if ($this->cachePath) {
$path = $this->getCachePath($identifier);
if (!is_dir(dirname($path))) {
mkdir(dirname($path), 0777, true);
}
file_put_contents(
$path,
'<?php return ' . var_export($data, true) . '?>'
);
return true;
}
}
/**
* Remove cache record by its unique identifier
*
* @param string $identifier
* @return bool
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function remove($identifier)
{
return false;
}
/**
* Clean cache records matching specified tags
*
* @param string $mode
* @param array $tags
* @return bool
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function clean($mode = \Zend_Cache::CLEANING_MODE_ALL, array $tags = [])
{
if ($this->cachePath) {
foreach (glob($this->cachePath . '/*') as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
}
return false;
}
/**
* Retrieve backend instance
*
* @return \Zend_Cache_Backend_Interface
*/
public function getBackend()
{
return null;
}
/**
* Retrieve frontend instance compatible with Zend Locale Data setCache() to be used as a workaround
*
* @return \Zend_Cache_Core
*/
public function getLowLevelFrontend()
{
return null;
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
creatuity/magento2-interceptors | https://github.com/creatuity/magento2-interceptors/blob/37e9f4b7df3439230e5585fbf55a038e2cc22766/Generator/CompiledPluginList.php | Generator/CompiledPluginList.php | <?php
namespace Creatuity\Interception\Generator;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Config\ReaderInterface;
use Magento\Framework\Config\ScopeInterface;
use Magento\Framework\Interception\Definition\Runtime as InterceptionDefinitionRuntime;
use Magento\Framework\Interception\ObjectManager\ConfigInterface;
use Magento\Framework\Interception\PluginList\PluginList;
use Magento\Framework\Interception\PluginListGenerator;
use Magento\Framework\ObjectManager\Config\Reader\Dom;
use Magento\Framework\ObjectManager\Definition\Runtime as ObjectManagerDefinitionRuntime;
use Magento\Framework\ObjectManager\Relations\Runtime as ObjectManagerRelationsRuntime;
use function class_exists;
/**
* Class CompiledPluginList
*/
class CompiledPluginList extends PluginList
{
/**
* CompiledPluginList constructor.
* @param ObjectManager $objectManager
* @param ScopeInterface $scope
* @param null|ReaderInterface $reader
* @param null|ConfigInterface $omConfig
* @param null|string $cachePath
*/
public function __construct(
ObjectManager $objectManager,
ScopeInterface $scope,
?ReaderInterface $reader = null,
?ConfigInterface $omConfig = null,
$cachePath = null
) {
if (!$reader || !$omConfig) {
$reader = $objectManager->get(Dom::class);
$omConfig = $objectManager->get(ConfigInterface::class);
}
parent::__construct(
$reader,
$scope,
new FileCache($cachePath),
new ObjectManagerRelationsRuntime(),
$omConfig,
new InterceptionDefinitionRuntime(),
$objectManager,
new ObjectManagerDefinitionRuntime(),
['global'],
'compiled_plugins',
new NoSerialize()
);
}
/**
* Retrieve plugin Instance
*
* @param string $type
* @param string $code
* @return mixed
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getPlugin($type, $code)
{
return null;
}
/**
* Get class of a plugin
*
* @param string $type
* @param string $code
* @return mixed
*/
public function getPluginType($type, $code)
{
return $this->_inherited[$type][$code]['instance'];
}
/**
* Set current scope
*
* @param ScopeInterface $scope
*/
public function setScope(ScopeInterface $scope)
{
$this->_configScope = $scope;
}
/**
* @inheridoc
*/
protected function _loadScopedData()
{
//this makes plugin work with Magento 2.4.1 as it uses separate PluginListGenerator class with its own scopeConfig
$closure = function ($scope) {
$previousScope = $this->scopeConfig->getCurrentScope();
$this->scopeConfig->setCurrentScope($scope);
return $previousScope;
};
if (class_exists(PluginListGenerator::class)) {
$pluginListGenerator = $this->_objectManager->get(PluginListGenerator::class);
$previousScope = $closure->call($pluginListGenerator, $this->_configScope->getCurrentScope());
parent::_loadScopedData();
$closure->call($pluginListGenerator, $previousScope);
} else {
parent::_loadScopedData();
}
}
}
| php | MIT | 37e9f4b7df3439230e5585fbf55a038e2cc22766 | 2026-01-05T05:02:29.611390Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/example.blade.php | example.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Consent</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap');
body {
font-family: "Inter", sans-serif;
}
</style>
{!! CookieConsent::styles() !!}
</head>
<body>
<!-- Your content -->
{!! CookieConsent::scripts(options: [
'cookie_lifetime' => config('laravel-cookie-consent.cookie_lifetime', 7),
'reject_lifetime' => config('laravel-cookie-consent.reject_lifetime', 1),
'disable_page_interaction' => config('laravel-cookie-consent.disable_page_interaction', true),
'preferences_modal_enabled' => config('laravel-cookie-consent.preferences_modal_enabled', true),
'consent_modal_layout' => config('laravel-cookie-consent.consent_modal_layout', 'bar-inline'),
'flip_button' => config('laravel-cookie-consent.flip_button', true),
'theme' => config('laravel-cookie-consent.theme', 'default'),
'cookie_prefix' => config('laravel-cookie-consent.cookie_prefix', 'Laravel_App'),
'policy_links' => config('laravel-cookie-consent.policy_links', [
['text' => 'Privacy Policy', 'link' => url('privacy-policy')],
['text' => 'Terms & Conditions', 'link' => url('terms-and-conditions')],
]),
'cookie_categories' => config('laravel-cookie-consent.cookie_categories', [
'necessary' => [
'enabled' => true,
'locked' => true,
'js_action' => 'loadGoogleAnalytics',
'title' => 'Essential Cookies',
'description' => 'These cookies are essential for the website to function properly.',
],
'analytics' => [
'enabled' => env('COOKIE_CONSENT_ANALYTICS', false),
'locked' => false,
'title' => 'Analytics Cookies',
'description' => 'These cookies help us understand how visitors interact with our website.',
],
'marketing' => [
'enabled' => env('COOKIE_CONSENT_MARKETING', false),
'locked' => false,
'js_action' => 'loadFacebookPixel',
'title' => 'Marketing Cookies',
'description' => 'These cookies are used for advertising and tracking purposes.',
],
'preferences' => [
'enabled' => env('COOKIE_CONSENT_PREFERENCES', false),
'locked' => false,
'js_action' => 'loadPreferencesFunc',
'title' => 'Preferences Cookies',
'description' => 'These cookies allow the website to remember user preferences.',
],
]),
'cookie_modal_title' => 'Cookie Preferences',
'cookie_modal_intro' => 'You can customize your cookie preferences below.',
'cookie_accept_btn_text' => 'Accept All',
'cookie_reject_btn_text' => 'Reject All',
'cookie_preferences_btn_text' => 'Manage Preferences',
'cookie_preferences_save_text' => 'Save Preferences',
]) !!}
<script>
// Example service loader (replace with your actual implementation)
function loadGoogleAnalytics() {
// Please put your GA script in loadGoogleAnalytics()
// You can define function name from - {!! CookieConsent::scripts() !!}
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_GA_ID');
// Load the GA script
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=YOUR_GA_ID';
script.async = true;
document.head.appendChild(script);
}
function loadFacebookPixel() {
// Please put your marketing script in loadFacebookPixel()
// You can define function name from - {!! CookieConsent::scripts() !!}
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'YOUR_PIXEL_ID');
fbq('track', 'PageView');
}
</script>
</body>
</html> | php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/autoload.php | vendor/autoload.php | <?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit097b259ba67d03f0111b724291f0acdf::getLoader();
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/autoload_real.php | vendor/composer/autoload_real.php | <?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit097b259ba67d03f0111b724291f0acdf
{
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;
}
spl_autoload_register(array('ComposerAutoloaderInit097b259ba67d03f0111b724291f0acdf', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit097b259ba67d03f0111b724291f0acdf', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit097b259ba67d03f0111b724291f0acdf::getInitializer($loader));
$loader->register(true);
return $loader;
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/autoload_namespaces.php | vendor/composer/autoload_namespaces.php | <?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/autoload_psr4.php | vendor/composer/autoload_psr4.php | <?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Devrabiul\\LaravelCookieConsent\\' => array($baseDir . '/src'),
);
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/autoload_static.php | vendor/composer/autoload_static.php | <?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit097b259ba67d03f0111b724291f0acdf
{
public static $prefixLengthsPsr4 = array (
'D' =>
array (
'Devrabiul\\LaravelCookieConsent\\' => 31,
),
);
public static $prefixDirsPsr4 = array (
'Devrabiul\\LaravelCookieConsent\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit097b259ba67d03f0111b724291f0acdf::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit097b259ba67d03f0111b724291f0acdf::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit097b259ba67d03f0111b724291f0acdf::$classMap;
}, null, ClassLoader::class);
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/ClassLoader.php | vendor/composer/ClassLoader.php | <?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 \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @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 list<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)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$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 list<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)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$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] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$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 list<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 list<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 = self::$includeFile;
$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 keyed by their corresponding vendor directories.
*
* @return array<string, 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;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/vendor/composer/autoload_classmap.php | vendor/composer/autoload_classmap.php | <?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/CookieConsentServiceProvider.php | src/CookieConsentServiceProvider.php | <?php
namespace Devrabiul\CookieConsent;
use Exception;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Response;
class CookieConsentServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* This method is called after all other service providers have been registered.
* It is used to perform any actions required to bootstrap the application services.
*
* @return void
* @throws Exception If there is an error during bootstrapping.
*/
public function boot(): void
{
$this->updateProcessingDirectoryConfig();
$this->app->register(AssetsServiceProvider::class);
$this->registerResources();
if ($this->app->runningInConsole()) {
$this->registerPublishing();
}
}
/**
* Register the publishing of configuration files.
*
* This method registers the configuration file for publishing to the application's config directory.
*
* @return void
* @throws Exception If there is an error during publishing.
*/
private function registerPublishing(): void
{
// Normal publish
$this->publishes([
__DIR__ . '/config/laravel-cookie-consent.php' => config_path('laravel-cookie-consent.php'),
]);
}
private function registerResources(): void
{
$this->loadRoutesFrom(__DIR__ . '/../routes/laravel-cookie-consent.php');
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'laravel-cookie-consent');
// $this->commands($this->registerCommands());
}
/**
* Register the application services.
*
* This method is called to bind services into the service container.
* It is used to register the CookieConsent service and load the configuration.
*
* @return void
* @throws Exception If the configuration file cannot be loaded.
*/
public function register(): void
{
$configPath = config_path('laravel-cookie-consent.php');
if (!file_exists($configPath)) {
config(['laravel-cookie-consent' => require __DIR__ . '/config/laravel-cookie-consent.php']);
}
$this->app->singleton('CookieConsent', function ($app) {
return new CookieConsent($app['session'], $app['config']);
});
}
/**
* Get the services provided by the provider.
*
* This method returns an array of services that this provider offers.
*
* @return array
* @throws Exception If there is an error retrieving the services.
*/
public function provides(): array
{
return ['CookieConsent'];
}
/**
* Determine and set the 'system_processing_directory' configuration value.
*
* This detects if the current PHP script is being executed from the public directory
* or the project root directory, or neither, and sets a config value accordingly:
*
* - 'public' if script path equals public_path()
* - 'root' if script path equals base_path()
* - 'unknown' otherwise
*
* This config can be used internally to adapt asset loading or paths.
*
* @return void
*/
private function updateProcessingDirectoryConfig(): void
{
$scriptPath = realpath(dirname($_SERVER['SCRIPT_FILENAME']));
$basePath = realpath(base_path());
$publicPath = realpath(public_path());
if ($scriptPath === $publicPath) {
$systemProcessingDirectory = 'public';
} elseif ($scriptPath === $basePath) {
$systemProcessingDirectory = 'root';
} else {
$systemProcessingDirectory = 'unknown';
}
config(['laravel-cookie-consent.system_processing_directory' => $systemProcessingDirectory]);
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/AssetsServiceProvider.php | src/AssetsServiceProvider.php | <?php
namespace Devrabiul\CookieConsent;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\File;
use function PHPUnit\Framework\isNull;
/**
* Class AssetsServiceProvider
*
* Service provider for the CookieConsent Laravel package.
*
* Handles bootstrapping of the package including
* - Setting up asset routes for package resources.
* - Managing version-based asset publishing.
* - Configuring processing directory detection.
* - Registering package publishing commands.
* - Registering the CookieConsent singleton.
*
* @package Devrabiul\CookieConsent
*/
class AssetsServiceProvider extends ServiceProvider
{
/**
* Bootstrap any package services.
*
* This method is called after all other services have been registered,
* allowing you to perform actions like route registration, publishing assets,
* and configuration adjustments.
*
* It:
* - Sets the system processing directory config value.
* - Defines a route for serving package assets in development or fallback.
* - Handles version-based asset publishing, replacing assets if a package version changed.
* - Registers publishable resources when running in console.
*
* @return void
*/
public function boot(): void
{
$this->handleVersionedPublishing(name: 'devrabiul/laravel-cookie-consent');
}
/**
* Register any application services.
*
* This method:
* - Loads the package config file if not already loaded.
* - Registers a singleton instance of the CookieConsent class in the Laravel service container.
*
* This allows other parts of the application to resolve the 'CookieConsent' service.
*
* @return void
*/
public function register(): void
{
//
}
/**
* Get the current installed version of the package from composer.lock.
*
*
* Returns null if:
* - composer.lock does not exist
* - package is not found in composer.lock
*
* @return string|null Version string of the installed package, e.g. "1.0.1" or null if unavailable.
*/
private function getCurrentVersion($name): ?string
{
$lockFile = base_path('composer.lock');
if (!file_exists($lockFile)) {
return null;
}
$lockData = json_decode(file_get_contents($lockFile), true);
$packages = $lockData['packages'] ?? [];
foreach ($packages as $package) {
if ($package['name'] === $name) {
return $package['version'];
}
}
return null;
}
/**
* Get the version recorded in the published version.php file.
*
* If the file exists and returns an array with a 'version' key,
* that version string is returned.
*
* Returns null if the file does not exist or does not contain a version.
*
* @return string|null Previously published version string or null if none found.
*/
private function getPublishedVersion($name): ?string
{
$versionFile = public_path('vendor/'.$name.'/version.php');
if (!File::exists($versionFile)) {
return null;
}
$versionData = include $versionFile;
return $versionData['version'] ?? null;
}
/**
* Publish the assets if the current package version differs from the published version.
*
* This method performs the following steps:
* - Retrieves the current installed package version.
* - Retrieves the previously published version from the public directory.
* - If versions differ (or no published version exists), deletes the existing asset folder.
* - Copies the new assets from the package's `assets` directory to the public vendor folder.
* - Writes/updates the version.php file in the public folder with the current version.
*
* This ensures the public assets are always in sync with the installed package version.
*
* @param string|null $name
* @return void
*/
private function handleVersionedPublishing(?string $name): void
{
$currentVersionRaw = $this->getCurrentVersion(name: $name);
$publishedVersionRaw = $this->getPublishedVersion(name: $name);
$currentVersion = $this->normalizeVersion($currentVersionRaw);
$publishedVersion = $this->normalizeVersion($publishedVersionRaw);
if ((is_null($currentVersion) && is_null($publishedVersion)) || ($currentVersion && $currentVersion !== $publishedVersion)) {
$assetsPath = public_path('vendor/' . $name);
$sourceAssets = base_path('vendor/' . $name . '/assets');
// Ensure source assets exist before proceeding
if (!File::exists($sourceAssets)) {
return;
}
// Delete and re-create the target directory
if (File::exists($assetsPath)) {
File::deleteDirectory($assetsPath);
}
File::ensureDirectoryExists($assetsPath);
File::copyDirectory($sourceAssets, $assetsPath);
// Create version.php file with the current version
$versionPhpContent = "<?php\n\nreturn [\n 'version' => '{$currentVersion}',\n];\n";
File::put(public_path('vendor/' . $name . '/version.php'), $versionPhpContent);
}
}
/**
* Normalize version to numeric-only format (e.g., strip ^, v, ~).
*
* @param string|null $version
* @return string|null
*/
private function normalizeVersion(?string $version): ?string
{
if (!$version) {
return null;
}
// Match numeric versions like 1.0.0, 1.1, 2.3.4-beta1 etc.
if (preg_match('/\d+\.\d+(?:\.\d+)?/', $version, $matches)) {
return $matches[0];
}
return null;
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/CookieConsent.php | src/CookieConsent.php | <?php
namespace Devrabiul\CookieConsent;
use Illuminate\Contracts\View\View;
use Illuminate\Session\SessionManager as Session;
use Illuminate\Config\Repository as Config;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\File;
/**
* Class CookieConsent
*
* Handles the display and management of cookie consent UI components in a Laravel application.
*/
class CookieConsent
{
/**
* The session manager.
*
* @var \Illuminate\Session\SessionManager
*/
protected $session;
/**
* The Config handler instance.
*
* @var \Illuminate\Contracts\Config\Repository
*/
protected $config;
/**
* The JavaScript type for script tags.
*
* @var string
*/
protected string $jsType = 'text/javascript';
/**
* CookieConsent constructor.
*
* @param Session $session The session manager instance.
* @param Config $config The configuration repository instance.
*/
function __construct(Session $session, Config $config)
{
$this->session = $session;
$this->config = $config;
}
/**
* Generate the HTML for the required stylesheet.
*
* @return string The HTML link tag for the stylesheet.
*/
public function styles(): string
{
$stylePath = 'vendor/devrabiul/laravel-cookie-consent/css/style.css';
if (File::exists(public_path($stylePath))) {
return '<link rel="stylesheet" href="' . $this->getDynamicAsset($stylePath) . '">';
}
return '<link rel="stylesheet" href="' . url('vendor/devrabiul/laravel-cookie-consent/assets/css/style.css') . '">';
}
/**
* Render the cookie consent view with the given configuration.
*
* @param array $cookieConfig Optional cookie configuration overrides.
* @return View The cookie consent view.
*/
public function content(array $cookieConfig = [])
{
return view('laravel-cookie-consent::cookie-consent', compact('cookieConfig'));
}
/**
* Generate the HTML for the required JavaScript with optional configuration overrides.
*
* @param array $options Optional configuration overrides.
* @return View The cookie consent script view.
*/
public function scripts(array $options = []): mixed
{
$config = (array)$this->config->get('laravel-cookie-consent');
$config = array_merge($config, $options);
if (isset($config['enabled']) && ($config['enabled'] === false || $config['enabled'] === 'false')) {
return '';
}
return self::content(cookieConfig: $config);
}
/**
* Generate the HTML for the required scripts.
*
* @return string The HTML link tag for the scripts.
*/
public function scriptsPath(): string
{
$script = $this->scriptTag('vendor/devrabiul/laravel-cookie-consent/assets/js/script.js');
$defaultJsPath = 'vendor/devrabiul/laravel-cookie-consent/js/script.js';
if (File::exists(public_path($defaultJsPath))) {
$script = $this->scriptTag($defaultJsPath);
}
$script .= '<script src="' . route('laravel-cookie-consent.script-utils') . '"></script>';
return $script;
}
/**
* Generate a script tag with the given source path.
*
* @param string $src
* @return string
*/
private function scriptTag(string $src): string
{
return '<script src="' . $this->getDynamicAsset($src) . '"></script>';
}
/**
* Resolve the dynamic asset path depending on processing directory and environment.
*
* @param string $path
* @return string
*/
private function getDynamicAsset(string $path): string
{
if (self::getProcessingDirectoryConfig() == 'public') {
$position = strpos($path, 'public/');
$result = $path;
if ($position === 0) {
$result = preg_replace('/public/', '', $path, 1);
}
} else {
$result = in_array(request()->ip(), ['127.0.0.1']) ? $path : 'public/' . $path;
}
return asset($result);
}
private function getProcessingDirectoryConfig(): string
{
$scriptPath = realpath(dirname($_SERVER['SCRIPT_FILENAME']));
$basePath = realpath(base_path());
$publicPath = realpath(public_path());
if ($scriptPath === $publicPath) {
$systemProcessingDirectory = 'public';
} elseif ($scriptPath === $basePath) {
$systemProcessingDirectory = 'root';
} else {
$systemProcessingDirectory = 'unknown';
}
return $systemProcessingDirectory;
}
public static function getRemoveInvalidCharacters($str): array|string
{
return str_ireplace(['"', ';', '<', '>'], ' ', preg_replace('/\s\s+/', ' ', $str));
}
/**
* Translates a given key using the `messages.php` language file in the current locale.
*
* - If the key does not exist in the file, it creates the file and inserts the key with a default value.
* - It ensures the required language directory and file exist.
* - Falls back to Laravel translation helper if the key is not found after insertion.
*
* @param string $key The translation key, e.g. 'messages.privacy_policy'.
* @param null $default The default value to use if the key doesn't exist.
*/
public static function translate(string $key, $default = null)
{
$locale = app()->getLocale();
$langDir = resource_path("lang/{$locale}");
$filePath = "{$langDir}/messages.php";
// Ensure the directory exists
if (!File::exists($langDir)) {
File::makeDirectory($langDir, 0755, true);
}
// If the file doesn't exist, create it with an empty array
if (!File::exists($filePath)) {
File::put($filePath, "<?php\n\nreturn [\n];");
}
try {
// Load existing translations
$translations = File::getRequire($filePath);
if (!empty($key)) {
$processedKey = str_replace('_', ' ', CookieConsent::getRemoveInvalidCharacters(str_replace("\'", "'", $key)));
$actualKey = CookieConsent::getRemoveInvalidCharacters($key);
// Add key if it doesn't exist
if (!array_key_exists($actualKey, $translations)) {
$translations[$actualKey] = $default ?? $processedKey;
$content = "<?php\n\nreturn [\n";
foreach ($translations as $k => $v) {
$content .= " '{$k}' => '{$v}',\n";
}
$content .= "];\n";
File::put($filePath, $content);
} elseif (array_key_exists($actualKey, $translations)) {
return $translations[$actualKey] ?? $default;
} else {
return __('messages.' . $actualKey);
}
}
} catch (\Exception $exception) {
}
return $key;
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/Http/Controllers/CookieConsentController.php | src/Http/Controllers/CookieConsentController.php | <?php
namespace Devrabiul\CookieConsent\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class CookieConsentController extends Controller
{
public function scriptUtils(Request $request)
{
$script = <<<JS
window.onload = function() {
// console.log('Hi');
};
JS;
return response($script, 200)->header('Content-Type', 'application/javascript');
}
}
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/Facades/CookieConsent.php | src/Facades/CookieConsent.php | <?php
namespace Devrabiul\CookieConsent\Facades;
use Illuminate\Support\Facades\Facade;
class CookieConsent extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'CookieConsent';
}
} | php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/src/config/laravel-cookie-consent.php | src/config/laravel-cookie-consent.php | <?php
/**
* Cookie Consent Configuration
*
* This file contains all the configuration options for the cookie consent system.
* It allows customization of the cookie banner appearance, behavior, and compliance settings.
*
* @package Config
* @author Muhammad Rabiul
* @license MIT
*/
return [
/*
|--------------------------------------------------------------------------
| Cookie Consent Prefix
|--------------------------------------------------------------------------
| This setting determines whether the cookie consent banner should be displayed.
| Set this value to 'true' to show the banner or 'false' to disable it.
| You can control this via the .env file using APP_NAME.
*/
'cookie_prefix' => env('APP_NAME', 'Laravel_App'),
/**
* Enable or disable the cookie consent banner
*
* @default true
* @env COOKIE_CONSENT_ENABLED
*/
'enabled' => env('COOKIE_CONSENT_ENABLED', true),
/**
* Cookie lifetime in days
*
* Defines how long the consent cookie should persist in the user's browser.
*
* @default 365
* @env COOKIE_CONSENT_LIFETIME
*/
'cookie_lifetime' => env('COOKIE_CONSENT_LIFETIME', 365),
/**
* Rejection cookie lifetime in days
*
* Specifies how long the rejection cookie should persist when users decline cookies.
*
* @default 7
* @env COOKIE_REJECT_LIFETIME
*/
'reject_lifetime' => env('COOKIE_REJECT_LIFETIME', 7),
/**
* Consent modal layout style
*
* Determines the visual presentation of the consent modal.
*
* @default 'bar-inline'
* @env COOKIE_CONSENT_MODAL_LAYOUT
* @option box - Small floating box
* @option box-inline - Small floating box positioned inline
* @option box-wide - Larger floating box
* @option cloud - Cloud-like floating consent box
* @option cloud-inline - Compact cloud-style box
* @option bar - Simple bar at top or bottom
* @option bar-inline - Compact inline bar
*/
'consent_modal_layout' => env('COOKIE_CONSENT_MODAL_LAYOUT', 'bar'),
/**
* Enable preferences modal
*
* Determines if users can access detailed cookie preferences.
*
* @default false
* @env COOKIE_CONSENT_PREFERENCES_ENABLED
*/
'preferences_modal_enabled' => env('COOKIE_CONSENT_PREFERENCES_ENABLED', true),
/**
* Preferences modal layout style
*
* Defines the visual presentation of the preferences modal.
*
* @default 'bar'
* @env COOKIE_CONSENT_PREFERENCES_LAYOUT
* @option bar - Bar-style modal
* @option box - Popup-style box
*/
'preferences_modal_layout' => env('COOKIE_CONSENT_PREFERENCES_LAYOUT', 'bar'),
/**
* Enable flip button animation
*
* Adds a flip animation effect to consent buttons.
*
* @default true
* @env COOKIE_CONSENT_FLIP_BUTTON
*/
'flip_button' => env('COOKIE_CONSENT_FLIP_BUTTON', true),
/**
* Disable page interaction until consent
*
* When enabled, users must interact with the cookie banner before accessing content.
*
* @default true
* @env COOKIE_CONSENT_DISABLE_INTERACTION
*/
'disable_page_interaction' => env('COOKIE_CONSENT_DISABLE_INTERACTION', true),
/**
* Color theme for the cookie banner
*
* @default 'default'
* @env COOKIE_CONSENT_THEME
* @option default - Standard theme
* @option dark - Dark mode theme
* @option light - Light mode theme
* @option custom - Custom styles (requires additional CSS)
*/
'theme' => env('COOKIE_CONSENT_THEME', 'default'),
/**
* Cookie banner title text
*
* @default "Cookie Disclaimer"
*/
'cookie_title' => "Cookie Disclaimer",
/**
* Cookie banner description text
*
* @default "This website uses cookies to enhance your browsing experience, analyze site traffic, and personalize content. By continuing to use this site, you consent to our use of cookies."
*/
'cookie_description' => "This website uses cookies to enhance your browsing experience, analyze site traffic, and personalize content. By continuing to use this site, you consent to our use of cookies.",
/**
* Accept all cookies button text
*
* @default 'Accept all'
*/
'cookie_accept_btn_text' => 'Accept all',
/**
* Reject all cookies button text
*
* @default 'Reject all'
*/
'cookie_reject_btn_text' => 'Reject all',
/**
* Manage preferences button text
*
* @default 'Manage preferences'
*/
'cookie_preferences_btn_text' => 'Manage preferences',
/**
* Save preferences button text
*
* @default 'Save preferences'
*/
'cookie_preferences_save_text' => 'Save preferences',
/**
* Preferences modal title text
*
* @default 'Cookie Preferences'
*/
'cookie_modal_title' => 'Cookie Preferences',
/**
* Preferences modal introduction text
*
* @default 'You can customize your cookie preferences below.'
*/
'cookie_modal_intro' => 'You can customize your cookie preferences below.',
/**
* Cookie categories configuration
*
* Defines the different types of cookies users can manage.
*
* @category necessary - Essential cookies that cannot be disabled
* @category analytics - Cookies used for tracking and analytics
* @category marketing - Cookies used for advertising
* @category preferences - Cookies for user preference storage
*/
'cookie_categories' => [
'necessary' => [
'enabled' => true,
'locked' => true,
'title' => 'Essential Cookies',
'description' => 'These cookies are essential for the website to function properly.',
],
'analytics' => [
'enabled' => env('COOKIE_CONSENT_ANALYTICS', false),
'locked' => false,
'js_action' => 'loadGoogleAnalytics',
'title' => 'Analytics Cookies',
'description' => 'These cookies help us understand how visitors interact with our website.',
],
'marketing' => [
'enabled' => env('COOKIE_CONSENT_MARKETING', false),
'locked' => false,
'js_action' => 'loadFacebookPixel',
'title' => 'Marketing Cookies',
'description' => 'These cookies are used for advertising and tracking purposes.',
],
'preferences' => [
'enabled' => env('COOKIE_CONSENT_PREFERENCES', false),
'locked' => false,
'title' => 'Preferences Cookies',
'description' => 'These cookies allow the website to remember user preferences.',
],
],
/**
* Policy links configuration
*
* Links to legal documents displayed in the cookie banner.
*
* @item text - Display text for the link
* @item link - URL to the policy document
*/
'policy_links' => [
[
'text' => 'Privacy Policy',
'link' => env('COOKIE_CONSENT_PRIVACY_POLICY_URL', '') ?? url('privacy-policy')
],
[
'text' => 'Terms and Conditions',
'link' => env('COOKIE_CONSENT_TERMS_URL', '') ?? url('terms-and-conditions')
],
],
];
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/routes/laravel-cookie-consent.php | routes/laravel-cookie-consent.php | <?php
use Illuminate\Support\Facades\Route;
use Devrabiul\CookieConsent\Http\Controllers\CookieConsentController;
Route::controller(CookieConsentController::class)->group(function () {
Route::get('/laravel-cookie-consent/script-utils', 'scriptUtils')->name('laravel-cookie-consent.script-utils');
});
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/assets/version.php | assets/version.php | <?php
return [
'version' => 'v1.1',
];
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
devrabiul/laravel-cookie-consent | https://github.com/devrabiul/laravel-cookie-consent/blob/11b54b1bd031c7a256412ff51a2a46cd9adaa3d8/resources/views/cookie-consent.blade.php | resources/views/cookie-consent.blade.php | <!-- Main Cookie Consent Banner -->
<div class="cookie-consent-root
cookie-consent-hide
{{ $cookieConfig['disable_page_interaction'] ? 'cookie-disable-interaction' : '' }}
consent-layout-{{ $cookieConfig['consent_modal_layout'] ?? 'bar' }}
theme-{{ $cookieConfig['theme'] ?? 'default' }}"
data-cookie-prefix="{{ Str::slug($cookieConfig['cookie_prefix']) }}_{{ date('Y') }}"
data-cookie-lifetime="{{ $cookieConfig['cookie_lifetime'] }}"
data-reject-lifetime="{{ $cookieConfig['reject_lifetime'] }}"
role="dialog"
aria-modal="true"
aria-label="Cookie consent banner"
>
<div class="cookie-consent-container">
<div class="cookie-consent-content-container">
<div class="cookie-consent-content">
<h2 class="cookie-consent-content-title">
{{ $cookieConfig['cookie_title'] }}
</h2>
<div class="cookie-consent-content-description">
<p>{{ $cookieConfig['cookie_description'] }}</p>
</div>
</div>
<div class="cookie-consent-button-container">
<div class="cookie-consent-button-action {{ $cookieConfig['flip_button'] ? 'flip-button' : '' }}">
<button type="button" class="cookie-consent-accept" aria-label="Accept all cookies">
{{ $cookieConfig['cookie_accept_btn_text'] }}
</button>
<button type="button" class="cookie-consent-reject" aria-label="Reject all cookies">
{{ $cookieConfig['cookie_reject_btn_text'] }}
</button>
</div>
@if ($cookieConfig['preferences_modal_enabled'])
<button type="button" class="preferences-btn" aria-expanded="false"
aria-controls="cookie-preferences-modal">
{{ $cookieConfig['cookie_preferences_btn_text'] }}
</button>
@endif
</div>
</div>
</div>
@if (isset($cookieConfig['policy_links']) && count($cookieConfig['policy_links']) > 0)
<div class="cookie-consent-links-container">
<ul class="cookie-consent-links-list">
@foreach ($cookieConfig['policy_links'] as $policyLinks)
<li class="cookie-consent-link-item">
<a target="_blank" rel="noopener noreferrer" href="{{ $policyLinks['link'] }}"
class="cookie-consent-link">
{{ $policyLinks['text'] }}
</a>
</li>
@endforeach
</ul>
</div>
@endif
</div>
<!-- Cookie Preferences Modal -->
<div id="cookie-preferences-modal" class="cookie-preferences-modal" aria-hidden="true">
<div class="cookie-preferences-modal-overlay" tabindex="-1"></div>
<div class="cookie-preferences-modal-content" role="document">
<div class="cookie-preferences-modal-header">
<h2 id="cookie-modal-title" class="cookie-preferences-modal-title">
{{ $cookieConfig['cookie_modal_title'] }}
</h2>
<button type="button" class="cookie-preferences-modal-close" aria-label="Close cookie preferences">
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"
aria-hidden="true">
<path d="M12 4L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</button>
</div>
<div class="cookie-preferences-modal-body">
<p class="cookie-preferences-intro">
{{ $cookieConfig['cookie_modal_intro'] }}
</p>
<div class="cookie-categories">
@foreach ($cookieConfig['cookie_categories'] as $category => $details)
@if ($details['enabled'])
<div class="cookie-category cookie-category-{{ $category }}">
<div class="cookie-category-header">
<h3 class="cookie-category-title">{{ $details['title'] }}</h3>
<label class="cookie-toggle">
<input type="checkbox"
{{ $details['locked'] ? 'disabled checked' : '' }}
data-category="{{ $category }}"
aria-label="{{ $details['title'] }} toggle">
<span class="cookie-toggle-slider"></span>
</label>
</div>
<p class="cookie-category-description">{{ $details['description'] }}</p>
</div>
@endif
@endforeach
</div>
</div>
<div class="cookie-preferences-modal-footer">
<div class="cookie-preferences-modal-button-group">
<button type="button" class="cookie-consent-accept primary-button">
{{ $cookieConfig['cookie_accept_btn_text'] }}
</button>
<button type="button" class="cookie-consent-reject primary-button">
{{ $cookieConfig['cookie_reject_btn_text'] }}
</button>
</div>
<div class="cookie-preferences-modal-save">
<button type="button" class="cookie-preferences-save primary-button">
{{ $cookieConfig['cookie_preferences_save_text'] }}
</button>
</div>
</div>
</div>
</div>
{!! CookieConsent::scriptsPath() !!}
<script type="text/javascript">
"use strict";
// Load analytics/tracking services based on preferences
// Then define your service loader
window.loadCookieCategoriesEnabledServices = function () {
const preferences = getCookiePreferences();
if (!preferences) return;
@foreach ($cookieConfig['cookie_categories'] as $category => $details)
@if(isset($details['js_action']))
try {
if (preferences?.{!! Str::slug($category) !!}) {
const action = {!! json_encode($details['js_action']) !!};
if (typeof window[action] === "function") {
window[action]();
}
}
} catch (exception) {
console.info(exception)
}
@endif
@endforeach
}
document.addEventListener('DOMContentLoaded', function () {
try {
loadCookieCategoriesEnabledServices();
} catch (e) {
console.info(e);
}
})
</script>
| php | MIT | 11b54b1bd031c7a256412ff51a2a46cd9adaa3d8 | 2026-01-05T05:02:38.493104Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/HelpersServiceProvider.php | src/HelpersServiceProvider.php | <?php
namespace Encore\Admin\Helpers;
use Illuminate\Support\ServiceProvider;
class HelpersServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'laravel-admin-helpers');
Helpers::boot();
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Helpers.php | src/Helpers.php | <?php
namespace Encore\Admin\Helpers;
use Encore\Admin\Admin;
use Encore\Admin\Auth\Database\Menu;
use Encore\Admin\Extension;
class Helpers extends Extension
{
/**
* Bootstrap this package.
*
* @return void
*/
public static function boot()
{
static::registerRoutes();
Admin::extend('helpers', __CLASS__);
}
/**
* Register routes for laravel-admin.
*
* @return void
*/
public static function registerRoutes()
{
parent::routes(function ($router) {
/* @var \Illuminate\Routing\Router $router */
$router->get('helpers/terminal/database', 'Encore\Admin\Helpers\Controllers\TerminalController@database');
$router->post('helpers/terminal/database', 'Encore\Admin\Helpers\Controllers\TerminalController@runDatabase');
$router->get('helpers/terminal/artisan', 'Encore\Admin\Helpers\Controllers\TerminalController@artisan');
$router->post('helpers/terminal/artisan', 'Encore\Admin\Helpers\Controllers\TerminalController@runArtisan');
$router->get('helpers/scaffold', 'Encore\Admin\Helpers\Controllers\ScaffoldController@index');
$router->post('helpers/scaffold', 'Encore\Admin\Helpers\Controllers\ScaffoldController@store');
$router->get('helpers/routes', 'Encore\Admin\Helpers\Controllers\RouteController@index');
});
}
public static function import()
{
$lastOrder = Menu::max('order') ?: 0;
$root = [
'parent_id' => 0,
'order' => $lastOrder++,
'title' => 'Helpers',
'icon' => 'fa-gears',
'uri' => '',
];
$root = Menu::create($root);
$menus = [
[
'title' => 'Scaffold',
'icon' => 'fa-keyboard-o',
'uri' => 'helpers/scaffold',
],
[
'title' => 'Database terminal',
'icon' => 'fa-database',
'uri' => 'helpers/terminal/database',
],
[
'title' => 'Laravel artisan',
'icon' => 'fa-terminal',
'uri' => 'helpers/terminal/artisan',
],
[
'title' => 'Routes',
'icon' => 'fa-list-alt',
'uri' => 'helpers/routes',
],
];
foreach ($menus as $menu) {
$menu['parent_id'] = $root->id;
$menu['order'] = $lastOrder++;
Menu::create($menu);
}
parent::createPermission('Admin helpers', 'ext.helpers', 'helpers/*');
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Controllers/RouteController.php | src/Controllers/RouteController.php | <?php
namespace Encore\Admin\Helpers\Controllers;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Controller;
use Illuminate\Routing\Route;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class RouteController extends Controller
{
public function index()
{
return Admin::content(function (Content $content) {
$model = $this->getModel()->setRoutes($this->getRoutes());
$content->body(Admin::grid($model, function (Grid $grid) {
$colors = [
'GET' => 'green',
'HEAD' => 'gray',
'POST' => 'blue',
'PUT' => 'yellow',
'DELETE' => 'red',
'PATCH' => 'aqua',
'OPTIONS'=> 'light-blue',
];
$grid->method()->map(function ($method) use ($colors) {
return "<span class=\"label bg-{$colors[$method]}\">$method</span>";
})->implode(' ');
$grid->uri()->display(function ($uri) {
return preg_replace('/\{.+?\}/', '<code>$0</span>', $uri);
})->sortable();
$grid->name();
$grid->action()->display(function ($uri) {
return preg_replace('/@.+/', '<code>$0</code>', $uri);
});
$grid->middleware()->badge('yellow');
$grid->disablePagination();
$grid->disableRowSelector();
$grid->disableActions();
$grid->disableCreation();
$grid->disableExport();
$grid->filter(function ($filter) {
$filter->disableIdFilter();
$filter->equal('action');
$filter->equal('uri');
});
}));
});
}
protected function getModel()
{
return new class() extends Model {
protected $routes;
protected $where = [];
public function setRoutes($routes)
{
$this->routes = $routes;
return $this;
}
public function where($column, $condition)
{
$this->where[$column] = trim($condition);
return $this;
}
public function orderBy()
{
return $this;
}
public function get()
{
$this->routes = collect($this->routes)->filter(function ($route) {
foreach ($this->where as $column => $condition) {
if (!Str::contains($route[$column], $condition)) {
return false;
}
}
return true;
})->all();
$instance = $this->newModelInstance();
return $instance->newCollection(array_map(function ($item) use ($instance) {
return $instance->newFromBuilder($item);
}, $this->routes));
}
};
}
public function getRoutes()
{
$routes = app('router')->getRoutes();
$routes = collect($routes)->map(function ($route) {
return $this->getRouteInformation($route);
})->all();
if ($sort = request('_sort')) {
$routes = $this->sortRoutes($sort, $routes);
}
return array_filter($routes);
}
/**
* Get the route information for a given route.
*
* @param \Illuminate\Routing\Route $route
*
* @return array
*/
protected function getRouteInformation(Route $route)
{
return [
'host' => $route->domain(),
'method' => $route->methods(),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
'middleware' => $this->getRouteMiddleware($route),
];
}
/**
* Sort the routes by a given element.
*
* @param string $sort
* @param array $routes
*
* @return array
*/
protected function sortRoutes($sort, $routes)
{
return Arr::sort($routes, function ($route) use ($sort) {
return $route[$sort];
});
}
/**
* Get before filters.
*
* @param \Illuminate\Routing\Route $route
*
* @return string
*/
protected function getRouteMiddleware($route)
{
return collect($route->gatherMiddleware())->map(function ($middleware) {
return $middleware instanceof \Closure ? 'Closure' : $middleware;
});
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Controllers/ScaffoldController.php | src/Controllers/ScaffoldController.php | <?php
namespace Encore\Admin\Helpers\Controllers;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Helpers\Scaffold\ControllerCreator;
use Encore\Admin\Helpers\Scaffold\MigrationCreator;
use Encore\Admin\Helpers\Scaffold\ModelCreator;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\MessageBag;
class ScaffoldController extends Controller
{
public function index()
{
return Admin::content(function (Content $content) {
$content->header('Scaffold');
$dbTypes = [
'string', 'integer', 'text', 'float', 'double', 'decimal', 'boolean', 'date', 'time',
'dateTime', 'timestamp', 'char', 'mediumText', 'longText', 'tinyInteger', 'smallInteger',
'mediumInteger', 'bigInteger', 'unsignedTinyInteger', 'unsignedSmallInteger', 'unsignedMediumInteger',
'unsignedInteger', 'unsignedBigInteger', 'enum', 'json', 'jsonb', 'dateTimeTz', 'timeTz',
'timestampTz', 'nullableTimestamps', 'binary', 'ipAddress', 'macAddress',
];
$action = URL::current();
$content->row(view('laravel-admin-helpers::scaffold', compact('dbTypes', 'action')));
});
}
public function store(Request $request)
{
$paths = [];
$message = '';
try {
// 1. Create model.
if (in_array('model', $request->get('create'))) {
$modelCreator = new ModelCreator($request->get('table_name'), $request->get('model_name'));
$paths['model'] = $modelCreator->create(
$request->get('primary_key'),
$request->get('timestamps') == 'on',
$request->get('soft_deletes') == 'on'
);
}
// 2. Create controller.
if (in_array('controller', $request->get('create'))) {
$paths['controller'] = (new ControllerCreator($request->get('controller_name')))
->create($request->get('model_name'), $request->get('fields'));
}
// 3. Create migration.
if (in_array('migration', $request->get('create'))) {
$migrationName = 'create_'.$request->get('table_name').'_table';
$paths['migration'] = (new MigrationCreator(app('files')))->buildBluePrint(
$request->get('fields'),
$request->get('primary_key', 'id'),
$request->get('timestamps') == 'on',
$request->get('soft_deletes') == 'on'
)->create($migrationName, database_path('migrations'), $request->get('table_name'));
}
// 4. Run migrate.
if (in_array('migrate', $request->get('create'))) {
Artisan::call('migrate');
$message = Artisan::output();
}
} catch (\Exception $exception) {
// Delete generated files if exception thrown.
app('files')->delete($paths);
return $this->backWithException($exception);
}
return $this->backWithSuccess($paths, $message);
}
protected function backWithException(\Exception $exception)
{
$error = new MessageBag([
'title' => 'Error',
'message' => $exception->getMessage(),
]);
return back()->withInput()->with(compact('error'));
}
protected function backWithSuccess($paths, $message)
{
$messages = [];
foreach ($paths as $name => $path) {
$messages[] = ucfirst($name).": $path";
}
$messages[] = "<br />$message";
$success = new MessageBag([
'title' => 'Success',
'message' => implode('<br />', $messages),
]);
return back()->with(compact('success'));
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Controllers/TerminalController.php | src/Controllers/TerminalController.php | <?php
namespace Encore\Admin\Helpers\Controllers;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;
use MongoDB\Driver\Command;
use MongoDB\Driver\Manager;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\Output;
class TerminalController extends Controller
{
public function artisan()
{
return Admin::content(function (Content $content) {
$content->header('Artisan terminal');
$content->row(view('laravel-admin-helpers::artisan', ['commands' => $this->organizedCommands()]));
});
}
public function runArtisan()
{
$command = Request::get('c', 'list');
// If Exception raised.
if (1 === Artisan::handle(
new ArgvInput(explode(' ', 'artisan '.trim($command))),
$output = new StringOutput()
)) {
return $this->renderException(new Exception($output->getContent()));
}
return sprintf('<pre>%s</pre>', $output->getContent());
}
public function database()
{
return Admin::content(function (Content $content) {
$content->header('Database terminal');
$content->row(view('laravel-admin-helpers::database', ['connections' => $this->connections()]));
});
}
public function runDatabase()
{
$query = Request::get('q');
$connection = Request::get('c', config('database.default'));
return $this->dispatchQuery($connection, $query);
}
protected function getDumpedHtml($var)
{
ob_start();
dump($var);
$content = ob_get_contents();
ob_get_clean();
return substr($content, strpos($content, '<pre '));
}
protected function connections()
{
$dbs = $redis = [];
foreach (config('database.connections') as $name => $_) {
$dbs[] = [
'option' => $name,
'value' => "db:$name",
'selected' => $name == config('database.default'),
];
}
$connections = array_filter(config('database.redis'), function ($config) {
return is_array($config);
});
foreach ($connections as $name => $_) {
$redis[] = [
'value' => "redis:$name",
'option' => $name,
];
}
return compact('dbs', 'redis');
}
protected function table(array $headers, $rows, $style = 'default')
{
$output = new StringOutput();
$table = new Table($output);
if ($rows instanceof Arrayable) {
$rows = $rows->toArray();
}
$table->setHeaders($headers)->setRows($rows)->setStyle($style)->render();
return $output->getContent();
}
protected function dispatchQuery($connection, $query)
{
list($type, $connection) = explode(':', $connection);
if ($type == 'redis') {
return $this->execRedisCommand($connection, $query);
}
$config = config('database.connections.'.$connection);
if ($config['driver'] == 'mongodb') {
return $this->execMongodbQuery($config, $query);
}
/* @var \Illuminate\Database\Connection $connection */
$connection = DB::connection($connection);
$connection->enableQueryLog();
try {
$result = $connection->select(str_replace([';', "\G"], '', $query));
} catch (Exception $exception) {
return $this->renderException($exception);
}
$log = current($connection->getQueryLog());
if (empty($result)) {
return sprintf("<pre>Empty set (%s sec)</pre>\r\n", number_format($log['time'] / 1000, 2));
}
$result = json_decode(json_encode($result), true);
if (Str::contains($query, "\G")) {
return $this->getDumpedHtml($result);
}
return sprintf(
"<pre>%s \n%d %s in set (%s sec)</pre>\r\n",
$this->table(array_keys(current($result)), $result),
count($result),
count($result) == 1 ? 'row' : 'rows',
number_format($log['time'] / 1000, 2)
);
}
protected function execMongodbQuery($config, $query)
{
if (Str::contains($query, '.find(') && !Str::contains($query, '.toArray(')) {
$query .= '.toArray()';
}
$manager = new Manager("mongodb://{$config['host']}:{$config['port']}");
$command = new Command(['eval' => $query]);
try {
$cursor = $manager->executeCommand($config['database'], $command);
} catch (Exception $exception) {
return $this->renderException($exception);
}
$result = $cursor->toArray()[0];
$result = json_decode(json_encode($result), true);
if (isset($result['errmsg'])) {
return $this->renderException(new Exception($result['errmsg']));
}
return $this->getDumpedHtml($result['retval']);
}
protected function execRedisCommand($connection, $command)
{
$command = explode(' ', $command);
try {
$result = Redis::connection($connection)->executeRaw($command);
} catch (Exception $exception) {
return $this->renderException($exception);
}
if (is_string($result) && Str::startsWith($result, ['ERR ', 'WRONGTYPE '])) {
return $this->renderException(new Exception($result));
}
return $this->getDumpedHtml($result);
}
protected function organizedCommands()
{
$commands = array_keys(Artisan::all());
$groups = $others = [];
foreach ($commands as $command) {
$parts = explode(':', $command);
if (isset($parts[1])) {
$groups[$parts[0]][] = $command;
} else {
$others[] = $command;
}
}
foreach ($groups as $key => $group) {
if (count($group) === 1) {
$others[] = $group[0];
unset($groups[$key]);
}
}
ksort($groups);
sort($others);
return compact('groups', 'others');
}
protected function renderException(Exception $exception)
{
return sprintf(
"<div class='callout callout-warning'><i class='icon fa fa-warning'></i> %s</div>",
str_replace("\n", '<br />', $exception->getMessage())
);
}
}
class StringOutput extends Output
{
public $output = '';
public function clear()
{
$this->output = '';
}
protected function doWrite($message, $newline)
{
$this->output .= $message.($newline ? "\n" : '');
}
public function getContent()
{
return trim($this->output);
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Scaffold/MigrationCreator.php | src/Scaffold/MigrationCreator.php | <?php
namespace Encore\Admin\Helpers\Scaffold;
use Illuminate\Database\Migrations\MigrationCreator as BaseMigrationCreator;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
class MigrationCreator extends BaseMigrationCreator
{
/**
* @var string
*/
protected $bluePrint = '';
public function __construct(Filesystem $files, $customStubPath = null)
{
parent::__construct($files, $customStubPath);
}
/**
* Create a new model.
*
* @param string $name
* @param string $path
* @param null $table
* @param bool|true $create
*
* @return string
*/
public function create($name, $path, $table = null, $create = true)
{
$this->ensureMigrationDoesntAlreadyExist($name);
$path = $this->getPath($name, $path);
$stub = $this->files->get(__DIR__.'/stubs/create.stub');
$this->files->put($path, $this->populateStub($name, $stub, $table));
$this->firePostCreateHooks($table);
return $path;
}
/**
* Populate stub.
*
* @param string $name
* @param string $stub
* @param string $table
*
* @return mixed
*/
protected function populateStub($name, $stub, $table)
{
return str_replace(
['DummyClass', 'DummyTable', 'DummyStructure'],
[$this->getClassName($name), $table, $this->bluePrint],
$stub
);
}
/**
* Build the table blueprint.
*
* @param array $fields
* @param string $keyName
* @param bool|true $useTimestamps
* @param bool|false $softDeletes
*
* @throws \Exception
*
* @return $this
*/
public function buildBluePrint($fields = [], $keyName = 'id', $useTimestamps = true, $softDeletes = false)
{
$fields = array_filter($fields, function ($field) {
return isset($field['name']) && !empty($field['name']);
});
if (empty($fields)) {
throw new \Exception('Table fields can\'t be empty');
}
$rows[] = "\$table->increments('$keyName');\n";
foreach ($fields as $field) {
$column = "\$table->{$field['type']}('{$field['name']}')";
if ($field['key']) {
$column .= "->{$field['key']}()";
}
if (isset($field['default']) && $field['default']) {
$column .= "->default('{$field['default']}')";
}
if (isset($field['comment']) && $field['comment']) {
$column .= "->comment('{$field['comment']}')";
}
if (Arr::get($field, 'nullable') == 'on') {
$column .= '->nullable()';
}
$rows[] = $column.";\n";
}
if ($useTimestamps) {
$rows[] = "\$table->timestamps();\n";
}
if ($softDeletes) {
$rows[] = "\$table->softDeletes();\n";
}
$this->bluePrint = trim(implode(str_repeat(' ', 12), $rows), "\n");
return $this;
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Scaffold/ControllerCreator.php | src/Scaffold/ControllerCreator.php | <?php
namespace Encore\Admin\Helpers\Scaffold;
class ControllerCreator
{
/**
* Controller full name.
*
* @var string
*/
protected $name;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
protected $DummyGridField = '';
protected $DummyShowField = '';
protected $DummyFormField = '';
/**
* ControllerCreator constructor.
*
* @param string $name
* @param null $files
*/
public function __construct($name, $files = null)
{
$this->name = $name;
$this->files = $files ?: app('files');
}
/**
* Create a controller.
*
* @param string $model
*
* @throws \Exception
*
* @return string
*/
public function create($model, $fields)
{
$path = $this->getpath($this->name);
if ($this->files->exists($path)) {
throw new \Exception("Controller [$this->name] already exists!");
}
$this->generateGridField($fields);
$this->generateShowField($fields);
$this->generateFormField($fields);
$stub = $this->files->get($this->getStub());
$this->files->put($path, $this->replace($stub, $this->name, $model));
return $path;
}
/**
* @param string $stub
* @param string $name
* @param string $model
*
* @return string
*/
protected function replace($stub, $name, $model)
{
$stub = $this->replaceClass($stub, $name);
return str_replace(
['DummyModelNamespace', 'DummyModel', 'DummyGridField', 'DummyShowField', 'DummyFormField'],
[$model, class_basename($model), $this->DummyGridField, $this->DummyShowField, $this->DummyFormField],
$stub
);
}
/**
* Get controller namespace from giving name.
*
* @param string $name
*
* @return string
*/
protected function getNamespace($name)
{
return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
}
/**
* Replace the class name for the given stub.
*
* @param string $stub
* @param string $name
*
* @return string
*/
protected function replaceClass($stub, $name)
{
$class = str_replace($this->getNamespace($name).'\\', '', $name);
return str_replace(['DummyClass', 'DummyNamespace'], [$class, $this->getNamespace($name)], $stub);
}
/**
* Get file path from giving controller name.
*
* @param $name
*
* @return string
*/
public function getPath($name)
{
$segments = explode('\\', $name);
array_shift($segments);
return app_path(implode('/', $segments)).'.php';
}
/**
* Get stub file path.
*
* @return string
*/
public function getStub()
{
return __DIR__.'/stubs/controller.stub';
}
public function generateFormField($fields = [])
{
$fields = array_filter($fields, function ($field) {
return isset($field['name']) && !empty($field['name']);
});
if (empty($fields)) {
throw new \Exception('Table fields can\'t be empty');
}
foreach ($fields as $field) {
$rows[] = "\$form->text('{$field['name']}', '{$field['name']}');\n";
}
$this->DummyFormField = trim(implode(str_repeat(' ', 8), $rows), "\n");
return $this;
}
public function generateShowField($fields = [])
{
$fields = array_filter($fields, function ($field) {
return isset($field['name']) && !empty($field['name']);
});
if (empty($fields)) {
throw new \Exception('Table fields can\'t be empty');
}
foreach ($fields as $field) {
$rows[] = "\$show->{$field['name']}('{$field['name']}');\n";
}
$this->DummyShowField = trim(implode(str_repeat(' ', 8), $rows), "\n");
return $this;
}
public function generateGridField($fields = [])
{
$fields = array_filter($fields, function ($field) {
return isset($field['name']) && !empty($field['name']);
});
if (empty($fields)) {
throw new \Exception('Table fields can\'t be empty');
}
foreach ($fields as $field) {
$rows[] = "\$grid->{$field['name']}('{$field['name']}');\n";
}
$this->DummyGridField = trim(implode(str_repeat(' ', 8), $rows), "\n");
return $this;
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/src/Scaffold/ModelCreator.php | src/Scaffold/ModelCreator.php | <?php
namespace Encore\Admin\Helpers\Scaffold;
use Illuminate\Support\Str;
class ModelCreator
{
/**
* Table name.
*
* @var string
*/
protected $tableName;
/**
* Model name.
*
* @var string
*/
protected $name;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* ModelCreator constructor.
*
* @param string $tableName
* @param string $name
* @param null $files
*/
public function __construct($tableName, $name, $files = null)
{
$this->tableName = $tableName;
$this->name = $name;
$this->files = $files ?: app('files');
}
/**
* Create a new migration file.
*
* @param string $keyName
* @param bool|true $timestamps
* @param bool|false $softDeletes
*
* @throws \Exception
*
* @return string
*/
public function create($keyName = 'id', $timestamps = true, $softDeletes = false)
{
$path = $this->getpath($this->name);
if ($this->files->exists($path)) {
throw new \Exception("Model [$this->name] already exists!");
}
$stub = $this->files->get($this->getStub());
$stub = $this->replaceClass($stub, $this->name)
->replaceNamespace($stub, $this->name)
->replaceSoftDeletes($stub, $softDeletes)
->replaceTable($stub, $this->name)
->replaceTimestamp($stub, $timestamps)
->replacePrimaryKey($stub, $keyName)
->replaceSpace($stub);
$this->files->put($path, $stub);
return $path;
}
/**
* Get path for migration file.
*
* @param string $name
*
* @return string
*/
public function getPath($name)
{
$segments = explode('\\', $name);
array_shift($segments);
return app_path(implode('/', $segments)).'.php';
}
/**
* Get namespace of giving class full name.
*
* @param string $name
*
* @return string
*/
protected function getNamespace($name)
{
return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
}
/**
* Replace class dummy.
*
* @param string $stub
* @param string $name
*
* @return $this
*/
protected function replaceClass(&$stub, $name)
{
$class = str_replace($this->getNamespace($name).'\\', '', $name);
$stub = str_replace('DummyClass', $class, $stub);
return $this;
}
/**
* Replace namespace dummy.
*
* @param string $stub
* @param string $name
*
* @return $this
*/
protected function replaceNamespace(&$stub, $name)
{
$stub = str_replace(
'DummyNamespace', $this->getNamespace($name), $stub
);
return $this;
}
/**
* Replace soft-deletes dummy.
*
* @param string $stub
* @param bool $softDeletes
*
* @return $this
*/
protected function replaceSoftDeletes(&$stub, $softDeletes)
{
$import = $use = '';
if ($softDeletes) {
$import = "use Illuminate\\Database\\Eloquent\\SoftDeletes;\n";
$use = "use SoftDeletes;\n";
}
$stub = str_replace(['DummyImportSoftDeletesTrait', 'DummyUseSoftDeletesTrait'], [$import, $use], $stub);
return $this;
}
/**
* Replace primarykey dummy.
*
* @param string $stub
* @param string $keyName
*
* @return $this
*/
protected function replacePrimaryKey(&$stub, $keyName)
{
$modelKey = $keyName == 'id' ? '' : "protected \$primaryKey = '$keyName';\n";
$stub = str_replace('DummyModelKey', $modelKey, $stub);
return $this;
}
/**
* Replace Table name dummy.
*
* @param string $stub
* @param string $name
*
* @return $this
*/
protected function replaceTable(&$stub, $name)
{
$class = str_replace($this->getNamespace($name).'\\', '', $name);
$table = Str::plural(strtolower($class)) !== $this->tableName ? "protected \$table = '$this->tableName';\n" : '';
$stub = str_replace('DummyModelTable', $table, $stub);
return $this;
}
/**
* Replace timestamps dummy.
*
* @param string $stub
* @param bool $timestamps
*
* @return $this
*/
protected function replaceTimestamp(&$stub, $timestamps)
{
$useTimestamps = $timestamps ? '' : "public \$timestamps = false;\n";
$stub = str_replace('DummyTimestamp', $useTimestamps, $stub);
return $this;
}
/**
* Replace spaces.
*
* @param string $stub
*
* @return mixed
*/
public function replaceSpace($stub)
{
return str_replace(["\n\n\n", "\n \n"], ["\n\n", ''], $stub);
}
/**
* Get stub path of model.
*
* @return string
*/
public function getStub()
{
return __DIR__.'/stubs/model.stub';
}
}
| php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/resources/views/artisan.blade.php | resources/views/artisan.blade.php | <script>
$(function () {
var storageKey = function () {
var connection = $('#connections').val();
return 'la-'+connection+'-history'
};
$('#terminal-box').slimScroll({
height: $('#pjax-container').height() - 247 +'px'
});
function History () {
this.index = this.count() - 1;
}
History.prototype.store = function () {
var history = localStorage.getItem(storageKey());
if (!history) {
history = [];
} else {
history = JSON.parse(history);
}
return history;
};
History.prototype.push = function (record) {
var history = this.store();
history.push(record);
localStorage.setItem(storageKey(), JSON.stringify(history));
this.index = this.count() - 1;
};
History.prototype.count = function () {
return this.store().length;
};
History.prototype.up = function () {
if (this.index > 0) {
this.index--;
}
return this.store()[this.index];
};
History.prototype.down = function () {
if (this.index < this.count() - 1) {
this.index++;
}
return this.store()[this.index];
};
History.prototype.clear = function () {
localStorage.removeItem(storageKey());
};
var history = new History;
var send = function () {
var $input = $('#terminal-query');
$.ajax({
url:location.pathname,
method: 'post',
data: {
c: $input.val(),
_token: LA.token
},
success: function (response) {
history.push($input.val());
$('#terminal-box')
.append('<div class="item"><small class="label label-default"> > artisan '+$input.val()+'<\/small><\/div>')
.append('<div class="item">'+response+'<\/div>')
.slimScroll({ scrollTo: $("#terminal-box")[0].scrollHeight });
$input.val('');
}
});
};
$('#terminal-query').on('keyup', function (e) {
e.preventDefault();
if (e.keyCode == 13) {
send();
}
if (e.keyCode == 38) {
$(this).val(history.up());
}
if (e.keyCode == 40) {
$(this).val(history.down());
}
});
$('#terminal-clear').click(function () {
$('#terminal-box').text('');
//history.clear();
});
$('.loaded-command').click(function () {
$('#terminal-query').val($(this).html() + ' ');
$('#terminal-query').focus();
});
$('#terminal-send').click(function () {
send();
});
});
</script>
<!-- Chat box -->
<div class="box box-primary">
<div class="box-header with-border">
<i class="fa fa-terminal"></i>
</div>
<div class="box-body chat" id="terminal-box">
<!-- chat item -->
<!-- /.item -->
</div>
<!-- /.chat -->
<div class="box-footer with-border">
<div style="margin-bottom: 10px;">
@foreach($commands['groups'] as $group => $command)
<div class="btn-group dropup">
<button type="button" class="btn btn-default btn-flat">{{ $group }}</button>
<button type="button" class="btn btn-default btn-flat dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
@foreach($command as $item)
<li><a href="#" class="loaded-command">{{$item}}</a></li>
@endforeach
</ul>
</div>
@endforeach
<div class="btn-group dropup">
<button type="button" class="btn btn-twitter btn-flat">Other</button>
<button type="button" class="btn btn-twitter btn-flat dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
@foreach($commands['others'] as $item)
<li><a href="#" class="loaded-command">{{$item}}</a></li>
@endforeach
</ul>
</div>
<button type="button" class="btn btn-success" id="terminal-send"><i class="fa fa-paper-plane"></i> send</button>
<button type="button" class="btn btn-warning" id="terminal-clear"><i class="fa fa-refresh"></i> clear</button>
</div>
<div class="input-group">
<span class="input-group-addon" style="font-size: 18px; line-height: 1.3333333;">artisan</span>
<input class="form-control input-lg" id="terminal-query" placeholder="command" style="border-left: 0px;padding-left: 0px;">
</div>
</div>
</div>
<!-- /.box (chat box) --> | php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/resources/views/scaffold.blade.php | resources/views/scaffold.blade.php | <div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Scaffold</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<form method="post" action="{{$action}}" id="scaffold" pjax-container>
<div class="box-body">
<div class="form-horizontal">
<div class="form-group">
<label for="inputTableName" class="col-sm-1 control-label">Table name</label>
<div class="col-sm-4">
<input type="text" name="table_name" class="form-control" id="inputTableName" placeholder="table name" value="{{ old('table_name') }}">
</div>
<span class="help-block hide" id="table-name-help">
<i class="fa fa-info"></i> Table name can't be empty!
</span>
</div>
<div class="form-group">
<label for="inputModelName" class="col-sm-1 control-label">Model</label>
<div class="col-sm-4">
<input type="text" name="model_name" class="form-control" id="inputModelName" placeholder="model" value="{{ old('model_name', "App\\Models\\") }}">
</div>
</div>
<div class="form-group">
<label for="inputControllerName" class="col-sm-1 control-label">Controller</label>
<div class="col-sm-4">
<input type="text" name="controller_name" class="form-control" id="inputControllerName" placeholder="controller" value="{{ old('controller_name', "App\\Admin\\Controllers\\") }}">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<div class="checkbox">
<label>
<input type="checkbox" checked value="migration" name="create[]" /> Create migration
</label>
<label>
<input type="checkbox" checked value="model" name="create[]" /> Create model
</label>
<label>
<input type="checkbox" checked value="controller" name="create[]" /> Create controller
</label>
<label>
<input type="checkbox" checked value="migrate" name="create[]" /> Run migrate
</label>
</div>
</div>
</div>
</div>
<hr />
<h4>Fields</h4>
<table class="table table-hover" id="table-fields">
<tbody>
<tr>
<th style="width: 200px">Field name</th>
<th>Type</th>
<th>Nullable</th>
<th>Key</th>
<th>Default value</th>
<th>Comment</th>
<th>Action</th>
</tr>
@if(old('fields'))
@foreach(old('fields') as $index => $field)
<tr>
<td>
<input type="text" name="fields[{{$index}}][name]" class="form-control" placeholder="field name" value="{{$field['name']}}" />
</td>
<td>
<select style="width: 200px" name="fields[{{$index}}][type]">
@foreach($dbTypes as $type)
<option value="{{ $type }}" {{$field['type'] == $type ? 'selected' : '' }}>{{$type}}</option>
@endforeach
</select>
</td>
<td><input type="checkbox" name="fields[{{$index}}][nullable]" {{ \Illuminate\Support\Arr::get($field, 'nullable') == 'on' ? 'checked': '' }}/></td>
<td>
<select style="width: 150px" name="fields[{{$index}}][key]">
{{--<option value="primary">Primary</option>--}}
<option value="" {{$field['key'] == '' ? 'selected' : '' }}>NULL</option>
<option value="unique" {{$field['key'] == 'unique' ? 'selected' : '' }}>Unique</option>
<option value="index" {{$field['key'] == 'index' ? 'selected' : '' }}>Index</option>
</select>
</td>
<td><input type="text" class="form-control" placeholder="default value" name="fields[{{$index}}][default]" value="{{$field['default']}}"/></td>
<td><input type="text" class="form-control" placeholder="comment" name="fields[{{$index}}][comment]" value="{{$field['comment']}}" /></td>
<td><a class="btn btn-sm btn-danger table-field-remove"><i class="fa fa-trash"></i> remove</a></td>
</tr>
@endforeach
@else
<tr>
<td>
<input type="text" name="fields[0][name]" class="form-control" placeholder="field name" />
</td>
<td>
<select style="width: 200px" name="fields[0][type]">
@foreach($dbTypes as $type)
<option value="{{ $type }}">{{$type}}</option>
@endforeach
</select>
</td>
<td><input type="checkbox" name="fields[0][nullable]" /></td>
<td>
<select style="width: 150px" name="fields[0][key]">
{{--<option value="primary">Primary</option>--}}
<option value="" selected>NULL</option>
<option value="unique">Unique</option>
<option value="index">Index</option>
</select>
</td>
<td><input type="text" class="form-control" placeholder="default value" name="fields[0][default]"></td>
<td><input type="text" class="form-control" placeholder="comment" name="fields[0][comment]"></td>
<td><a class="btn btn-sm btn-danger table-field-remove"><i class="fa fa-trash"></i> remove</a></td>
</tr>
@endif
</tbody>
</table>
<hr style="margin-top: 0;"/>
<div class='form-inline margin' style="width: 100%">
<div class='form-group'>
<button type="button" class="btn btn-sm btn-success" id="add-table-field"><i class="fa fa-plus"></i> Add field</button>
</div>
<div class='form-group pull-right' style="margin-right: 20px; margin-top: 5px;">
<div class="checkbox">
<label>
<input type="checkbox" checked name="timestamps"> Created_at & Updated_at
</label>
<label>
<input type="checkbox" name="soft_deletes"> Soft deletes
</label>
</div>
</div>
<div class="form-group pull-right" style="margin-right: 20px;">
<label for="inputPrimaryKey">Primary key</label>
<input type="text" name="primary_key" class="form-control" id="inputPrimaryKey" placeholder="Primary key" value="id" style="width: 100px;">
</div>
</div>
{{--<hr />--}}
{{--<h4>Relations</h4>--}}
{{--<table class="table table-hover" id="model-relations">--}}
{{--<tbody>--}}
{{--<tr>--}}
{{--<th style="width: 200px">Relation name</th>--}}
{{--<th>Type</th>--}}
{{--<th>Related model</th>--}}
{{--<th>forignKey</th>--}}
{{--<th>OtherKey</th>--}}
{{--<th>With Pivot</th>--}}
{{--<th>Action</th>--}}
{{--</tr>--}}
{{--</tbody>--}}
{{--</table>--}}
{{--<hr style="margin-top: 0;"/>--}}
{{--<div class='form-inline margin' style="width: 100%">--}}
{{--<div class='form-group'>--}}
{{--<button type="button" class="btn btn-sm btn-success" id="add-model-relation"><i class="fa fa-plus"></i> Add relation</button>--}}
{{--</div>--}}
{{--</div>--}}
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">submit</button>
</div>
{{ csrf_field() }}
<!-- /.box-footer -->
</form>
</div>
</div>
<template id="table-field-tpl">
<tr>
<td>
<input type="text" name="fields[__index__][name]" class="form-control" placeholder="field name" />
</td>
<td>
<select style="width: 200px" name="fields[__index__][type]">
@foreach($dbTypes as $type)
<option value="{{ $type }}">{{$type}}</option>
@endforeach
</select>
</td>
<td><input type="checkbox" name="fields[__index__][nullable]" /></td>
<td>
<select style="width: 150px" name="fields[__index__][key]">
<option value="" selected>NULL</option>
<option value="unique">Unique</option>
<option value="index">Index</option>
</select>
</td>
<td><input type="text" class="form-control" placeholder="default value" name="fields[__index__][default]"></td>
<td><input type="text" class="form-control" placeholder="comment" name="fields[__index__][comment]"></td>
<td><a class="btn btn-sm btn-danger table-field-remove"><i class="fa fa-trash"></i> remove</a></td>
</tr>
</template>
<template id="model-relation-tpl">
<tr>
<td><input type="text" class="form-control" placeholder="relation name" value=""></td>
<td>
<select style="width: 150px">
<option value="HasOne" selected>HasOne</option>
<option value="BelongsTo">BelongsTo</option>
<option value="HasMany">HasMany</option>
<option value="BelongsToMany">BelongsToMany</option>
</select>
</td>
<td><input type="text" class="form-control" placeholder="related model"></td>
<td><input type="text" class="form-control" placeholder="default value"></td>
<td><input type="text" class="form-control" placeholder="default value"></td>
<td><input type="checkbox" /></td>
<td><a class="btn btn-sm btn-danger model-relation-remove"><i class="fa fa-trash"></i> remove</a></td>
</tr>
</template>
<script>
$(function () {
$('input[type=checkbox]').iCheck({checkboxClass:'icheckbox_minimal-blue'});
$('select').select2();
$('#add-table-field').click(function (event) {
$('#table-fields tbody').append($('#table-field-tpl').html().replace(/__index__/g, $('#table-fields tr').length - 1));
$('select').select2();
$('input[type=checkbox]').iCheck({checkboxClass:'icheckbox_minimal-blue'});
});
$('#table-fields').on('click', '.table-field-remove', function(event) {
$(event.target).closest('tr').remove();
});
$('#add-model-relation').click(function (event) {
$('#model-relations tbody').append($('#model-relation-tpl').html().replace(/__index__/g, $('#model-relations tr').length - 1));
$('select').select2();
$('input[type=checkbox]').iCheck({checkboxClass:'icheckbox_minimal-blue'});
relation_count++;
});
$('#model-relations').on('click', '.model-relation-remove', function(event) {
$(event.target).closest('tr').remove();
});
$('#scaffold').on('submit', function (event) {
//event.preventDefault();
if ($('#inputTableName').val() == '') {
$('#inputTableName').closest('.form-group').addClass('has-error');
$('#table-name-help').removeClass('hide');
return false;
}
return true;
});
});
</script> | php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
laravel-admin-extensions/helpers | https://github.com/laravel-admin-extensions/helpers/blob/b5ee6173794797d665b5baf7cc2713b523c2dd33/resources/views/database.blade.php | resources/views/database.blade.php | <script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if ('sf-dump-compact' == oldClass) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if ('sf-dump-expanded' == oldClass) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } a.lastChild.innerHTML = arrow; s.className = newClass; if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (a[s].className !== newClass) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; return function (root) { root = doc.getElementById(root); function a(e, f) { addEventListener(root, e, function (e) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a) { if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if ('sf-dump-compact' == r.className) { toggle(s, isCtrlKey(e)); } } if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } }); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), elt = root.getElementsByTagName('A'), len = elt.length, i = 0, t = []; while (i < len) t.push(elt[i++]); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); root = t; len = t.length; i = t = 0; while (i < len) { elt = root[i]; if ("SAMP" == elt.tagName) { elt.className = "sf-dump-expanded"; a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; if ('sf-dump' != elt.parentNode.className) { toggle(a); } } else if ("sf-dump-ref" == elt.className && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { t = a.nextSibling; elt.appendChild(a); t.parentNode.insertBefore(a, t); if (/^[@#]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } ++i; } }; })(document); </script><style> pre.sf-dump { display: block; white-space: pre; padding: 5px; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; }pre.sf-dump{ color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; word-break: normal}pre.sf-dump .sf-dump-num{font-weight:bold; color:#1299DA}pre.sf-dump .sf-dump-const{font-weight:bold}pre.sf-dump .sf-dump-str{font-weight:bold; color:#56DB3A}pre.sf-dump .sf-dump-note{color:#1299DA}pre.sf-dump .sf-dump-ref{color:#A0A0A0}pre.sf-dump .sf-dump-public{color:#FFFFFF}pre.sf-dump .sf-dump-protected{color:#FFFFFF}pre.sf-dump .sf-dump-private{color:#FFFFFF}pre.sf-dump .sf-dump-meta{color:#B729D9}pre.sf-dump .sf-dump-key{color:#56DB3A}pre.sf-dump .sf-dump-index{color:#1299DA}</style>
<script>
$(function () {
var storageKey = function () {
var connection = $('#connections').val();
return 'la-'+connection+'-history'
};
$('#terminal-box').slimScroll({
height: $('#pjax-container').height() - 205 +'px'
});
function History () {
this.index = this.count() - 1;
}
History.prototype.store = function () {
var history = localStorage.getItem(storageKey());
if (!history) {
history = [];
} else {
history = JSON.parse(history);
}
return history;
};
History.prototype.push = function (record) {
var history = this.store();
history.push(record);
localStorage.setItem(storageKey(), JSON.stringify(history));
this.index = this.count() - 1;
};
History.prototype.count = function () {
return this.store().length;
};
History.prototype.up = function () {
if (this.index > 0) {
this.index--;
}
return this.store()[this.index];
};
History.prototype.down = function () {
if (this.index < this.count() - 1) {
this.index++;
}
return this.store()[this.index];
};
History.prototype.clear = function () {
localStorage.removeItem(storageKey());
};
var history = new History;
var send = function () {
var $input = $('#terminal-query');
$.ajax({
url:location.pathname,
method: 'post',
data: {
c: $('#connections').val(),
q: $input.val(),
_token: LA.token
},
success: function (response) {
history.push($input.val());
$('#terminal-box')
.append('<div class="item"><small class="label label-default">'+$('#connections').val()+'> '+$input.val()+'<\/small><\/div>')
.append('<div class="item">'+response+'<\/div>')
.slimScroll({ scrollTo: $("#terminal-box")[0].scrollHeight });
$input.val('');
}
});
};
$('#terminal-query').on('keyup', function (e) {
if (e.keyCode == 13 && $(this).val()) {
send();
}
if (e.keyCode == 38) {
$(this).val(history.up());
}
if (e.keyCode == 40) {
$(this).val(history.down());
}
});
$('#terminal-send').click(function () {
send();
});
$('#terminal-clear').click(function () {
$('#terminal-box').text('');
//history.clear();
});
});
</script>
<!-- Chat box -->
<div class="box box-primary">
<div class="box-header with-border">
<i class="fa fa-terminal"></i>
<div class="box-tools pull-right" data-toggle="tooltip" title="Status">
<div class="input-group input-group-sm" style="width: 150px;">
<select name="connection" id="connections" class="form-control pull-right" style="margin-right: 10px;">
@if(!empty($connections['dbs']))
<optgroup label="dbs">
@foreach($connections['dbs'] as $db)
<option value="{{$db['value']}}" {{ $db['selected'] ? 'selected':'' }}>{{$db['option']}}</option>
@endforeach
</optgroup>
@endif
@if(!empty($connections['redis']))
<optgroup label="redis">
@foreach($connections['redis'] as $redis)
<option value="{{$redis['value']}}">{{$redis['option']}}</option>
@endforeach
</optgroup>
@endif
</select>
</div>
</div>
</div>
<div class="box-body chat" id="terminal-box">
<!-- chat item -->
<!-- /.item -->
</div>
<!-- /.chat -->
<div class="box-footer with-border">
<div class="input-group">
<input class="form-control input-lg" id="terminal-query" placeholder="Type query...">
<div class="input-group-btn">
<button type="button" class="btn btn-primary btn-lg" id="terminal-send"><i class="fa fa-paper-plane"></i></button>
</div>
<div class="input-group-btn">
<button type="button" class="btn btn-warning btn-lg" id="terminal-clear"><i class="fa fa-trash"></i></button>
</div>
</div>
</div>
</div>
<!-- /.box (chat box) --> | php | MIT | b5ee6173794797d665b5baf7cc2713b523c2dd33 | 2026-01-05T05:02:47.157553Z | false |
dejurin/php-google-translate-for-free | https://github.com/dejurin/php-google-translate-for-free/blob/cbef0daa72685003463024286e3c3e3e10c1a3b3/example.php | example.php | <?php
require_once 'GoogleTranslateForFree.php';
//Single
$source = 'en';
$target = 'ru';
$attempts = 5;
$text = 'Hello';
$tr = new GoogleTranslateForFree();
$result = $tr->translate($source, $target, $text, $attempts);
var_dump($result);
//Array
$source = 'en';
$target = 'ru';
$attempts = 5;
$arr = ['hello', 'world'];
$tr = new GoogleTranslateForFree();
$result = $tr->translate($source, $target, $arr, $attempts);
var_dump($result);
| php | MIT | cbef0daa72685003463024286e3c3e3e10c1a3b3 | 2026-01-05T05:03:07.683652Z | false |
dejurin/php-google-translate-for-free | https://github.com/dejurin/php-google-translate-for-free/blob/cbef0daa72685003463024286e3c3e3e10c1a3b3/GoogleTranslateForFree.php | GoogleTranslateForFree.php | <?php
/**
* GoogleTranslateForFree.php.
*
* Class for free use Google Translator. With attempts connecting on failure and array support.
*
* @category Translation
*
* @author Yuri Darwin
* @author Yuri Darwin <gkhelloworld@gmail.com>
* @copyright 2019 Yuri Darwin
* @license https://opensource.org/licenses/MIT
*
* @version 1.0.0
*/
/**
* Main class GoogleTranslateForFree.
*/
class GoogleTranslateForFree
{
/**
* @param string $source
* @param string $target
* @param string|array $text
* @param int $attempts
*
* @return string|array With the translation of the text in the target language
*/
public static function translate($source, $target, $text, $attempts = 5)
{
// Request translation
if (is_array($text)) {
// Array
$translation = self::requestTranslationArray($source, $target, $text, $attempts = 5);
} else {
// Single
$translation = self::requestTranslation($source, $target, $text, $attempts = 5);
}
return $translation;
}
/**
* @param string $source
* @param string $target
* @param array $text
* @param int $attempts
*
* @return array
*/
protected static function requestTranslationArray($source, $target, $text, $attempts)
{
$arr = [];
foreach ($text as $value) {
// timeout 0.5 sec
usleep(500000);
$arr[] = self::requestTranslation($source, $target, $value, $attempts = 5);
}
return $arr;
}
/**
* @param string $source
* @param string $target
* @param string $text
* @param int $attempts
*
* @return string
*/
protected static function requestTranslation($source, $target, $text, $attempts)
{
// Google translate URL
$url = 'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=uk-RU&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
$fields = [
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text),
];
if (strlen($fields['q']) >= 5000) {
throw new \Exception('Maximum number of characters exceeded: 5000');
}
// URL-ify the data for the POST
$fields_string = self::fieldsString($fields);
$content = self::curlRequest($url, $fields, $fields_string, 0, $attempts);
if (null === $content) {
//echo $text,' Error',PHP_EOL;
return '';
} else {
// Parse translation
return self::getSentencesFromJSON($content);
}
}
/**
* Dump of the JSON's response in an array.
*
* @param string $json
*
* @return string
*/
protected static function getSentencesFromJSON($json)
{
$arr = json_decode($json, true);
$sentences = '';
if (isset($arr['sentences'])) {
foreach ($arr['sentences'] as $s) {
$sentences .= isset($s['trans']) ? $s['trans'] : '';
}
}
return $sentences;
}
/**
* Curl Request attempts connecting on failure.
*
* @param string $url
* @param array $fields
* @param string $fields_string
* @param int $i
* @param int $attempts
*
* @return string
*/
protected static function curlRequest($url, $fields, $fields_string, $i, $attempts)
{
$i++;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (false === $result || 200 !== $httpcode) {
// echo $i,'/',$attempts,' Aborted, trying again... ',curl_error($ch),PHP_EOL;
if ($i >= $attempts) {
//echo 'Could not connect and get data.',PHP_EOL;
return;
//die('Could not connect and get data.'.PHP_EOL);
} else {
// timeout 1.5 sec
usleep(1500000);
return self::curlRequest($url, $fields, $fields_string, $i, $attempts);
}
} else {
return $result; //self::getBodyCurlResponse();
}
curl_close($ch);
}
/**
* Make string with post data fields.
*
* @param array $fields
*
* @return string
*/
protected static function fieldsString($fields)
{
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key.'='.$value.'&';
}
return rtrim($fields_string, '&');
}
}
| php | MIT | cbef0daa72685003463024286e3c3e3e10c1a3b3 | 2026-01-05T05:03:07.683652Z | false |
dejurin/php-google-translate-for-free | https://github.com/dejurin/php-google-translate-for-free/blob/cbef0daa72685003463024286e3c3e3e10c1a3b3/src/GoogleTranslateForFree.php | src/GoogleTranslateForFree.php | <?php
namespace Dejurin;
/**
* GoogleTranslateForFree.php.
*
* Class for free use Google Translator. With attempts connecting on failure and array support.
*
* @category Translation
*
* @author Yuri Darwin
* @author Yuri Darwin <gkhelloworld@gmail.com>
* @copyright 2019 Yuri Darwin
* @license https://opensource.org/licenses/MIT
*
* @version 1.0.0
*/
/**
* Main class GoogleTranslateForFree.
*/
class GoogleTranslateForFree
{
/**
* @param string $source
* @param string $target
* @param string|array $text
* @param int $attempts
*
* @return string|array With the translation of the text in the target language
*/
public static function translate($source, $target, $text, $attempts = 5)
{
// Request translation
if (is_array($text)) {
// Array
$translation = self::requestTranslationArray($source, $target, $text, $attempts = 5);
} else {
// Single
$translation = self::requestTranslation($source, $target, $text, $attempts = 5);
}
return $translation;
}
/**
* @param string $source
* @param string $target
* @param array $text
* @param int $attempts
*
* @return array
*/
protected static function requestTranslationArray($source, $target, $text, $attempts)
{
$arr = [];
foreach ($text as $value) {
// timeout 0.5 sec
usleep(500000);
$arr[] = self::requestTranslation($source, $target, $value, $attempts = 5);
}
return $arr;
}
/**
* @param string $source
* @param string $target
* @param string $text
* @param int $attempts
*
* @return string
*/
protected static function requestTranslation($source, $target, $text, $attempts)
{
// Google translate URL
$url = 'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=uk-RU&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
$fields = [
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text),
];
if (strlen($fields['q']) >= 5000) {
throw new \Exception('Maximum number of characters exceeded: 5000');
}
// URL-ify the data for the POST
$fields_string = self::fieldsString($fields);
$content = self::curlRequest($url, $fields, $fields_string, 0, $attempts);
if (null === $content) {
//echo $text,' Error',PHP_EOL;
return '';
} else {
// Parse translation
return self::getSentencesFromJSON($content);
}
}
/**
* Dump of the JSON's response in an array.
*
* @param string $json
*
* @return string
*/
protected static function getSentencesFromJSON($json)
{
$arr = json_decode($json, true);
$sentences = '';
if (isset($arr['sentences'])) {
foreach ($arr['sentences'] as $s) {
$sentences .= isset($s['trans']) ? $s['trans'] : '';
}
}
return $sentences;
}
/**
* Curl Request attempts connecting on failure.
*
* @param string $url
* @param array $fields
* @param string $fields_string
* @param int $i
* @param int $attempts
*
* @return string
*/
protected static function curlRequest($url, $fields, $fields_string, $i, $attempts)
{
$i++;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (false === $result || 200 !== $httpcode) {
// echo $i,'/',$attempts,' Aborted, trying again... ',curl_error($ch),PHP_EOL;
if ($i >= $attempts) {
//echo 'Could not connect and get data.',PHP_EOL;
return;
//die('Could not connect and get data.'.PHP_EOL);
} else {
// timeout 1.5 sec
usleep(1500000);
return self::curlRequest($url, $fields, $fields_string, $i, $attempts);
}
} else {
return $result; //self::getBodyCurlResponse();
}
curl_close($ch);
}
/**
* Make string with post data fields.
*
* @param array $fields
*
* @return string
*/
protected static function fieldsString($fields)
{
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key.'='.$value.'&';
}
return rtrim($fields_string, '&');
}
}
| php | MIT | cbef0daa72685003463024286e3c3e3e10c1a3b3 | 2026-01-05T05:03:07.683652Z | false |
mybuilder/phpunit-accelerator | https://github.com/mybuilder/phpunit-accelerator/blob/91dae70fbeb7b81b9502a9d3ea80d1184c1134b1/src/TestListener.php | src/TestListener.php | <?php
namespace MyBuilder\PhpunitAccelerator;
use PHPUnit\Framework\TestListener as BaseTestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
class TestListener implements BaseTestListener
{
use TestListenerDefaultImplementation;
private $ignorePolicy;
const PHPUNIT_PROPERTY_PREFIX = 'PHPUnit_';
public function __construct(IgnoreTestPolicy $ignorePolicy = null)
{
$this->ignorePolicy = ($ignorePolicy) ?: new NeverIgnoreTestPolicy();
}
public function endTest(\PHPUnit\Framework\Test $test, float $time): void
{
$testReflection = new \ReflectionObject($test);
if ($this->ignorePolicy->shouldIgnore($testReflection)) {
return;
}
$this->safelyFreeProperties($test, $testReflection->getProperties());
}
private function safelyFreeProperties(\PHPUnit\Framework\Test $test, array $properties)
{
foreach ($properties as $property) {
if ($this->isSafeToFreeProperty($property)) {
$this->freeProperty($test, $property);
}
}
}
private function isSafeToFreeProperty(\ReflectionProperty $property)
{
return !$property->isStatic() && $this->isNotPhpUnitProperty($property);
}
private function isNotPhpUnitProperty(\ReflectionProperty $property)
{
return 0 !== strpos($property->getDeclaringClass()->getName(), self::PHPUNIT_PROPERTY_PREFIX);
}
private function freeProperty(\PHPUnit\Framework\Test $test, \ReflectionProperty $property)
{
$property->setAccessible(true);
$property->setValue($test, null);
}
}
class NeverIgnoreTestPolicy implements IgnoreTestPolicy
{
public function shouldIgnore(\ReflectionObject $testReflection)
{
return false;
}
}
| php | MIT | 91dae70fbeb7b81b9502a9d3ea80d1184c1134b1 | 2026-01-05T05:03:17.385475Z | false |
mybuilder/phpunit-accelerator | https://github.com/mybuilder/phpunit-accelerator/blob/91dae70fbeb7b81b9502a9d3ea80d1184c1134b1/src/IgnoreTestPolicy.php | src/IgnoreTestPolicy.php | <?php
namespace MyBuilder\PhpunitAccelerator;
interface IgnoreTestPolicy
{
/**
* @return boolean
*/
public function shouldIgnore(\ReflectionObject $testReflection);
}
| php | MIT | 91dae70fbeb7b81b9502a9d3ea80d1184c1134b1 | 2026-01-05T05:03:17.385475Z | false |
mybuilder/phpunit-accelerator | https://github.com/mybuilder/phpunit-accelerator/blob/91dae70fbeb7b81b9502a9d3ea80d1184c1134b1/tests/TestListenerTest.php | tests/TestListenerTest.php | <?php
use MyBuilder\PhpunitAccelerator\TestListener;
use MyBuilder\PhpunitAccelerator\IgnoreTestPolicy;
class TestListenerTest extends \PHPUnit\Framework\TestCase
{
private $dummyTest;
protected function setUp()
{
$this->dummyTest = new DummyTest();
}
/**
* @test
*/
public function shouldFreeTestProperty()
{
$this->endTest(new TestListener());
$this->assertFreesTestProperty();
}
private function endTest(TestListener $listener)
{
$listener->endTest($this->dummyTest, 0);
}
private function assertFreesTestProperty()
{
$this->assertNull($this->dummyTest->property);
}
/**
* @test
*/
public function shouldNotFreePhpUnitProperty()
{
$this->endTest(new TestListener());
$this->assertDoesNotFreePHPUnitProperty();
}
private function assertDoesNotFreePHPUnitProperty()
{
$this->assertNotNull($this->dummyTest->phpUnitProperty);
}
/**
* @test
*/
public function shouldNotFreeTestPropertyWithIgnoreAlwaysPolicy()
{
$this->endTest(new TestListener(new AlwaysIgnoreTestPolicy()));
$this->assertDoesNotFreeTestProperty();
}
private function assertDoesNotFreeTestProperty()
{
$this->assertNotNull($this->dummyTest->property);
}
}
class PHPUnit_Fake extends \PHPUnit\Framework\TestCase
{
public $phpUnitProperty = 1;
}
class DummyTest extends \PHPUnit_Fake
{
public $property = 1;
}
class AlwaysIgnoreTestPolicy implements IgnoreTestPolicy
{
public function shouldIgnore(\ReflectionObject $testReflection)
{
return true;
}
}
| php | MIT | 91dae70fbeb7b81b9502a9d3ea80d1184c1134b1 | 2026-01-05T05:03:17.385475Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ConfigProvider.php | src/ConfigProvider.php | <?php
namespace Laminas\Db;
class ConfigProvider
{
/**
* Retrieve laminas-db default configuration.
*
* @return array
*/
public function __invoke()
{
return [
'dependencies' => $this->getDependencyConfig(),
];
}
/**
* Retrieve laminas-db default dependency configuration.
*
* @return array
*/
public function getDependencyConfig()
{
return [
'abstract_factories' => [
Adapter\AdapterAbstractServiceFactory::class,
],
'factories' => [
Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
],
'aliases' => [
Adapter\Adapter::class => Adapter\AdapterInterface::class,
// Legacy Zend Framework aliases
// phpcs:disable WebimpressCodingStandard.Formatting.StringClassReference.Found
'Zend\Db\Adapter\AdapterInterface' => Adapter\AdapterInterface::class,
'Zend\Db\Adapter\Adapter' => Adapter\Adapter::class,
// phpcs:enable WebimpressCodingStandard.Formatting.StringClassReference.Found
],
];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Module.php | src/Module.php | <?php
namespace Laminas\Db;
class Module
{
/**
* Retrieve default laminas-db configuration for laminas-mvc context.
*
* @return array
*/
public function getConfig()
{
$provider = new ConfigProvider();
return [
'service_manager' => $provider->getDependencyConfig(),
];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Metadata.php | src/Metadata/Metadata.php | <?php
namespace Laminas\Db\Metadata;
use Laminas\Db\Adapter\Adapter;
/**
* @deprecated Use Laminas\Db\Metadata\Source\Factory::createSourceFromAdapter($adapter)
*/
class Metadata implements MetadataInterface
{
/** @var MetadataInterface */
protected $source;
/**
* Constructor
*/
public function __construct(Adapter $adapter)
{
$this->source = Source\Factory::createSourceFromAdapter($adapter);
}
/**
* {@inheritdoc}
*/
public function getTables($schema = null, $includeViews = false)
{
return $this->source->getTables($schema, $includeViews);
}
/**
* {@inheritdoc}
*/
public function getViews($schema = null)
{
return $this->source->getViews($schema);
}
/**
* {@inheritdoc}
*/
public function getTriggers($schema = null)
{
return $this->source->getTriggers($schema);
}
/**
* {@inheritdoc}
*/
public function getConstraints($table, $schema = null)
{
return $this->source->getConstraints($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumns($table, $schema = null)
{
return $this->source->getColumns($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getConstraintKeys($constraint, $table, $schema = null)
{
return $this->source->getConstraintKeys($constraint, $table, $schema);
}
/**
* {@inheritdoc}
*/
public function getConstraint($constraintName, $table, $schema = null)
{
return $this->source->getConstraint($constraintName, $table, $schema);
}
/**
* {@inheritdoc}
*/
public function getSchemas()
{
return $this->source->getSchemas();
}
/**
* {@inheritdoc}
*/
public function getTableNames($schema = null, $includeViews = false)
{
return $this->source->getTableNames($schema, $includeViews);
}
/**
* {@inheritdoc}
*/
public function getTable($tableName, $schema = null)
{
return $this->source->getTable($tableName, $schema);
}
/**
* {@inheritdoc}
*/
public function getViewNames($schema = null)
{
return $this->source->getViewNames($schema);
}
/**
* {@inheritdoc}
*/
public function getView($viewName, $schema = null)
{
return $this->source->getView($viewName, $schema);
}
/**
* {@inheritdoc}
*/
public function getTriggerNames($schema = null)
{
return $this->source->getTriggerNames($schema);
}
/**
* {@inheritdoc}
*/
public function getTrigger($triggerName, $schema = null)
{
return $this->source->getTrigger($triggerName, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumnNames($table, $schema = null)
{
return $this->source->getColumnNames($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumn($columnName, $table, $schema = null)
{
return $this->source->getColumn($columnName, $table, $schema);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/MetadataInterface.php | src/Metadata/MetadataInterface.php | <?php
namespace Laminas\Db\Metadata;
interface MetadataInterface
{
/**
* Get schemas.
*
* @return string[]
*/
public function getSchemas();
/**
* Get table names.
*
* @param null|string $schema
* @param bool $includeViews
* @return string[]
*/
public function getTableNames($schema = null, $includeViews = false);
/**
* Get tables.
*
* @param null|string $schema
* @param bool $includeViews
* @return Object\TableObject[]
*/
public function getTables($schema = null, $includeViews = false);
/**
* Get table
*
* @param string $tableName
* @param null|string $schema
* @return Object\TableObject
*/
public function getTable($tableName, $schema = null);
/**
* Get view names
*
* @param null|string $schema
* @return string[]
*/
public function getViewNames($schema = null);
/**
* Get views
*
* @param null|string $schema
* @return Object\ViewObject[]
*/
public function getViews($schema = null);
/**
* Get view
*
* @param string $viewName
* @param null|string $schema
* @return Object\ViewObject
*/
public function getView($viewName, $schema = null);
/**
* Get column names
*
* @param string $table
* @param null|string $schema
* @return string[]
*/
public function getColumnNames($table, $schema = null);
/**
* Get columns
*
* @param string $table
* @param null|string $schema
* @return Object\ColumnObject[]
*/
public function getColumns($table, $schema = null);
/**
* Get column
*
* @param string $columnName
* @param string $table
* @param null|string $schema
* @return Object\ColumnObject
*/
public function getColumn($columnName, $table, $schema = null);
/**
* Get constraints
*
* @param string $table
* @param null|string $schema
* @return Object\ConstraintObject[]
*/
public function getConstraints($table, $schema = null);
/**
* Get constraint
*
* @param string $constraintName
* @param string $table
* @param null|string $schema
* @return Object\ConstraintObject
*/
public function getConstraint($constraintName, $table, $schema = null);
/**
* Get constraint keys
*
* @param string $constraint
* @param string $table
* @param null|string $schema
* @return Object\ConstraintKeyObject[]
*/
public function getConstraintKeys($constraint, $table, $schema = null);
/**
* Get trigger names
*
* @param null|string $schema
* @return string[]
*/
public function getTriggerNames($schema = null);
/**
* Get triggers
*
* @param null|string $schema
* @return Object\TriggerObject[]
*/
public function getTriggers($schema = null);
/**
* Get trigger
*
* @param string $triggerName
* @param null|string $schema
* @return Object\TriggerObject
*/
public function getTrigger($triggerName, $schema = null);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/ColumnObject.php | src/Metadata/Object/ColumnObject.php | <?php
namespace Laminas\Db\Metadata\Object;
use function array_key_exists;
class ColumnObject
{
/** @var string */
protected $name;
/** @var string */
protected $tableName;
/** @var string */
protected $schemaName;
/** @var int */
protected $ordinalPosition;
/** @var string */
protected $columnDefault;
/** @var bool */
protected $isNullable;
/** @var string */
protected $dataType;
/** @var int */
protected $characterMaximumLength;
/** @var int */
protected $characterOctetLength;
/** @var int */
protected $numericPrecision;
/** @var int */
protected $numericScale;
/** @var bool */
protected $numericUnsigned;
/** @var array */
protected $errata = [];
/**
* Constructor
*
* @param string $name
* @param string $tableName
* @param string $schemaName
*/
public function __construct($name, $tableName, $schemaName = null)
{
$this->setName($name);
$this->setTableName($tableName);
$this->setSchemaName($schemaName);
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get table name
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Set table name
*
* @param string $tableName
* @return $this Provides a fluent interface
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
return $this;
}
/**
* Set schema name
*
* @param string $schemaName
*/
public function setSchemaName($schemaName)
{
$this->schemaName = $schemaName;
}
/**
* Get schema name
*
* @return string
*/
public function getSchemaName()
{
return $this->schemaName;
}
/**
* @return int $ordinalPosition
*/
public function getOrdinalPosition()
{
return $this->ordinalPosition;
}
/**
* @param int $ordinalPosition to set
* @return $this Provides a fluent interface
*/
public function setOrdinalPosition($ordinalPosition)
{
$this->ordinalPosition = $ordinalPosition;
return $this;
}
/**
* @return null|string the $columnDefault
*/
public function getColumnDefault()
{
return $this->columnDefault;
}
/**
* @param mixed $columnDefault to set
* @return $this Provides a fluent interface
*/
public function setColumnDefault($columnDefault)
{
$this->columnDefault = $columnDefault;
return $this;
}
/**
* @return bool $isNullable
*/
public function getIsNullable()
{
return $this->isNullable;
}
/**
* @param bool $isNullable to set
* @return $this Provides a fluent interface
*/
public function setIsNullable($isNullable)
{
$this->isNullable = $isNullable;
return $this;
}
/**
* @return bool $isNullable
*/
public function isNullable()
{
return $this->isNullable;
}
/**
* @return null|string the $dataType
*/
public function getDataType()
{
return $this->dataType;
}
/**
* @param string $dataType the $dataType to set
* @return $this Provides a fluent interface
*/
public function setDataType($dataType)
{
$this->dataType = $dataType;
return $this;
}
/**
* @return int|null the $characterMaximumLength
*/
public function getCharacterMaximumLength()
{
return $this->characterMaximumLength;
}
/**
* @param int $characterMaximumLength the $characterMaximumLength to set
* @return $this Provides a fluent interface
*/
public function setCharacterMaximumLength($characterMaximumLength)
{
$this->characterMaximumLength = $characterMaximumLength;
return $this;
}
/**
* @return int|null the $characterOctetLength
*/
public function getCharacterOctetLength()
{
return $this->characterOctetLength;
}
/**
* @param int $characterOctetLength the $characterOctetLength to set
* @return $this Provides a fluent interface
*/
public function setCharacterOctetLength($characterOctetLength)
{
$this->characterOctetLength = $characterOctetLength;
return $this;
}
/**
* @return int the $numericPrecision
*/
public function getNumericPrecision()
{
return $this->numericPrecision;
}
/**
* @param int $numericPrecision the $numericPrevision to set
* @return $this Provides a fluent interface
*/
public function setNumericPrecision($numericPrecision)
{
$this->numericPrecision = $numericPrecision;
return $this;
}
/**
* @return int the $numericScale
*/
public function getNumericScale()
{
return $this->numericScale;
}
/**
* @param int $numericScale the $numericScale to set
* @return $this Provides a fluent interface
*/
public function setNumericScale($numericScale)
{
$this->numericScale = $numericScale;
return $this;
}
/**
* @return bool
*/
public function getNumericUnsigned()
{
return $this->numericUnsigned;
}
/**
* @param bool $numericUnsigned
* @return $this Provides a fluent interface
*/
public function setNumericUnsigned($numericUnsigned)
{
$this->numericUnsigned = $numericUnsigned;
return $this;
}
/**
* @return bool
*/
public function isNumericUnsigned()
{
return $this->numericUnsigned;
}
/**
* @return array the $errata
*/
public function getErratas()
{
return $this->errata;
}
/**
* @param array $erratas
* @return $this Provides a fluent interface
*/
public function setErratas(array $erratas)
{
foreach ($erratas as $name => $value) {
$this->setErrata($name, $value);
}
return $this;
}
/**
* @param string $errataName
* @return mixed
*/
public function getErrata($errataName)
{
if (array_key_exists($errataName, $this->errata)) {
return $this->errata[$errataName];
}
return null;
}
/**
* @param string $errataName
* @param mixed $errataValue
* @return $this Provides a fluent interface
*/
public function setErrata($errataName, $errataValue)
{
$this->errata[$errataName] = $errataValue;
return $this;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/TriggerObject.php | src/Metadata/Object/TriggerObject.php | <?php
namespace Laminas\Db\Metadata\Object;
use DateTime;
class TriggerObject
{
/** @var string */
protected $name;
/** @var string */
protected $eventManipulation;
/** @var string */
protected $eventObjectCatalog;
/** @var string */
protected $eventObjectSchema;
/** @var string */
protected $eventObjectTable;
/** @var string */
protected $actionOrder;
/** @var string */
protected $actionCondition;
/** @var string */
protected $actionStatement;
/** @var string */
protected $actionOrientation;
/** @var string */
protected $actionTiming;
/** @var string */
protected $actionReferenceOldTable;
/** @var string */
protected $actionReferenceNewTable;
/** @var string */
protected $actionReferenceOldRow;
/** @var string */
protected $actionReferenceNewRow;
/** @var DateTime */
protected $created;
/**
* Get Name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set Name.
*
* @param string $name
* @return $this Provides a fluent interface
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get Event Manipulation.
*
* @return string
*/
public function getEventManipulation()
{
return $this->eventManipulation;
}
/**
* Set Event Manipulation.
*
* @param string $eventManipulation
* @return $this Provides a fluent interface
*/
public function setEventManipulation($eventManipulation)
{
$this->eventManipulation = $eventManipulation;
return $this;
}
/**
* Get Event Object Catalog.
*
* @return string
*/
public function getEventObjectCatalog()
{
return $this->eventObjectCatalog;
}
/**
* Set Event Object Catalog.
*
* @param string $eventObjectCatalog
* @return $this Provides a fluent interface
*/
public function setEventObjectCatalog($eventObjectCatalog)
{
$this->eventObjectCatalog = $eventObjectCatalog;
return $this;
}
/**
* Get Event Object Schema.
*
* @return string
*/
public function getEventObjectSchema()
{
return $this->eventObjectSchema;
}
/**
* Set Event Object Schema.
*
* @param string $eventObjectSchema
* @return $this Provides a fluent interface
*/
public function setEventObjectSchema($eventObjectSchema)
{
$this->eventObjectSchema = $eventObjectSchema;
return $this;
}
/**
* Get Event Object Table.
*
* @return string
*/
public function getEventObjectTable()
{
return $this->eventObjectTable;
}
/**
* Set Event Object Table.
*
* @param string $eventObjectTable
* @return $this Provides a fluent interface
*/
public function setEventObjectTable($eventObjectTable)
{
$this->eventObjectTable = $eventObjectTable;
return $this;
}
/**
* Get Action Order.
*
* @return string
*/
public function getActionOrder()
{
return $this->actionOrder;
}
/**
* Set Action Order.
*
* @param string $actionOrder
* @return $this Provides a fluent interface
*/
public function setActionOrder($actionOrder)
{
$this->actionOrder = $actionOrder;
return $this;
}
/**
* Get Action Condition.
*
* @return string
*/
public function getActionCondition()
{
return $this->actionCondition;
}
/**
* Set Action Condition.
*
* @param string $actionCondition
* @return $this Provides a fluent interface
*/
public function setActionCondition($actionCondition)
{
$this->actionCondition = $actionCondition;
return $this;
}
/**
* Get Action Statement.
*
* @return string
*/
public function getActionStatement()
{
return $this->actionStatement;
}
/**
* Set Action Statement.
*
* @param string $actionStatement
* @return $this Provides a fluent interface
*/
public function setActionStatement($actionStatement)
{
$this->actionStatement = $actionStatement;
return $this;
}
/**
* Get Action Orientation.
*
* @return string
*/
public function getActionOrientation()
{
return $this->actionOrientation;
}
/**
* Set Action Orientation.
*
* @param string $actionOrientation
* @return $this Provides a fluent interface
*/
public function setActionOrientation($actionOrientation)
{
$this->actionOrientation = $actionOrientation;
return $this;
}
/**
* Get Action Timing.
*
* @return string
*/
public function getActionTiming()
{
return $this->actionTiming;
}
/**
* Set Action Timing.
*
* @param string $actionTiming
* @return $this Provides a fluent interface
*/
public function setActionTiming($actionTiming)
{
$this->actionTiming = $actionTiming;
return $this;
}
/**
* Get Action Reference Old Table.
*
* @return string
*/
public function getActionReferenceOldTable()
{
return $this->actionReferenceOldTable;
}
/**
* Set Action Reference Old Table.
*
* @param string $actionReferenceOldTable
* @return $this Provides a fluent interface
*/
public function setActionReferenceOldTable($actionReferenceOldTable)
{
$this->actionReferenceOldTable = $actionReferenceOldTable;
return $this;
}
/**
* Get Action Reference New Table.
*
* @return string
*/
public function getActionReferenceNewTable()
{
return $this->actionReferenceNewTable;
}
/**
* Set Action Reference New Table.
*
* @param string $actionReferenceNewTable
* @return $this Provides a fluent interface
*/
public function setActionReferenceNewTable($actionReferenceNewTable)
{
$this->actionReferenceNewTable = $actionReferenceNewTable;
return $this;
}
/**
* Get Action Reference Old Row.
*
* @return string
*/
public function getActionReferenceOldRow()
{
return $this->actionReferenceOldRow;
}
/**
* Set Action Reference Old Row.
*
* @param string $actionReferenceOldRow
* @return $this Provides a fluent interface
*/
public function setActionReferenceOldRow($actionReferenceOldRow)
{
$this->actionReferenceOldRow = $actionReferenceOldRow;
return $this;
}
/**
* Get Action Reference New Row.
*
* @return string
*/
public function getActionReferenceNewRow()
{
return $this->actionReferenceNewRow;
}
/**
* Set Action Reference New Row.
*
* @param string $actionReferenceNewRow
* @return $this Provides a fluent interface
*/
public function setActionReferenceNewRow($actionReferenceNewRow)
{
$this->actionReferenceNewRow = $actionReferenceNewRow;
return $this;
}
/**
* Get Created.
*
* @return DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set Created.
*
* @param DateTime $created
* @return $this Provides a fluent interface
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/TableObject.php | src/Metadata/Object/TableObject.php | <?php
namespace Laminas\Db\Metadata\Object;
class TableObject extends AbstractTableObject
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/ConstraintKeyObject.php | src/Metadata/Object/ConstraintKeyObject.php | <?php
namespace Laminas\Db\Metadata\Object;
class ConstraintKeyObject
{
public const FK_CASCADE = 'CASCADE';
public const FK_SET_NULL = 'SET NULL';
public const FK_NO_ACTION = 'NO ACTION';
public const FK_RESTRICT = 'RESTRICT';
public const FK_SET_DEFAULT = 'SET DEFAULT';
/** @var string */
protected $columnName;
/** @var int */
protected $ordinalPosition;
/** @var bool */
protected $positionInUniqueConstraint;
/** @var string */
protected $referencedTableSchema;
/** @var string */
protected $referencedTableName;
/** @var string */
protected $referencedColumnName;
/** @var string */
protected $foreignKeyUpdateRule;
/** @var string */
protected $foreignKeyDeleteRule;
/**
* Constructor
*
* @param string $column
*/
public function __construct($column)
{
$this->setColumnName($column);
}
/**
* Get column name
*
* @return string
*/
public function getColumnName()
{
return $this->columnName;
}
/**
* Set column name
*
* @param string $columnName
* @return $this Provides a fluent interface
*/
public function setColumnName($columnName)
{
$this->columnName = $columnName;
return $this;
}
/**
* Get ordinal position
*
* @return int
*/
public function getOrdinalPosition()
{
return $this->ordinalPosition;
}
/**
* Set ordinal position
*
* @param int $ordinalPosition
* @return $this Provides a fluent interface
*/
public function setOrdinalPosition($ordinalPosition)
{
$this->ordinalPosition = $ordinalPosition;
return $this;
}
/**
* Get position in unique constraint
*
* @return bool
*/
public function getPositionInUniqueConstraint()
{
return $this->positionInUniqueConstraint;
}
/**
* Set position in unique constraint
*
* @param bool $positionInUniqueConstraint
* @return $this Provides a fluent interface
*/
public function setPositionInUniqueConstraint($positionInUniqueConstraint)
{
$this->positionInUniqueConstraint = $positionInUniqueConstraint;
return $this;
}
/**
* Get referencred table schema
*
* @return string
*/
public function getReferencedTableSchema()
{
return $this->referencedTableSchema;
}
/**
* Set referenced table schema
*
* @param string $referencedTableSchema
* @return $this Provides a fluent interface
*/
public function setReferencedTableSchema($referencedTableSchema)
{
$this->referencedTableSchema = $referencedTableSchema;
return $this;
}
/**
* Get referenced table name
*
* @return string
*/
public function getReferencedTableName()
{
return $this->referencedTableName;
}
/**
* Set Referenced table name
*
* @param string $referencedTableName
* @return $this Provides a fluent interface
*/
public function setReferencedTableName($referencedTableName)
{
$this->referencedTableName = $referencedTableName;
return $this;
}
/**
* Get referenced column name
*
* @return string
*/
public function getReferencedColumnName()
{
return $this->referencedColumnName;
}
/**
* Set referenced column name
*
* @param string $referencedColumnName
* @return $this Provides a fluent interface
*/
public function setReferencedColumnName($referencedColumnName)
{
$this->referencedColumnName = $referencedColumnName;
return $this;
}
/**
* set foreign key update rule
*
* @param string $foreignKeyUpdateRule
*/
public function setForeignKeyUpdateRule($foreignKeyUpdateRule)
{
$this->foreignKeyUpdateRule = $foreignKeyUpdateRule;
}
/**
* Get foreign key update rule
*
* @return string
*/
public function getForeignKeyUpdateRule()
{
return $this->foreignKeyUpdateRule;
}
/**
* Set foreign key delete rule
*
* @param string $foreignKeyDeleteRule
*/
public function setForeignKeyDeleteRule($foreignKeyDeleteRule)
{
$this->foreignKeyDeleteRule = $foreignKeyDeleteRule;
}
/**
* get foreign key delete rule
*
* @return string
*/
public function getForeignKeyDeleteRule()
{
return $this->foreignKeyDeleteRule;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/ViewObject.php | src/Metadata/Object/ViewObject.php | <?php
namespace Laminas\Db\Metadata\Object;
class ViewObject extends AbstractTableObject
{
/** @var null|string */
protected $viewDefinition;
/** @var null|string */
protected $checkOption;
/** @var null|bool */
protected $isUpdatable;
/**
* @return string $viewDefinition
*/
public function getViewDefinition()
{
return $this->viewDefinition;
}
/**
* @param string $viewDefinition to set
* @return $this Provides a fluent interface
*/
public function setViewDefinition($viewDefinition)
{
$this->viewDefinition = $viewDefinition;
return $this;
}
/**
* @return string $checkOption
*/
public function getCheckOption()
{
return $this->checkOption;
}
/**
* @param string $checkOption to set
* @return $this Provides a fluent interface
*/
public function setCheckOption($checkOption)
{
$this->checkOption = $checkOption;
return $this;
}
/**
* @return bool $isUpdatable
*/
public function getIsUpdatable()
{
return $this->isUpdatable;
}
/**
* @param bool $isUpdatable to set
* @return $this Provides a fluent interface
*/
public function setIsUpdatable($isUpdatable)
{
$this->isUpdatable = $isUpdatable;
return $this;
}
/** @return bool */
public function isUpdatable()
{
return (bool) $this->isUpdatable;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/ConstraintObject.php | src/Metadata/Object/ConstraintObject.php | <?php
namespace Laminas\Db\Metadata\Object;
class ConstraintObject
{
/** @var string */
protected $name;
/** @var string */
protected $tableName;
/** @var string */
protected $schemaName;
/**
* One of "PRIMARY KEY", "UNIQUE", "FOREIGN KEY", or "CHECK"
*
* @var string
*/
protected $type;
/** @var string[] */
protected $columns = [];
/** @var string */
protected $referencedTableSchema;
/** @var string */
protected $referencedTableName;
/** @var string[] */
protected $referencedColumns;
/** @var string */
protected $matchOption;
/** @var string */
protected $updateRule;
/** @var string */
protected $deleteRule;
/** @var string */
protected $checkClause;
/**
* Constructor
*
* @param string $name
* @param string $tableName
* @param string $schemaName
*/
public function __construct($name, $tableName, $schemaName = null)
{
$this->setName($name);
$this->setTableName($tableName);
$this->setSchemaName($schemaName);
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set schema name
*
* @param string $schemaName
*/
public function setSchemaName($schemaName)
{
$this->schemaName = $schemaName;
}
/**
* Get schema name
*
* @return string
*/
public function getSchemaName()
{
return $this->schemaName;
}
/**
* Get table name
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Set table name
*
* @param string $tableName
* @return $this Provides a fluent interface
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
return $this;
}
/**
* Set type
*
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
/** @return bool */
public function hasColumns()
{
return ! empty($this->columns);
}
/**
* Get Columns.
*
* @return string[]
*/
public function getColumns()
{
return $this->columns;
}
/**
* Set Columns.
*
* @param string[] $columns
* @return $this Provides a fluent interface
*/
public function setColumns(array $columns)
{
$this->columns = $columns;
return $this;
}
/**
* Get Referenced Table Schema.
*
* @return string
*/
public function getReferencedTableSchema()
{
return $this->referencedTableSchema;
}
/**
* Set Referenced Table Schema.
*
* @param string $referencedTableSchema
* @return $this Provides a fluent interface
*/
public function setReferencedTableSchema($referencedTableSchema)
{
$this->referencedTableSchema = $referencedTableSchema;
return $this;
}
/**
* Get Referenced Table Name.
*
* @return string
*/
public function getReferencedTableName()
{
return $this->referencedTableName;
}
/**
* Set Referenced Table Name.
*
* @param string $referencedTableName
* @return $this Provides a fluent interface
*/
public function setReferencedTableName($referencedTableName)
{
$this->referencedTableName = $referencedTableName;
return $this;
}
/**
* Get Referenced Columns.
*
* @return string[]
*/
public function getReferencedColumns()
{
return $this->referencedColumns;
}
/**
* Set Referenced Columns.
*
* @param string[] $referencedColumns
* @return $this Provides a fluent interface
*/
public function setReferencedColumns(array $referencedColumns)
{
$this->referencedColumns = $referencedColumns;
return $this;
}
/**
* Get Match Option.
*
* @return string
*/
public function getMatchOption()
{
return $this->matchOption;
}
/**
* Set Match Option.
*
* @param string $matchOption
* @return $this Provides a fluent interface
*/
public function setMatchOption($matchOption)
{
$this->matchOption = $matchOption;
return $this;
}
/**
* Get Update Rule.
*
* @return string
*/
public function getUpdateRule()
{
return $this->updateRule;
}
/**
* Set Update Rule.
*
* @param string $updateRule
* @return $this Provides a fluent interface
*/
public function setUpdateRule($updateRule)
{
$this->updateRule = $updateRule;
return $this;
}
/**
* Get Delete Rule.
*
* @return string
*/
public function getDeleteRule()
{
return $this->deleteRule;
}
/**
* Set Delete Rule.
*
* @param string $deleteRule
* @return $this Provides a fluent interface
*/
public function setDeleteRule($deleteRule)
{
$this->deleteRule = $deleteRule;
return $this;
}
/**
* Get Check Clause.
*
* @return string
*/
public function getCheckClause()
{
return $this->checkClause;
}
/**
* Set Check Clause.
*
* @param string $checkClause
* @return $this Provides a fluent interface
*/
public function setCheckClause($checkClause)
{
$this->checkClause = $checkClause;
return $this;
}
/**
* Is primary key
*
* @return bool
*/
public function isPrimaryKey()
{
return 'PRIMARY KEY' === $this->type;
}
/**
* Is unique key
*
* @return bool
*/
public function isUnique()
{
return 'UNIQUE' === $this->type;
}
/**
* Is foreign key
*
* @return bool
*/
public function isForeignKey()
{
return 'FOREIGN KEY' === $this->type;
}
/**
* Is foreign key
*
* @return bool
*/
public function isCheck()
{
return 'CHECK' === $this->type;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Object/AbstractTableObject.php | src/Metadata/Object/AbstractTableObject.php | <?php
namespace Laminas\Db\Metadata\Object;
abstract class AbstractTableObject
{
/*
protected $catalogName = null;
protected $schemaName = null;
*/
/** @var string */
protected $name;
/** @var string */
protected $type;
/** @var array */
protected $columns;
/** @var array */
protected $constraints;
/**
* Constructor
*
* @param string $name
*/
public function __construct($name)
{
if ($name) {
$this->setName($name);
}
}
/**
* Set columns
*
* @param array $columns
*/
public function setColumns(array $columns)
{
$this->columns = $columns;
}
/**
* Get columns
*
* @return array
*/
public function getColumns()
{
return $this->columns;
}
/**
* Set constraints
*
* @param array $constraints
*/
public function setConstraints($constraints)
{
$this->constraints = $constraints;
}
/**
* Get constraints
*
* @return array
*/
public function getConstraints()
{
return $this->constraints;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/OracleMetadata.php | src/Metadata/Source/OracleMetadata.php | <?php
namespace Laminas\Db\Metadata\Source;
use Laminas\Db\Adapter\Adapter;
use function implode;
use function strtoupper;
/**
* Metadata source for Oracle
*/
class OracleMetadata extends AbstractSource
{
/** @var array */
protected $constraintTypeMap = [
'C' => 'CHECK',
'P' => 'PRIMARY KEY',
'R' => 'FOREIGN_KEY',
];
/**
* {@inheritdoc}
*
* @see \Laminas\Db\Metadata\Source\AbstractSource::loadColumnData()
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$isColumns = [
'COLUMN_ID',
'COLUMN_NAME',
'DATA_DEFAULT',
'NULLABLE',
'DATA_TYPE',
'DATA_LENGTH',
'DATA_PRECISION',
'DATA_SCALE',
];
$this->prepareDataHierarchy('columns', $schema, $table);
$parameters = [
':ownername' => $schema,
':tablename' => $table,
];
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM all_tab_columns'
. ' WHERE owner = :ownername AND table_name = :tablename';
$result = $this->adapter->query($sql)->execute($parameters);
$columns = [];
foreach ($result as $row) {
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['COLUMN_ID'],
'column_default' => $row['DATA_DEFAULT'],
'is_nullable' => 'Y' === $row['NULLABLE'],
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['DATA_LENGTH'],
'character_octet_length' => null,
'numeric_precision' => $row['DATA_PRECISION'],
'numeric_scale' => $row['DATA_SCALE'],
'numeric_unsigned' => false,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
return $this;
}
/**
* Constraint type
*
* @param string $type
* @return string
*/
protected function getConstraintType($type)
{
if (isset($this->constraintTypeMap[$type])) {
return $this->constraintTypeMap[$type];
}
return $type;
}
/**
* {@inheritdoc}
*
* @see \Laminas\Db\Metadata\Source\AbstractSource::loadConstraintData()
*/
protected function loadConstraintData($table, $schema)
{
// phpcs:disable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$sql = '
SELECT
ac.owner,
ac.constraint_name,
ac.constraint_type,
ac.search_condition check_clause,
ac.table_name,
ac.delete_rule,
cc1.column_name,
cc2.table_name as ref_table,
cc2.column_name as ref_column,
cc2.owner as ref_owner
FROM all_constraints ac
INNER JOIN all_cons_columns cc1
ON cc1.constraint_name = ac.constraint_name
LEFT JOIN all_cons_columns cc2
ON cc2.constraint_name = ac.r_constraint_name
AND cc2.position = cc1.position
WHERE
ac.owner = :ownername AND ac.table_name = :tablename
ORDER BY ac.constraint_name
';
$parameters = [
':ownername' => $schema,
':tablename' => $table,
];
$results = $this->adapter->query($sql)->execute($parameters);
$isFK = false;
$name = null;
$constraints = [];
foreach ($results as $row) {
if ($row['CONSTRAINT_NAME'] !== $name) {
$name = $row['CONSTRAINT_NAME'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $this->getConstraintType($row['CONSTRAINT_TYPE']),
'table_name' => $row['TABLE_NAME'],
];
if ('C' === $row['CONSTRAINT_TYPE']) {
$constraints[$name]['CHECK_CLAUSE'] = $row['CHECK_CLAUSE'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = 'R' === $row['CONSTRAINT_TYPE'];
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REF_OWNER'];
$constraints[$name]['referenced_table_name'] = $row['REF_TABLE'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = 'NONE';
$constraints[$name]['update_rule'] = null;
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REF_COLUMN'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
return $this;
// phpcs:enable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
}
/**
* {@inheritdoc}
*
* @see \Laminas\Db\Metadata\Source\AbstractSource::loadSchemaData()
*/
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$sql = 'SELECT USERNAME FROM ALL_USERS';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['USERNAME'];
}
$this->data['schemas'] = $schemas;
}
/**
* {@inheritdoc}
*
* @see \Laminas\Db\Metadata\Source\AbstractSource::loadTableNameData()
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return $this;
}
$this->prepareDataHierarchy('table_names', $schema);
$tables = [];
// Tables
$bind = [':OWNER' => strtoupper($schema)];
$result = $this->adapter->query('SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER=:OWNER')->execute($bind);
foreach ($result as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => 'BASE TABLE',
'view_definition' => null,
'check_option' => null,
'is_updatable' => false,
];
}
// Views
$result = $this->adapter->query('SELECT VIEW_NAME, TEXT FROM ALL_VIEWS WHERE OWNER=:OWNER', $bind);
foreach ($result as $row) {
$tables[$row['VIEW_NAME']] = [
'table_type' => 'VIEW',
'view_definition' => null,
'check_option' => 'NONE',
'is_updatable' => false,
];
}
$this->data['table_names'][$schema] = $tables;
return $this;
}
/**
* FIXME: load trigger data
*
* {@inheritdoc}
*
* @see \Laminas\Db\Metadata\Source\AbstractSource::loadTriggerData()
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/SqliteMetadata.php | src/Metadata/Source/SqliteMetadata.php | <?php
namespace Laminas\Db\Metadata\Source;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\ResultSet\ResultSetInterface;
use function array_merge;
use function implode;
use function is_array;
use function is_string;
use function preg_match;
use function strtoupper;
class SqliteMetadata extends AbstractSource
{
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$results = $this->fetchPragma('database_list');
foreach ($results as $row) {
$schemas[] = $row['name'];
}
$this->data['schemas'] = $schemas;
}
/**
* @param string $schema
* @return void
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
// FEATURE: Filename?
$p = $this->adapter->getPlatform();
$sql = 'SELECT "name", "type", "sql" FROM ' . $p->quoteIdentifierChain([$schema, 'sqlite_master'])
. ' WHERE "type" IN (\'table\',\'view\') AND "name" NOT LIKE \'sqlite_%\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
if ('table' === $row['type']) {
$table = [
'table_type' => 'BASE TABLE',
'view_definition' => null, // VIEW only
'check_option' => null, // VIEW only
'is_updatable' => null, // VIEW only
];
} else {
$table = [
'table_type' => 'VIEW',
'view_definition' => null,
'check_option' => 'NONE',
'is_updatable' => false,
];
// Parse out extra data
if (null !== ($data = $this->parseView($row['sql']))) {
$table = array_merge($table, $data);
}
}
$tables[$row['name']] = $table;
}
$this->data['table_names'][$schema] = $tables;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$this->prepareDataHierarchy('sqlite_columns', $schema, $table);
$results = $this->fetchPragma('table_info', $table, $schema);
$columns = [];
foreach ($results as $row) {
$columns[$row['name']] = [
// cid appears to be zero-based, ordinal position needs to be one-based
'ordinal_position' => $row['cid'] + 1,
'column_default' => $row['dflt_value'],
'is_nullable' => ! (bool) $row['notnull'],
'data_type' => $row['type'],
'character_maximum_length' => null,
'character_octet_length' => null,
'numeric_precision' => null,
'numeric_scale' => null,
'numeric_unsigned' => null,
'erratas' => [],
];
// TODO: populate character_ and numeric_values with correct info
}
$this->data['columns'][$schema][$table] = $columns;
$this->data['sqlite_columns'][$schema][$table] = $results;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$this->loadColumnData($table, $schema);
$primaryKey = [];
foreach ($this->data['sqlite_columns'][$schema][$table] as $col) {
if ((bool) $col['pk']) {
$primaryKey[] = $col['name'];
}
}
if (empty($primaryKey)) {
$primaryKey = null;
}
$constraints = [];
$indexes = $this->fetchPragma('index_list', $table, $schema);
foreach ($indexes as $index) {
if (! (bool) $index['unique']) {
continue;
}
$constraint = [
'constraint_name' => $index['name'],
'constraint_type' => 'UNIQUE',
'table_name' => $table,
'columns' => [],
];
$info = $this->fetchPragma('index_info', $index['name'], $schema);
foreach ($info as $column) {
$constraint['columns'][] = $column['name'];
}
if ($primaryKey === $constraint['columns']) {
$constraint['constraint_type'] = 'PRIMARY KEY';
$primaryKey = null;
}
$constraints[$constraint['constraint_name']] = $constraint;
}
if (null !== $primaryKey) {
$constraintName = '_laminas_' . $table . '_PRIMARY';
$constraints[$constraintName] = [
'constraint_name' => $constraintName,
'constraint_type' => 'PRIMARY KEY',
'table_name' => $table,
'columns' => $primaryKey,
];
}
$foreignKeys = $this->fetchPragma('foreign_key_list', $table, $schema);
$id = $name = null;
foreach ($foreignKeys as $fk) {
if ($id !== $fk['id']) {
$id = $fk['id'];
$name = '_laminas_' . $table . '_FOREIGN_KEY_' . ($id + 1);
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => 'FOREIGN KEY',
'table_name' => $table,
'columns' => [],
'referenced_table_schema' => $schema,
'referenced_table_name' => $fk['table'],
'referenced_columns' => [],
// TODO: Verify match, on_update, and on_delete values conform to SQL Standard
'match_option' => strtoupper($fk['match']),
'update_rule' => strtoupper($fk['on_update']),
'delete_rule' => strtoupper($fk['on_delete']),
];
}
$constraints[$name]['columns'][] = $fk['from'];
$constraints[$name]['referenced_columns'][] = $fk['to'];
}
$this->data['constraints'][$schema][$table] = $constraints;
}
/**
* @param string $schema
* @return null|array<string, string>
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$sql = 'SELECT "name", "tbl_name", "sql" FROM '
. $p->quoteIdentifierChain([$schema, 'sqlite_master'])
. ' WHERE "type" = \'trigger\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$triggers = [];
foreach ($results->toArray() as $row) {
$trigger = [
'trigger_name' => $row['name'],
'event_manipulation' => null, // in $row['sql']
'event_object_catalog' => null,
'event_object_schema' => $schema,
'event_object_table' => $row['tbl_name'],
'action_order' => 0,
'action_condition' => null, // in $row['sql']
'action_statement' => null, // in $row['sql']
'action_orientation' => 'ROW',
'action_timing' => null, // in $row['sql']
'action_reference_old_table' => null,
'action_reference_new_table' => null,
'action_reference_old_row' => 'OLD',
'action_reference_new_row' => 'NEW',
'created' => null,
];
// Parse out extra data
if (null !== ($data = $this->parseTrigger($row['sql']))) {
$trigger = array_merge($trigger, $data);
}
$triggers[$trigger['trigger_name']] = $trigger;
}
$this->data['triggers'][$schema] = $triggers;
}
/**
* @param string $name
* @param null|scalar $value
* @param string $schema
* @return array
*/
protected function fetchPragma($name, $value = null, $schema = null)
{
$p = $this->adapter->getPlatform();
$sql = 'PRAGMA ';
if (null !== $schema) {
$sql .= $p->quoteIdentifier($schema) . '.';
}
$sql .= $name;
if (null !== $value) {
$sql .= '(' . $p->quoteTrustedValue($value) . ')';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
if ($results instanceof ResultSetInterface) {
return $results->toArray();
}
return [];
}
/**
* @param string $sql
* @return null|array<string, mixed>
*/
protected function parseView($sql)
{
static $re = null;
if (null === $re) {
$identifierChain = $this->getIdentifierChainRegularExpression();
$re = $this->buildRegularExpression([
'CREATE',
['TEMP|TEMPORARY'],
'VIEW',
['IF', 'NOT', 'EXISTS'],
$identifierChain,
'AS',
'(?<view_definition>.+)',
[';'],
]);
}
if (! preg_match($re, $sql, $matches)) {
return null;
}
return [
'view_definition' => $matches['view_definition'],
];
}
/**
* @param string $sql
* @return null|array<string, mixed>
*/
protected function parseTrigger($sql)
{
static $re = null;
if (null === $re) {
$identifier = $this->getIdentifierRegularExpression();
$identifierList = $this->getIdentifierListRegularExpression();
$identifierChain = $this->getIdentifierChainRegularExpression();
$re = $this->buildRegularExpression([
'CREATE',
['TEMP|TEMPORARY'],
'TRIGGER',
['IF', 'NOT', 'EXISTS'],
$identifierChain,
['(?<action_timing>BEFORE|AFTER|INSTEAD\\s+OF)'],
'(?<event_manipulation>DELETE|INSERT|UPDATE)',
['OF', '(?<column_usage>' . $identifierList . ')'],
'ON',
'(?<event_object_table>' . $identifier . ')',
['FOR', 'EACH', 'ROW'],
['WHEN', '(?<action_condition>.+)'],
'(?<action_statement>BEGIN',
'.+',
'END)',
[';'],
]);
}
if (! preg_match($re, $sql, $matches)) {
return null;
}
$data = [];
foreach ($matches as $key => $value) {
if (is_string($key)) {
$data[$key] = $value;
}
}
// Normalize data and populate defaults, if necessary
$data['event_manipulation'] = strtoupper($data['event_manipulation']);
if (empty($data['action_condition'])) {
$data['action_condition'] = null;
}
if (! empty($data['action_timing'])) {
$data['action_timing'] = strtoupper($data['action_timing']);
if ('I' === $data['action_timing'][0]) {
// normalize the white-space between the two words
$data['action_timing'] = 'INSTEAD OF';
}
} else {
$data['action_timing'] = 'AFTER';
}
unset($data['column_usage']);
return $data;
}
/** @return string */
protected function buildRegularExpression(array $re)
{
foreach ($re as &$value) {
if (is_array($value)) {
$value = '(?:' . implode('\\s*+', $value) . '\\s*+)?';
} else {
$value .= '\\s*+';
}
}
unset($value);
$re = '/^' . implode('\\s*+', $re) . '$/';
return $re;
}
/** @return string */
protected function getIdentifierRegularExpression()
{
static $re = null;
if (null === $re) {
$re = '(?:' . implode('|', [
'"(?:[^"\\\\]++|\\\\.)*+"',
'`(?:[^`]++|``)*+`',
'\\[[^\\]]+\\]',
'[^\\s\\.]+',
]) . ')';
}
return $re;
}
/** @return string */
protected function getIdentifierChainRegularExpression()
{
static $re = null;
if (null === $re) {
$identifier = $this->getIdentifierRegularExpression();
$re = $identifier . '(?:\\s*\\.\\s*' . $identifier . ')*+';
}
return $re;
}
/** @return string */
protected function getIdentifierListRegularExpression()
{
static $re = null;
if (null === $re) {
$identifier = $this->getIdentifierRegularExpression();
$re = $identifier . '(?:\\s*,\\s*' . $identifier . ')*+';
}
return $re;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/MysqlMetadata.php | src/Metadata/Source/MysqlMetadata.php | <?php
namespace Laminas\Db\Metadata\Source;
use DateTime;
use Laminas\Db\Adapter\Adapter;
use function array_change_key_case;
use function array_walk;
use function implode;
use function preg_match;
use function preg_match_all;
use function str_replace;
use function strpos;
use const CASE_LOWER;
use const PREG_PATTERN_ORDER;
class MysqlMetadata extends AbstractSource
{
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'SCHEMATA'])
. ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' != \'INFORMATION_SCHEMA\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['SCHEMA_NAME'];
}
$this->data['schemas'] = $schemas;
}
/**
* @param string $schema
* @return void
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['T', 'TABLE_TYPE'],
['V', 'VIEW_DEFINITION'],
['V', 'CHECK_OPTION'],
['V', 'IS_UPDATABLE'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'VIEWS']) . ' V'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => $row['TABLE_TYPE'],
'view_definition' => $row['VIEW_DEFINITION'],
'check_option' => $row['CHECK_OPTION'],
'is_updatable' => 'YES' === $row['IS_UPDATABLE'],
];
}
$this->data['table_names'][$schema] = $tables;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$p = $this->adapter->getPlatform();
$isColumns = [
['C', 'ORDINAL_POSITION'],
['C', 'COLUMN_DEFAULT'],
['C', 'IS_NULLABLE'],
['C', 'DATA_TYPE'],
['C', 'CHARACTER_MAXIMUM_LENGTH'],
['C', 'CHARACTER_OCTET_LENGTH'],
['C', 'NUMERIC_PRECISION'],
['C', 'NUMERIC_SCALE'],
['C', 'COLUMN_NAME'],
['C', 'COLUMN_TYPE'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'COLUMNS']) . 'C'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')'
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table);
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$erratas = [];
$matches = [];
if (preg_match('/^(?:enum|set)\((.+)\)$/i', $row['COLUMN_TYPE'], $matches)) {
$permittedValues = $matches[1];
if (
preg_match_all(
"/\\s*'((?:[^']++|'')*+)'\\s*(?:,|\$)/",
$permittedValues,
$matches,
PREG_PATTERN_ORDER
)
) {
$permittedValues = str_replace("''", "'", $matches[1]);
} else {
$permittedValues = [$permittedValues];
}
$erratas['permitted_values'] = $permittedValues;
}
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['ORDINAL_POSITION'],
'column_default' => $row['COLUMN_DEFAULT'],
'is_nullable' => 'YES' === $row['IS_NULLABLE'],
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'],
'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'],
'numeric_precision' => $row['NUMERIC_PRECISION'],
'numeric_scale' => $row['NUMERIC_SCALE'],
'numeric_unsigned' => false !== strpos($row['COLUMN_TYPE'], 'unsigned'),
'erratas' => $erratas,
];
}
$this->data['columns'][$schema][$table] = $columns;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadConstraintData($table, $schema)
{
// phpcs:disable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['T', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
['KCU', 'COLUMN_NAME'],
['RC', 'MATCH_OPTION'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['KCU', 'REFERENCED_TABLE_SCHEMA'],
['KCU', 'REFERENCED_TABLE_NAME'],
['KCU', 'REFERENCED_COLUMN_NAME'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . ' TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . ' RC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_TYPE'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " ELSE 4 END"
. ', ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ', ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$realName = null;
$constraints = [];
foreach ($results->toArray() as $row) {
if ($row['CONSTRAINT_NAME'] !== $realName) {
$realName = $row['CONSTRAINT_NAME'];
$isFK = 'FOREIGN KEY' === $row['CONSTRAINT_TYPE'];
if ($isFK) {
$name = $realName;
} else {
$name = '_laminas_' . $row['TABLE_NAME'] . '_' . $realName;
}
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['CONSTRAINT_TYPE'],
'table_name' => $row['TABLE_NAME'],
'columns' => [],
];
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA'];
$constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['MATCH_OPTION'];
$constraints[$name]['update_rule'] = $row['UPDATE_RULE'];
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
// phpcs:enable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
}
/**
* @param string $schema
* @return void
*/
protected function loadConstraintDataNames($schema)
{
if (isset($this->data['constraint_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['TC', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . 'TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_names'][$schema] = $data;
}
/**
* @param string $schema
* @return void
*/
protected function loadConstraintDataKeys($schema)
{
if (isset($this->data['constraint_keys'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_keys', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['KCU', 'CONSTRAINT_NAME'],
['KCU', 'COLUMN_NAME'],
['KCU', 'ORDINAL_POSITION'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . 'KCU'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_keys'][$schema] = $data;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadConstraintReferences($table, $schema)
{
parent::loadConstraintReferences($table, $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['RC', 'TABLE_NAME'],
['RC', 'CONSTRAINT_NAME'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['KCU', 'REFERENCED_TABLE_SCHEMA'],
['KCU', 'REFERENCED_TABLE_NAME'],
['KCU', 'REFERENCED_COLUMN_NAME'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. 'FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . 'RC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'TABLE_NAME'])
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . 'KCU'
. ' ON ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. 'WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_references'][$schema] = $data;
}
/**
* @param string $schema
* @return void
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
// 'TRIGGER_CATALOG',
// 'TRIGGER_SCHEMA',
'TRIGGER_NAME',
'EVENT_MANIPULATION',
'EVENT_OBJECT_CATALOG',
'EVENT_OBJECT_SCHEMA',
'EVENT_OBJECT_TABLE',
'ACTION_ORDER',
'ACTION_CONDITION',
'ACTION_STATEMENT',
'ACTION_ORIENTATION',
'ACTION_TIMING',
'ACTION_REFERENCE_OLD_TABLE',
'ACTION_REFERENCE_NEW_TABLE',
'ACTION_REFERENCE_OLD_ROW',
'ACTION_REFERENCE_NEW_ROW',
'CREATED',
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifier($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TRIGGERS'])
. ' WHERE ';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
if (null !== $row['created']) {
$row['created'] = new DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/PostgresqlMetadata.php | src/Metadata/Source/PostgresqlMetadata.php | <?php
namespace Laminas\Db\Metadata\Source;
use DateTime;
use Laminas\Db\Adapter\Adapter;
use function array_change_key_case;
use function array_walk;
use function implode;
use function is_array;
use function is_string;
use function key;
use const CASE_LOWER;
class PostgresqlMetadata extends AbstractSource
{
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('schema_name')
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'schemata'])
. ' WHERE ' . $p->quoteIdentifier('schema_name')
. ' != \'information_schema\''
. ' AND ' . $p->quoteIdentifier('schema_name') . " NOT LIKE 'pg_%'";
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['schema_name'];
}
$this->data['schemas'] = $schemas;
}
/**
* @param string $schema
* @return void
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['t', 'table_name'],
['t', 'table_type'],
['v', 'view_definition'],
['v', 'check_option'],
['v', 'is_updatable'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'tables']) . ' t'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'views']) . ' v'
. ' ON ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['v', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['v', 'table_name'])
. ' WHERE ' . $p->quoteIdentifierChain(['t', 'table_type'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' != \'information_schema\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['table_name']] = [
'table_type' => $row['table_type'],
'view_definition' => $row['view_definition'],
'check_option' => $row['check_option'],
'is_updatable' => 'YES' === $row['is_updatable'],
];
}
$this->data['table_names'][$schema] = $tables;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$platform = $this->adapter->getPlatform();
$isColumns = [
'table_name',
'column_name',
'ordinal_position',
'column_default',
'is_nullable',
'data_type',
'character_maximum_length',
'character_octet_length',
'numeric_precision',
'numeric_scale',
];
array_walk($isColumns, function (&$c) use ($platform) {
$c = $platform->quoteIdentifier($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $platform->quoteIdentifier('information_schema')
. $platform->getIdentifierSeparator() . $platform->quoteIdentifier('columns')
. ' WHERE ' . $platform->quoteIdentifier('table_schema')
. ' != \'information\''
. ' AND ' . $platform->quoteIdentifier('table_name')
. ' = ' . $platform->quoteTrustedValue($table);
if ($schema !== '__DEFAULT_SCHEMA__') {
$sql .= ' AND ' . $platform->quoteIdentifier('table_schema')
. ' = ' . $platform->quoteTrustedValue($schema);
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$columns[$row['column_name']] = [
'ordinal_position' => $row['ordinal_position'],
'column_default' => $row['column_default'],
'is_nullable' => 'YES' === $row['is_nullable'],
'data_type' => $row['data_type'],
'character_maximum_length' => $row['character_maximum_length'],
'character_octet_length' => $row['character_octet_length'],
'numeric_precision' => $row['numeric_precision'],
'numeric_scale' => $row['numeric_scale'],
'numeric_unsigned' => null,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadConstraintData($table, $schema)
{
// phpcs:disable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['t', 'table_name'],
['tc', 'constraint_name'],
['tc', 'constraint_type'],
['kcu', 'column_name'],
['cc', 'check_clause'],
['rc', 'match_option'],
['rc', 'update_rule'],
['rc', 'delete_rule'],
['referenced_table_schema' => 'kcu2', 'table_schema'],
['referenced_table_name' => 'kcu2', 'table_name'],
['referenced_column_name' => 'kcu2', 'column_name'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'tables']) . ' t'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['information_schema', 'table_constraints']) . ' tc'
. ' ON ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['tc', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['tc', 'table_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'key_column_usage']) . ' kcu'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'table_name'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'check_constraints']) . ' cc'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['cc', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['cc', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'referential_constraints']) . ' rc'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['rc', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['rc', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'key_column_usage']) . ' kcu2'
. ' ON ' . $p->quoteIdentifierChain(['rc', 'unique_constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['rc', 'unique_constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'constraint_name'])
. ' AND ' . $p->quoteIdentifierChain(['kcu', 'position_in_unique_constraint'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'ordinal_position'])
. ' WHERE ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_type'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' != \'information_schema\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['tc', 'constraint_type'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " WHEN 'CHECK' THEN 4"
. " ELSE 5 END"
. ', ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ', ' . $p->quoteIdentifierChain(['kcu', 'ordinal_position']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$name = null;
$constraints = [];
foreach ($results->toArray() as $row) {
if ($row['constraint_name'] !== $name) {
$name = $row['constraint_name'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['constraint_type'],
'table_name' => $row['table_name'],
];
if ('CHECK' === $row['constraint_type']) {
$constraints[$name]['check_clause'] = $row['check_clause'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = 'FOREIGN KEY' === $row['constraint_type'];
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['referenced_table_schema'];
$constraints[$name]['referenced_table_name'] = $row['referenced_table_name'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['match_option'];
$constraints[$name]['update_rule'] = $row['update_rule'];
$constraints[$name]['delete_rule'] = $row['delete_rule'];
}
}
$constraints[$name]['columns'][] = $row['column_name'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['referenced_column_name'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
// phpcs:enable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
}
/**
* @param string $schema
* @return void
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
'trigger_name',
'event_manipulation',
'event_object_catalog',
'event_object_schema',
'event_object_table',
'action_order',
'action_condition',
'action_statement',
'action_orientation',
['action_timing' => 'condition_timing'],
['action_reference_old_table' => 'condition_reference_old_table'],
['action_reference_new_table' => 'condition_reference_new_table'],
'created',
];
array_walk($isColumns, function (&$c) use ($p) {
if (is_array($c)) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
} else {
$c = $p->quoteIdentifier($c);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'triggers'])
. ' WHERE ';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('trigger_schema')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('trigger_schema')
. ' != \'information_schema\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
$row['action_reference_old_row'] = 'OLD';
$row['action_reference_new_row'] = 'NEW';
if (null !== $row['created']) {
$row['created'] = new DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/AbstractSource.php | src/Metadata/Source/AbstractSource.php | <?php
namespace Laminas\Db\Metadata\Source;
use Exception;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Metadata\MetadataInterface;
use Laminas\Db\Metadata\Object\ColumnObject;
use Laminas\Db\Metadata\Object\ConstraintKeyObject;
use Laminas\Db\Metadata\Object\ConstraintObject;
use Laminas\Db\Metadata\Object\TableObject;
use Laminas\Db\Metadata\Object\TriggerObject;
use Laminas\Db\Metadata\Object\ViewObject;
use function array_keys;
use function func_get_args;
use function str_replace;
abstract class AbstractSource implements MetadataInterface
{
public const DEFAULT_SCHEMA = '__DEFAULT_SCHEMA__';
/** @var Adapter */
protected $adapter;
/** @var string */
protected $defaultSchema;
/** @var array */
protected $data = [];
/**
* Constructor
*/
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->defaultSchema = $adapter->getCurrentSchema() ?: self::DEFAULT_SCHEMA;
}
/**
* Get schemas
*
* @return string[]
*/
public function getSchemas()
{
$this->loadSchemaData();
return $this->data['schemas'];
}
/**
* {@inheritdoc}
*/
public function getTableNames($schema = null, $includeViews = false)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
if ($includeViews) {
return array_keys($this->data['table_names'][$schema]);
}
$tableNames = [];
foreach ($this->data['table_names'][$schema] as $tableName => $data) {
if ('BASE TABLE' === $data['table_type']) {
$tableNames[] = $tableName;
}
}
return $tableNames;
}
/**
* {@inheritdoc}
*/
public function getTables($schema = null, $includeViews = false)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$tables = [];
foreach ($this->getTableNames($schema, $includeViews) as $tableName) {
$tables[] = $this->getTable($tableName, $schema);
}
return $tables;
}
/**
* {@inheritdoc}
*/
public function getTable($tableName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
if (! isset($this->data['table_names'][$schema][$tableName])) {
throw new Exception('Table "' . $tableName . '" does not exist');
}
$data = $this->data['table_names'][$schema][$tableName];
switch ($data['table_type']) {
case 'BASE TABLE':
$table = new TableObject($tableName);
break;
case 'VIEW':
$table = new ViewObject($tableName);
$table->setViewDefinition($data['view_definition']);
$table->setCheckOption($data['check_option']);
$table->setIsUpdatable($data['is_updatable']);
break;
default:
throw new Exception(
'Table "' . $tableName . '" is of an unsupported type "' . $data['table_type'] . '"'
);
}
$table->setColumns($this->getColumns($tableName, $schema));
$table->setConstraints($this->getConstraints($tableName, $schema));
return $table;
}
/**
* {@inheritdoc}
*/
public function getViewNames($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
$viewNames = [];
foreach ($this->data['table_names'][$schema] as $tableName => $data) {
if ('VIEW' === $data['table_type']) {
$viewNames[] = $tableName;
}
}
return $viewNames;
}
/**
* {@inheritdoc}
*/
public function getViews($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$views = [];
foreach ($this->getViewNames($schema) as $tableName) {
$views[] = $this->getTable($tableName, $schema);
}
return $views;
}
/**
* {@inheritdoc}
*/
public function getView($viewName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
$tableNames = $this->data['table_names'][$schema];
if (isset($tableNames[$viewName]) && 'VIEW' === $tableNames[$viewName]['table_type']) {
return $this->getTable($viewName, $schema);
}
throw new Exception('View "' . $viewName . '" does not exist');
}
/**
* {@inheritdoc}
*/
public function getColumnNames($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
if (! isset($this->data['columns'][$schema][$table])) {
throw new Exception('"' . $table . '" does not exist');
}
return array_keys($this->data['columns'][$schema][$table]);
}
/**
* {@inheritdoc}
*/
public function getColumns($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
$columns = [];
foreach ($this->getColumnNames($table, $schema) as $columnName) {
$columns[] = $this->getColumn($columnName, $table, $schema);
}
return $columns;
}
/**
* {@inheritdoc}
*/
public function getColumn($columnName, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
if (! isset($this->data['columns'][$schema][$table][$columnName])) {
throw new Exception('A column by that name was not found.');
}
$info = $this->data['columns'][$schema][$table][$columnName];
$column = new ColumnObject($columnName, $table, $schema);
$props = [
'ordinal_position',
'column_default',
'is_nullable',
'data_type',
'character_maximum_length',
'character_octet_length',
'numeric_precision',
'numeric_scale',
'numeric_unsigned',
'erratas',
];
foreach ($props as $prop) {
if (isset($info[$prop])) {
$column->{'set' . str_replace('_', '', $prop)}($info[$prop]);
}
}
$column->setOrdinalPosition($info['ordinal_position']);
$column->setColumnDefault($info['column_default']);
$column->setIsNullable($info['is_nullable']);
$column->setDataType($info['data_type']);
$column->setCharacterMaximumLength($info['character_maximum_length']);
$column->setCharacterOctetLength($info['character_octet_length']);
$column->setNumericPrecision($info['numeric_precision']);
$column->setNumericScale($info['numeric_scale']);
$column->setNumericUnsigned($info['numeric_unsigned']);
$column->setErratas($info['erratas']);
return $column;
}
/**
* {@inheritdoc}
*/
public function getConstraints($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintData($table, $schema);
$constraints = [];
foreach (array_keys($this->data['constraints'][$schema][$table]) as $constraintName) {
$constraints[] = $this->getConstraint($constraintName, $table, $schema);
}
return $constraints;
}
/**
* {@inheritdoc}
*/
public function getConstraint($constraintName, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintData($table, $schema);
if (! isset($this->data['constraints'][$schema][$table][$constraintName])) {
throw new Exception('Cannot find a constraint by that name in this table');
}
$info = $this->data['constraints'][$schema][$table][$constraintName];
$constraint = new ConstraintObject($constraintName, $table, $schema);
foreach (
[
'constraint_type' => 'setType',
'match_option' => 'setMatchOption',
'update_rule' => 'setUpdateRule',
'delete_rule' => 'setDeleteRule',
'columns' => 'setColumns',
'referenced_table_schema' => 'setReferencedTableSchema',
'referenced_table_name' => 'setReferencedTableName',
'referenced_columns' => 'setReferencedColumns',
'check_clause' => 'setCheckClause',
] as $key => $setMethod
) {
if (isset($info[$key])) {
$constraint->{$setMethod}($info[$key]);
}
}
return $constraint;
}
/**
* {@inheritdoc}
*/
public function getConstraintKeys($constraint, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintReferences($table, $schema);
// organize references first
$references = [];
foreach ($this->data['constraint_references'][$schema] as $refKeyInfo) {
if ($refKeyInfo['constraint_name'] === $constraint) {
$references[$refKeyInfo['constraint_name']] = $refKeyInfo;
}
}
$this->loadConstraintDataKeys($schema);
$keys = [];
foreach ($this->data['constraint_keys'][$schema] as $constraintKeyInfo) {
if ($constraintKeyInfo['table_name'] === $table && $constraintKeyInfo['constraint_name'] === $constraint) {
$keys[] = $key = new ConstraintKeyObject($constraintKeyInfo['column_name']);
$key->setOrdinalPosition($constraintKeyInfo['ordinal_position']);
if (isset($references[$constraint])) {
//$key->setReferencedTableSchema($constraintKeyInfo['referenced_table_schema']);
$key->setForeignKeyUpdateRule($references[$constraint]['update_rule']);
$key->setForeignKeyDeleteRule($references[$constraint]['delete_rule']);
//$key->setReferencedTableSchema($references[$constraint]['referenced_table_schema']);
$key->setReferencedTableName($references[$constraint]['referenced_table_name']);
$key->setReferencedColumnName($references[$constraint]['referenced_column_name']);
}
}
}
return $keys;
}
/**
* {@inheritdoc}
*/
public function getTriggerNames($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTriggerData($schema);
return array_keys($this->data['triggers'][$schema]);
}
/**
* {@inheritdoc}
*/
public function getTriggers($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$triggers = [];
foreach ($this->getTriggerNames($schema) as $triggerName) {
$triggers[] = $this->getTrigger($triggerName, $schema);
}
return $triggers;
}
/**
* {@inheritdoc}
*/
public function getTrigger($triggerName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTriggerData($schema);
if (! isset($this->data['triggers'][$schema][$triggerName])) {
throw new Exception('Trigger "' . $triggerName . '" does not exist');
}
$info = $this->data['triggers'][$schema][$triggerName];
$trigger = new TriggerObject();
$trigger->setName($triggerName);
$trigger->setEventManipulation($info['event_manipulation']);
$trigger->setEventObjectCatalog($info['event_object_catalog']);
$trigger->setEventObjectSchema($info['event_object_schema']);
$trigger->setEventObjectTable($info['event_object_table']);
$trigger->setActionOrder($info['action_order']);
$trigger->setActionCondition($info['action_condition']);
$trigger->setActionStatement($info['action_statement']);
$trigger->setActionOrientation($info['action_orientation']);
$trigger->setActionTiming($info['action_timing']);
$trigger->setActionReferenceOldTable($info['action_reference_old_table']);
$trigger->setActionReferenceNewTable($info['action_reference_new_table']);
$trigger->setActionReferenceOldRow($info['action_reference_old_row']);
$trigger->setActionReferenceNewRow($info['action_reference_new_row']);
$trigger->setCreated($info['created']);
return $trigger;
}
/**
* Prepare data hierarchy
*
* @param string $type
* @return void
*/
protected function prepareDataHierarchy($type)
{
$data = &$this->data;
foreach (func_get_args() as $key) {
if (! isset($data[$key])) {
$data[$key] = [];
}
$data = &$data[$key];
}
}
/**
* Load schema data
*/
protected function loadSchemaData()
{
}
/**
* Load table name data
*
* @param string $schema
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
}
/**
* Load column data
*
* @param string $table
* @param string $schema
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
}
/**
* Load constraint data
*
* @param string $table
* @param string $schema
*/
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema);
}
/**
* Load constraint data keys
*
* @param string $schema
*/
protected function loadConstraintDataKeys($schema)
{
if (isset($this->data['constraint_keys'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_keys', $schema);
}
/**
* Load constraint references
*
* @param string $table
* @param string $schema
*/
protected function loadConstraintReferences($table, $schema)
{
if (isset($this->data['constraint_references'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_references', $schema);
}
/**
* Load trigger data
*
* @param string $schema
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/SqlServerMetadata.php | src/Metadata/Source/SqlServerMetadata.php | <?php
namespace Laminas\Db\Metadata\Source;
use DateTime;
use Laminas\Db\Adapter\Adapter;
use function array_change_key_case;
use function array_walk;
use function implode;
use function is_string;
use function key;
use const CASE_LOWER;
class SqlServerMetadata extends AbstractSource
{
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'SCHEMATA'])
. ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' != \'INFORMATION_SCHEMA\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['SCHEMA_NAME'];
}
$this->data['schemas'] = $schemas;
}
/**
* @param string $schema
* @return void
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['T', 'TABLE_TYPE'],
['V', 'VIEW_DEFINITION'],
['V', 'CHECK_OPTION'],
['V', 'IS_UPDATABLE'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' t'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'VIEWS']) . ' v'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => $row['TABLE_TYPE'],
'view_definition' => $row['VIEW_DEFINITION'],
'check_option' => $row['CHECK_OPTION'],
'is_updatable' => 'YES' === $row['IS_UPDATABLE'],
];
}
$this->data['table_names'][$schema] = $tables;
}
/**
* @param string $table
* @param string $schema
* @return string
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$p = $this->adapter->getPlatform();
$isColumns = [
['C', 'ORDINAL_POSITION'],
['C', 'COLUMN_DEFAULT'],
['C', 'IS_NULLABLE'],
['C', 'DATA_TYPE'],
['C', 'CHARACTER_MAXIMUM_LENGTH'],
['C', 'CHARACTER_OCTET_LENGTH'],
['C', 'NUMERIC_PRECISION'],
['C', 'NUMERIC_SCALE'],
['C', 'COLUMN_NAME'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'COLUMNS']) . 'C'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')'
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table);
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['ORDINAL_POSITION'],
'column_default' => $row['COLUMN_DEFAULT'],
'is_nullable' => 'YES' === $row['IS_NULLABLE'],
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'],
'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'],
'numeric_precision' => $row['NUMERIC_PRECISION'],
'numeric_scale' => $row['NUMERIC_SCALE'],
'numeric_unsigned' => null,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
}
/**
* @param string $table
* @param string $schema
* @return void
*/
protected function loadConstraintData($table, $schema)
{
// phpcs:disable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['T', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
['KCU', 'COLUMN_NAME'],
['CC', 'CHECK_CLAUSE'],
['RC', 'MATCH_OPTION'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['REFERENCED_TABLE_SCHEMA' => 'KCU2', 'TABLE_SCHEMA'],
['REFERENCED_TABLE_NAME' => 'KCU2', 'TABLE_NAME'],
['REFERENCED_COLUMN_NAME' => 'KCU2', 'COLUMN_NAME'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . ' TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'CHECK_CONSTRAINTS']) . ' CC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['CC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['CC', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . ' RC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU2'
. ' ON ' . $p->quoteIdentifierChain(['RC', 'UNIQUE_CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'UNIQUE_CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'CONSTRAINT_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'ORDINAL_POSITION'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_TYPE'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " WHEN 'CHECK' THEN 4"
. " ELSE 5 END"
. ', ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ', ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$name = null;
$constraints = [];
$isFK = false;
foreach ($results->toArray() as $row) {
if ($row['CONSTRAINT_NAME'] !== $name) {
$name = $row['CONSTRAINT_NAME'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['CONSTRAINT_TYPE'],
'table_name' => $row['TABLE_NAME'],
];
if ('CHECK' === $row['CONSTRAINT_TYPE']) {
$constraints[$name]['check_clause'] = $row['CHECK_CLAUSE'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = 'FOREIGN KEY' === $row['CONSTRAINT_TYPE'];
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA'];
$constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['MATCH_OPTION'];
$constraints[$name]['update_rule'] = $row['UPDATE_RULE'];
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
// phpcs:enable WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
}
/**
* @param string $schema
* @return void
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
'TRIGGER_NAME',
'EVENT_MANIPULATION',
'EVENT_OBJECT_CATALOG',
'EVENT_OBJECT_SCHEMA',
'EVENT_OBJECT_TABLE',
'ACTION_ORDER',
'ACTION_CONDITION',
'ACTION_STATEMENT',
'ACTION_ORIENTATION',
'ACTION_TIMING',
'ACTION_REFERENCE_OLD_TABLE',
'ACTION_REFERENCE_NEW_TABLE',
'ACTION_REFERENCE_OLD_ROW',
'ACTION_REFERENCE_NEW_ROW',
'CREATED',
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifier($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TRIGGERS'])
. ' WHERE ';
if ($schema !== self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
if (null !== $row['created']) {
$row['created'] = new DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Metadata/Source/Factory.php | src/Metadata/Source/Factory.php | <?php
namespace Laminas\Db\Metadata\Source;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Exception\InvalidArgumentException;
use Laminas\Db\Metadata\MetadataInterface;
/**
* Source metadata factory.
*/
class Factory
{
/**
* Create source from adapter
*
* @return MetadataInterface
* @throws InvalidArgumentException If adapter platform name not recognized.
*/
public static function createSourceFromAdapter(Adapter $adapter)
{
$platformName = $adapter->getPlatform()->getName();
switch ($platformName) {
case 'MySQL':
return new MysqlMetadata($adapter);
case 'SQLServer':
return new SqlServerMetadata($adapter);
case 'SQLite':
return new SqliteMetadata($adapter);
case 'PostgreSQL':
return new PostgresqlMetadata($adapter);
case 'Oracle':
return new OracleMetadata($adapter);
default:
throw new InvalidArgumentException("Unknown adapter platform '{$platformName}'");
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/AbstractResultSet.php | src/ResultSet/AbstractResultSet.php | <?php
namespace Laminas\Db\ResultSet;
use ArrayIterator;
use Countable;
use Iterator;
use IteratorAggregate;
use Laminas\Db\Adapter\Driver\ResultInterface;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function count;
use function current;
use function gettype;
use function is_array;
use function is_object;
use function key;
use function method_exists;
use function reset;
abstract class AbstractResultSet implements Iterator, ResultSetInterface
{
/**
* if -1, datasource is already buffered
* if -2, implicitly disabling buffering in ResultSet
* if false, explicitly disabled
* if null, default state - nothing, but can buffer until iteration started
* if array, already buffering
*
* @var mixed
*/
protected $buffer;
/** @var null|int */
protected $count;
/** @var Iterator|IteratorAggregate|ResultInterface */
protected $dataSource;
/** @var int */
protected $fieldCount;
/** @var int */
protected $position = 0;
/**
* Set the data source for the result set
*
* @param array|Iterator|IteratorAggregate|ResultInterface $dataSource
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function initialize($dataSource)
{
// reset buffering
if (is_array($this->buffer)) {
$this->buffer = [];
}
if ($dataSource instanceof ResultInterface) {
$this->fieldCount = $dataSource->getFieldCount();
$this->dataSource = $dataSource;
if ($dataSource->isBuffered()) {
$this->buffer = -1;
}
if (is_array($this->buffer)) {
$this->dataSource->rewind();
}
return $this;
}
if (is_array($dataSource)) {
// its safe to get numbers from an array
$first = current($dataSource);
reset($dataSource);
$this->fieldCount = $first === false ? 0 : count($first);
$this->dataSource = new ArrayIterator($dataSource);
$this->buffer = -1; // array's are a natural buffer
} elseif ($dataSource instanceof IteratorAggregate) {
$this->dataSource = $dataSource->getIterator();
} elseif ($dataSource instanceof Iterator) {
$this->dataSource = $dataSource;
} else {
throw new Exception\InvalidArgumentException(
'DataSource provided is not an array, nor does it implement Iterator or IteratorAggregate'
);
}
return $this;
}
/**
* @return $this Provides a fluent interface
* @throws Exception\RuntimeException
*/
public function buffer()
{
if ($this->buffer === -2) {
throw new Exception\RuntimeException('Buffering must be enabled before iteration is started');
} elseif ($this->buffer === null) {
$this->buffer = [];
if ($this->dataSource instanceof ResultInterface) {
$this->dataSource->rewind();
}
}
return $this;
}
/** @return bool */
public function isBuffered()
{
if ($this->buffer === -1 || is_array($this->buffer)) {
return true;
}
return false;
}
/**
* Get the data source used to create the result set
*
* @return null|Iterator
*/
public function getDataSource()
{
return $this->dataSource;
}
/**
* Retrieve count of fields in individual rows of the result set
*
* @return int
*/
public function getFieldCount()
{
if (null !== $this->fieldCount) {
return $this->fieldCount;
}
$dataSource = $this->getDataSource();
if (null === $dataSource) {
return 0;
}
$dataSource->rewind();
if (! $dataSource->valid()) {
$this->fieldCount = 0;
return 0;
}
$row = $dataSource->current();
if (is_object($row) && $row instanceof Countable) {
$this->fieldCount = $row->count();
return $this->fieldCount;
}
$row = (array) $row;
$this->fieldCount = count($row);
return $this->fieldCount;
}
/**
* Iterator: move pointer to next item
*
* @return void
*/
#[ReturnTypeWillChange]
public function next()
{
if ($this->buffer === null) {
$this->buffer = -2; // implicitly disable buffering from here on
}
if (! is_array($this->buffer) || $this->position === $this->dataSource->key()) {
$this->dataSource->next();
}
$this->position++;
}
/**
* Iterator: retrieve current key
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* Iterator: get current item
*
* @return array|null
*/
#[ReturnTypeWillChange]
public function current()
{
if (-1 === $this->buffer) {
// datasource was an array when the resultset was initialized
return $this->dataSource->current();
}
if ($this->buffer === null) {
$this->buffer = -2; // implicitly disable buffering from here on
} elseif (is_array($this->buffer) && isset($this->buffer[$this->position])) {
return $this->buffer[$this->position];
}
$data = $this->dataSource->current();
if (is_array($this->buffer)) {
$this->buffer[$this->position] = $data;
}
return is_array($data) ? $data : null;
}
/**
* Iterator: is pointer valid?
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
if (is_array($this->buffer) && isset($this->buffer[$this->position])) {
return true;
}
if ($this->dataSource instanceof Iterator) {
return $this->dataSource->valid();
} else {
$key = key($this->dataSource);
return $key !== null;
}
}
/**
* Iterator: rewind
*
* @return void
*/
#[ReturnTypeWillChange]
public function rewind()
{
if (! is_array($this->buffer)) {
if ($this->dataSource instanceof Iterator) {
$this->dataSource->rewind();
} else {
reset($this->dataSource);
}
}
$this->position = 0;
}
/**
* Countable: return count of rows
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
if ($this->count !== null) {
return $this->count;
}
if ($this->dataSource instanceof Countable) {
$this->count = count($this->dataSource);
}
return $this->count;
}
/**
* Cast result set to array of arrays
*
* @return array
* @throws Exception\RuntimeException If any row is not castable to an array.
*/
public function toArray()
{
$return = [];
foreach ($this as $row) {
if (is_array($row)) {
$return[] = $row;
continue;
}
if (
! is_object($row)
|| (
! method_exists($row, 'toArray')
&& ! method_exists($row, 'getArrayCopy')
)
) {
throw new Exception\RuntimeException(
'Rows as part of this DataSource, with type ' . gettype($row) . ' cannot be cast to an array'
);
}
$return[] = method_exists($row, 'toArray') ? $row->toArray() : $row->getArrayCopy();
}
return $return;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/HydratingResultSet.php | src/ResultSet/HydratingResultSet.php | <?php
namespace Laminas\Db\ResultSet;
use ArrayObject;
use Laminas\Hydrator\ArraySerializable;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Hydrator\HydratorInterface;
use function class_exists;
use function gettype;
use function is_array;
use function is_object;
class HydratingResultSet extends AbstractResultSet
{
/** @var HydratorInterface */
protected $hydrator;
/** @var null|object */
protected $objectPrototype;
/**
* Constructor
*
* @param null|object $objectPrototype
*/
public function __construct(?HydratorInterface $hydrator = null, $objectPrototype = null)
{
$defaultHydratorClass = class_exists(ArraySerializableHydrator::class)
? ArraySerializableHydrator::class
: ArraySerializable::class;
$this->setHydrator($hydrator ?: new $defaultHydratorClass());
$this->setObjectPrototype($objectPrototype ?: new ArrayObject());
}
/**
* Set the row object prototype
*
* @param object $objectPrototype
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setObjectPrototype($objectPrototype)
{
if (! is_object($objectPrototype)) {
throw new Exception\InvalidArgumentException(
'An object must be set as the object prototype, a ' . gettype($objectPrototype) . ' was provided.'
);
}
$this->objectPrototype = $objectPrototype;
return $this;
}
/**
* Get the row object prototype
*
* @return object
*/
public function getObjectPrototype()
{
return $this->objectPrototype;
}
/**
* Set the hydrator to use for each row object
*
* @return $this Provides a fluent interface
*/
public function setHydrator(HydratorInterface $hydrator)
{
$this->hydrator = $hydrator;
return $this;
}
/**
* Get the hydrator to use for each row object
*
* @return HydratorInterface
*/
public function getHydrator()
{
return $this->hydrator;
}
/**
* Iterator: get current item
*
* @return object|null
*/
public function current()
{
if ($this->buffer === null) {
$this->buffer = -2; // implicitly disable buffering from here on
} elseif (is_array($this->buffer) && isset($this->buffer[$this->position])) {
return $this->buffer[$this->position];
}
$data = $this->dataSource->current();
$current = is_array($data) ? $this->hydrator->hydrate($data, clone $this->objectPrototype) : null;
if (is_array($this->buffer)) {
$this->buffer[$this->position] = $current;
}
return $current;
}
/**
* Cast result set to array of arrays
*
* @return array
* @throws Exception\RuntimeException If any row is not castable to an array.
*/
public function toArray()
{
$return = [];
foreach ($this as $row) {
$return[] = $this->hydrator->extract($row);
}
return $return;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/ResultSet.php | src/ResultSet/ResultSet.php | <?php
namespace Laminas\Db\ResultSet;
use ArrayObject;
use function in_array;
use function is_array;
use function is_object;
use function method_exists;
class ResultSet extends AbstractResultSet
{
public const TYPE_ARRAYOBJECT = 'arrayobject';
public const TYPE_ARRAY = 'array';
/**
* Allowed return types
*
* @var array
*/
protected $allowedReturnTypes = [
self::TYPE_ARRAYOBJECT,
self::TYPE_ARRAY,
];
/** @var ArrayObject */
protected $arrayObjectPrototype;
/**
* Return type to use when returning an object from the set
*
* @var ResultSet::TYPE_ARRAYOBJECT|ResultSet::TYPE_ARRAY
*/
protected $returnType = self::TYPE_ARRAYOBJECT;
/**
* Constructor
*
* @param string $returnType
* @param null|ArrayObject $arrayObjectPrototype
*/
public function __construct($returnType = self::TYPE_ARRAYOBJECT, $arrayObjectPrototype = null)
{
if (in_array($returnType, $this->allowedReturnTypes, true)) {
$this->returnType = $returnType;
} else {
$this->returnType = self::TYPE_ARRAYOBJECT;
}
if ($this->returnType === self::TYPE_ARRAYOBJECT) {
$this->setArrayObjectPrototype($arrayObjectPrototype ?: new ArrayObject([], ArrayObject::ARRAY_AS_PROPS));
}
}
/**
* Set the row object prototype
*
* @param ArrayObject $arrayObjectPrototype
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setArrayObjectPrototype($arrayObjectPrototype)
{
if (
! is_object($arrayObjectPrototype)
|| (
! $arrayObjectPrototype instanceof ArrayObject
&& ! method_exists($arrayObjectPrototype, 'exchangeArray')
)
) {
throw new Exception\InvalidArgumentException(
'Object must be of type ArrayObject, or at least implement exchangeArray'
);
}
$this->arrayObjectPrototype = $arrayObjectPrototype;
return $this;
}
/**
* Get the row object prototype
*
* @return ArrayObject
*/
public function getArrayObjectPrototype()
{
return $this->arrayObjectPrototype;
}
/**
* Get the return type to use when returning objects from the set
*
* @return string
*/
public function getReturnType()
{
return $this->returnType;
}
/**
* @return array|ArrayObject|null
*/
public function current()
{
$data = parent::current();
if ($this->returnType === self::TYPE_ARRAYOBJECT && is_array($data)) {
/** @var ArrayObject $ao */
$ao = clone $this->arrayObjectPrototype;
if ($ao instanceof ArrayObject || method_exists($ao, 'exchangeArray')) {
$ao->exchangeArray($data);
}
return $ao;
}
return $data;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/ResultSetInterface.php | src/ResultSet/ResultSetInterface.php | <?php
namespace Laminas\Db\ResultSet;
use Countable;
use Traversable;
interface ResultSetInterface extends Traversable, Countable
{
/**
* Can be anything traversable|array
*
* @abstract
* @param iterable $dataSource
* @return mixed
*/
public function initialize($dataSource);
/**
* Field terminology is more correct as information coming back
* from the database might be a column, and/or the result of an
* operation or intersection of some data
*
* @abstract
* @return mixed
*/
public function getFieldCount();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/Exception/ExceptionInterface.php | src/ResultSet/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\ResultSet\Exception;
use Laminas\Db\Exception;
interface ExceptionInterface extends Exception\ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.