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 |
|---|---|---|---|---|---|---|---|---|
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/config/routes.php | config/routes.php | <?php
return [
// default route. You can rmeove if you don't want one.
'__default__' => ['welcome', 'index'],
// Custom regex routes, "#" not allowed. Don't end with slash if
// you want non slash to match (or use /?). Use capture groups for arguments:
// '^/id/(\d+)/?$' => ['Controller', 'index'], passes the capture group match
// into Controller::index method call.
'^/user/([0-9]+)/?$' => ['welcome', 'index'],
// For more complicated PHP based routing, extend GPRouteGenerator
// '^/api/v1/(.*)$' => MyCustomRouteGenerator::class,
];
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/controllers/Users.php | sample_app/controllers/Users.php | <?php
final class Users extends GPController {
public function login() {
$email = $this->post->getString('email');
$password = $this->post->getString('password');
$user = User::getOneByEmail($email);
if (!$user || !password_verify($password, $user->getPassword())) {
Welcome::redirect();
}
GPSession::set('user_id', $user->getID());
Posts::redirect();
}
public function create() {
$email = $this->post->getString('email');
$password = $this->post->getString('password');
$user = User::getOneByEmail($email);
if ($user) {
Welcome::redirect();
}
$user = (new User())
->setEmail($email)
->setPassword(password_hash($password, PASSWORD_DEFAULT))
->save();
$this->login();
}
public function logout() {
GPSession::destroy();
Welcome::redirect();
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/controllers/Posts.php | sample_app/controllers/Posts.php | <?php
final class Posts extends GPController {
public function __construct() {
if (!GPSession::get('user_id')) {
Welcome::redirect();
}
}
public function index() {
GP::view('post_list', ['posts' => Post::getAll()]);
}
public function one($id) {
$post = Post::getByID($id);
if (!$post) {
GP::return404();
}
$post->loadComments();
GP::view('one_post', ['post' => $post]);
}
public function create() {
$text = $this->post->getString('text');
$post = (new Post())->setText($text)->save();
$post->addCreator(User::getByID(GPSession::get('user_id')))->save();
Posts::redirect();
}
public function createComment() {
$text = $this->post->getString('text');
$post_id = $this->post->getString('post_id');
$post = Post::getByID($post_id);
$comment = (new Comment())->setText($text)->save();
$comment->addCreator(User::getByID(GPSession::get('user_id')))->save();
$post->addComments($comment)->save();
Posts::redirect()->one($post_id);
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/controllers/Welcome.php | sample_app/controllers/Welcome.php | <?php
class Welcome extends GPController {
public function index() {
GP::view('login_view');
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/controllers/admin/Admin.php | sample_app/controllers/admin/Admin.php | <?php
class Admin extends GPController {
public function __construct() {
if (!GPConfig::get()->admin_enabled) {
GP::return404();
}
}
public function index() {
$data = [
'types' => GPNodeMap::regenAndGetAllTypes(),
'counts' => ipull(GPDatabase::get()->getTypeCounts(), 'count', 'type'),
];
GPDatabase::get()->dispose();
GP::viewWithLayout('admin/explore_view', 'layout/admin_layout', $data);
}
public function node_type($type) {
$name = GPNodeMap::getClass($type);
$data = [
'type' => $type,
'name' => $name,
'nodes' => $name::getAll(),
];
GPDatabase::get()->dispose();
GP::viewWithLayout('admin/node_type_view', 'layout/admin_layout', $data);
}
public function node($id) {
$node = GPNode::getByID($id);
if (!$node) {
self::redirect();
}
$node->loadConnectedNodes($node::getEdgeTypes());
GP::viewWithLayout(
'admin/node_view',
'layout/admin_layout',
['node' => $node]
);
}
public function edges() {
$node_classes = GPNodeMap::regenAndGetAllTypes();
$edges = [];
foreach ($node_classes as $class) {
array_concat_in_place($edges, $class::getEdgeTypes());
}
GP::viewWithLayout(
'admin/edge_view',
'layout/admin_layout',
['edges' => $edges]
);
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/controllers/admin/AdminAjax.php | sample_app/controllers/admin/AdminAjax.php | <?php
class AdminAjax extends GPController {
public function __construct() {
if (!GPConfig::get()->admin_enabled) {
GP::return404();
}
}
public function create($type) {
if ($this->post->getExists('create')) {
GPNode::createFromType($type)->save();
}
Admin::redirect()->node_type($type);
}
public function delete($type) {
if ($this->post->getInt('delete_node_id')) {
GPNode::getByID($this->post->getInt('delete_node_id'))->delete();
}
Admin::redirect()->node_type($type);
}
public function save($id) {
$node = GPNode::getByID($id);
$key = $this->post->getString('data_key');
$val = $this->post->getString('data_val');
$key_to_unset = $this->post->getString('data_key_to_unset');
if ($key && $val) {
$data_type = $node::getDataTypeByName($key);
if (
$data_type !== null &&
$data_type->getType() === GPDataType::GP_ARRAY
) {
$val = json_decode($val, true);
} else if (
$data_type !== null &&
$data_type->getType() === GPDataType::GP_BOOL
) {
$val = (bool) $val;
}
$node->setData($key, $val)->save();
}
if ($key_to_unset) {
$node->unsetData($key_to_unset)->save();
}
$edge_type = $this->post->get('edge_type');
if ($edge_type && $this->post->getInt('to_id')) {
$edge = is_numeric($edge_type) ?
$node::getEdgeTypeByType($edge_type) :
$node::getEdgeType($edge_type);
$other_node = GPNode::getByID($this->post->getInt('to_id'));
if ($this->post->getExists('delete')) {
$node->addPendingRemovalNodes($edge, [$other_node]);
} else {
$node->addPendingConnectedNodes($edge, [$other_node]);
}
$node->save();
}
Admin::redirect()->node($id);
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/models/User.php | sample_app/models/User.php | <?php
final class User extends GPNode {
protected static function getDataTypesImpl() {
return [
new GPDataType('email', GPDataType::GP_STRING, true),
new GPDataType('password', GPDataType::GP_STRING),
];
}
protected static function getEdgeTypesImpl() {
return [
(new GPEdgeType(Post::class, 'posts'))
->inverse(Comment::getEdgeType('creator')),
(new GPEdgeType(Comment::class, 'comments'))
->inverse(Comment::getEdgeType('creator')),
];
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/models/Comment.php | sample_app/models/Comment.php | <?php
final class Comment extends GPNode {
protected static function getDataTypesImpl() {
return [
new GPDataType('text', GPDataType::GP_STRING),
];
}
protected static function getEdgeTypesImpl() {
return [
(new GPEdgeType(Post::class))->setSingleNodeName('post'),
(new GPEdgeType(User::class, 'creators'))->setSingleNodeName('creator'),
];
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/models/Post.php | sample_app/models/Post.php | <?php
final class Post extends GPNode {
protected static function getDataTypesImpl() {
return [
new GPDataType('text', GPDataType::GP_STRING),
];
}
protected static function getEdgeTypesImpl() {
return [
(new GPEdgeType(Comment::class, 'comments'))
->inverse(Comment::getEdgeType('post')),
(new GPEdgeType(User::class, 'creators'))->setSingleNodeName('creator'),
];
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/one_post.php | sample_app/views/one_post.php | <p>
<?=$post->getText()?>
</p>
<label>Comments:</label>
<ul>
<?php foreach ($post->getComments() as $comment):?>
<li><?=$comment->getText()?></li>
<?php endforeach ?>
</ul>
<form method="POST" action="<?=Posts::URI()->createComment()?>">
<label>New Comment:</label>
<textarea name="text"></textarea>
<button>Create</button>
<input type="hidden" name="post_id" value="<?=$post->getID()?>">
<?=GPSecurity::csrf()?>
</form> | php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/login_view.php | sample_app/views/login_view.php | <form method="POST" action="<?=Users::URI()->create()?>">
<label>New User</label>
<label>Email:</label>
<input type="email" name="email" required>
<label>Password:</label>
<input type="password" name="password" required>
<button>Submit</button>
<?=GPSecurity::csrf()?>
</form>
<form method="POST" action="<?=Users::URI()->login()?>">
<label>Existing User</label>
<label>Email:</label>
<input type="email" name="email" required>
<label>Password:</label>
<input type="password" name="password" required>
<button>Submit</button>
<?=GPSecurity::csrf()?>
</form> | php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/post_list.php | sample_app/views/post_list.php | <form method="POST" action="<?=Posts::URI()->create()?>">
<label>New Post:</label>
<textarea name="text"></textarea>
<button>Create</button>
<?=GPSecurity::csrf()?>
</form>
<ul>
<?php foreach ($posts as $post):?>
<li>
<a href="<?=Posts::URI()->one($post->getID())?>">
<?=StringLibrary::truncate($post->getText(), 10)?>
</a>
</li>
<?php endforeach ?>
</ul> | php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/admin/node_view.php | sample_app/views/admin/node_view.php | <a href="<?=Admin::URI()->node_type($node::getType())?>">
back to <?= get_class($node) ?> list
</a>
<h2><?= get_class($node) ?> ID <?= $node->getID() ?></h2>
<h3>Data:</h3>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th scope="col" class="col-xs-5">Key</th>
<th scope="col" class="col-xs-5">Value</th>
<th scope="col" class="col-xs-1">Indexed</th>
<th scope="col" class="col-xs-1 text-center">Unset</th>
</tr>
</thead>
<tbody>
<?php foreach ($node->getDataArray() as $key => $value): ?>
<tr>
<th scope="row"><code><?=$key?></code></th>
<th scope="row"><?=is_array($value) ? json_encode($value) : $value?></th>
<th scope="row">
<?=idx($node->getIndexedData(), $key) ? 'yes' : 'no'?>
</th>
<th scope="row">
<form
class="text-center"
action="<?=AdminAjax::URI()->save($node->getID())?>"
method="POST">
<?=GPSecurity::csrf()?>
<input name="data_key_to_unset" type="hidden" value="<?=$key?>">
<button class="btn btn-xs btn-danger">
X
</button>
</form>
</th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<form action="<?=AdminAjax::URI()->save($node->getID())?>" method="POST">
<?=GPSecurity::csrf()?>
<input name="data_key" type="text" placeholder="key">
<input name="data_val" type="text" placeholder="val">
<button class="btn btn-primary btn-sm">
Set data
</button>
</form>
<h3>Edges:</h3>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th scope="col" class="col-xs-6">Edge</th>
<th scope="col" class="col-xs-5">To Node</th>
<th scope="col" class="col-xs-1 text-center">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($node->getConnectedNodes($node::getEdgeTypes())
as $e => $nodes): ?>
<?php foreach ($nodes as $conn_node): ?>
<tr>
<th scope="row">
<code><?=$node::getEdgeTypeByType($e)->getName().' - '.$e?></code>
</th>
<th scope="row">
<a href="<?=Admin::URI()->node($conn_node->getID())?>">
Link
</a>
ID: <?=$conn_node->getID()?>
type: <?=get_class($conn_node)?>
<?=method_exists( $conn_node, '__toString' ) ? ' - '.$conn_node : ''?>
</th>
<th scope="row">
<form
class="text-center"
action="<?=AdminAjax::URI()->save($node->getID())?>"
method="POST">
<?=GPSecurity::csrf()?>
<input name="edge_type" type="hidden" value="<?=$e?>">
<input
name="to_id"
type="hidden"
value="<?=$conn_node->getID()?>">
<input name="delete" type="hidden">
<button class="btn btn-xs btn-danger">
X
</button>
</form>
</th>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<form action="<?=AdminAjax::URI()->save($node->getID())?>" method="POST">
<?=GPSecurity::csrf()?>
<input name="edge_type" type="text" placeholder="edge type">
<input name="to_id" type="text" placeholder="To node ID">
<button class="btn btn-primary btn-sm">
Add edge
</button>
</form>
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/admin/edge_view.php | sample_app/views/admin/edge_view.php | <h1>Edges</h1>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th scope="col" class="col-xs-4">Type</th>
<th scope="col" class="col-xs-4">Name</th>
<th scope="col" class="col-xs-4">From Type</th>
<th scope="col" class="col-xs-4">To Type</th>
</tr>
</thead>
<tbody>
<?php foreach ($edges as $edge): ?>
<tr>
<th scope="row"><code><?=$edge->getType()?></code></th>
<th scope="row"><?=$edge->getName()?></th>
<th scope="row"><?=GPNodeMap::getCLass($edge->getFromType())?></th>
<th scope="row"><?=GPNodeMap::getClass($edge->getToType())?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div> | php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/admin/node_type_view.php | sample_app/views/admin/node_type_view.php | <h3>
<form action="<?=AdminAjax::URI()->create($type)?>" method="POST">
<?=GPSecurity::csrf()?>
<?=$name?>
<button class="btn btn-primary">
New <?=$name?>
</button>
<input name="create" type="hidden">
</form>
</h3>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Data</th>
<th>Updated</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($nodes as $node): ?>
<tr>
<td>
<a href="<?=Admin::URI()->node($node->getID())?>">
<?=$node->getID()?>
</a>
</td>
<td><?=substr($node->getJSONData(), 0, 128)?></td>
<td><?=$node->getUpdated()?></td>
<td>
<a
class="btn btn-sm btn-default active"
href="<?=Admin::URI()->node($node->getID())?>">
Edit
</a>
</td>
<td>
<form action="<?=AdminAjax::URI()->delete($type)?>" method="POST">
<?=GPSecurity::csrf()?>
<input
name="delete_node_id"
type="hidden"
value="<?=$node->getID()?>"
/>
<button class="btn btn-sm btn-danger">Delete</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<tbody>
</table>
</div>
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/admin/explore_view.php | sample_app/views/admin/explore_view.php | <h3>Node Types</h3>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<?php foreach ($types as $id => $name): ?>
<tr>
<td><a href="<?=Admin::URI()->node_type($id)?>"><?=$id?></a></td>
<td><a href="<?=Admin::URI()->node_type($id)?>"><?=$name?></a></td>
<td><?=idx($counts, $id, 0)?></td>
</tr>
<?php endforeach; ?>
<tbody>
</table>
</div>
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/views/layout/admin_layout.php | sample_app/views/layout/admin_layout.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node Explorer</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body style="padding-top: 50px;">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="<?=Admin::URI()?>">Node Types</a>
<a class="navbar-brand" href="<?=Admin::URI()->edges()?>">Edge Types</a>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="page-header">
<h1>Node Explorer</h1>
</div>
<?=$content?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
mikeland73/graphp | https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/sample_app/libraries/StringLibrary.php | sample_app/libraries/StringLibrary.php | <?php
final class StringLibrary extends GPObject {
public static function truncate($string, $length) {
if (mb_strlen($string) > $length) {
$string = mb_substr($string, 0, $length - 3).'...';
}
return $string;
}
}
| php | MIT | 5f55bbb2eae1e058f83e831baaaec728a9c10dfd | 2026-01-05T04:54:31.965184Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/ecs.php | ecs.php | <?php
declare(strict_types=1);
use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer;
use PhpCsFixer\Fixer\ControlStructure\YodaStyleFixer;
use PhpCsFixer\Fixer\FunctionNotation\NativeFunctionInvocationFixer;
use PhpCsFixer\Fixer\Import\NoUnusedImportsFixer;
use PhpCsFixer\Fixer\Import\OrderedImportsFixer;
use PhpCsFixer\Fixer\Operator\ConcatSpaceFixer;
use PhpCsFixer\Fixer\Phpdoc\PhpdocTypesOrderFixer;
use PhpCsFixer\Fixer\Whitespace\ArrayIndentationFixer;
use PhpCsFixer\Fixer\Whitespace\MethodChainingIndentationFixer;
use PhpCsFixerCustomFixers\Fixer\NoDuplicatedImportsFixer;
use Symplify\CodingStandard\Fixer\ArrayNotation\StandaloneLineInMultilineArrayFixer;
use Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer;
use Symplify\CodingStandard\Fixer\Spacing\MethodChainingNewlineFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
return static function (ECSConfig $ecsConfig): void {
$ecsConfig->parallel();
$ecsConfig->paths([
__DIR__ . '/src',
]);
$ecsConfig->skip([
__DIR__ . '/ecs.php',
__DIR__ . '/src/DependencyInjection/Configuration.php',
]);
$ecsConfig->sets([
SetList::SYMPLIFY,
SetList::PSR_12,
SetList::DOCTRINE_ANNOTATIONS,
SetList::CLEAN_CODE,
]);
$ecsConfig->ruleWithConfiguration(YodaStyleFixer::class, [
'equal' => false,
'identical' => false,
'less_and_greater' => false,
]);
$ecsConfig->ruleWithConfiguration(PhpdocTypesOrderFixer::class, [
'null_adjustment' => 'always_last',
'sort_algorithm' => 'none',
]);
$ecsConfig->ruleWithConfiguration(OrderedImportsFixer::class, [
'imports_order' => ['class', 'function', 'const'],
]);
$ecsConfig->ruleWithConfiguration(ConcatSpaceFixer::class, [
'spacing' => 'one',
]);
$ecsConfig->ruleWithConfiguration(LineLengthFixer::class, [
LineLengthFixer::LINE_LENGTH => 120,
]);
$ecsConfig->rule(NativeFunctionInvocationFixer::class);
$ecsConfig->rule(NoTrailingCommaInSinglelineFixer::class);
$ecsConfig->rule(MethodChainingNewlineFixer::class);
$ecsConfig->rule(MethodChainingIndentationFixer::class);
$ecsConfig->rule(StandaloneLineInMultilineArrayFixer::class);
$ecsConfig->rule(ArrayIndentationFixer::class);
$ecsConfig->rule(NoUnusedImportsFixer::class);
$ecsConfig->rule(NoDuplicatedImportsFixer::class);
};
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/SwordBundle.php | src/SwordBundle.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle;
use Sword\SwordBundle\DependencyInjection\Compiler\WordpressPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
final class SwordBundle extends Bundle
{
public function getPath(): string
{
return \dirname(__DIR__);
}
public function build(ContainerBuilder $container): void
{
$container->addCompilerPass(new WordpressPass());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Event/WooCommerceRegistrationEvent.php | src/Event/WooCommerceRegistrationEvent.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Event;
use Symfony\Contracts\EventDispatcher\Event;
final class WooCommerceRegistrationEvent extends Event
{
public function __construct(
public readonly int $customerId,
public readonly array $customerData,
) {
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Entity/WordpressEntityInterface.php | src/Entity/WordpressEntityInterface.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Entity;
interface WordpressEntityInterface
{
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Controller/ReauthenticateController.php | src/Controller/ReauthenticateController.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Controller;
use Sword\SwordBundle\Loader\WordpressLoader;
use Sword\SwordBundle\Security\UserReauthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Annotation\Route;
#[AsController]
final class ReauthenticateController extends AbstractController
{
#[Route('/reauthenticate', name: Routes::REAUTHENTICATE, priority: 100)]
public function reauthenticate(
Request $request,
WordpressLoader $wordpressLoader,
UserReauthenticator $userReauthenticator,
): Response {
$response = $request->headers->get('referer') === $request->getRequestUri()
? $this->redirectToRoute(Routes::WORDPRESS, [
'path' => ''
])
: $this->redirect($request->headers->get('referer') ?: $this->generateUrl(Routes::WORDPRESS, [
'path' => ''
]));
$wordpressLoader->loadWordpress();
$userReauthenticator->reauthenticate();
return $response;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Controller/WordpressController.php | src/Controller/WordpressController.php | <?php
namespace Sword\SwordBundle\Controller;
use Sword\SwordBundle\Loader\WordpressLoader;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Annotation\Route;
#[AsController]
class WordpressController extends AbstractController
{
#[Route('/{path<.*>}', name: Routes::WORDPRESS, priority: -100)]
public function index(WordpressLoader $wordpressLoader, string $path): Response
{
return $wordpressLoader->createWordpressResponse($path);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Controller/Routes.php | src/Controller/Routes.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Controller;
final class Routes
{
public const WORDPRESS = 'sword_wordpress';
public const REAUTHENTICATE = 'sword_reauthenticate';
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Translation/ChildThemeTranslationInitializer.php | src/Translation/ChildThemeTranslationInitializer.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Translation;
use Sword\SwordBundle\Service\AbstractWordpressService;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final class ChildThemeTranslationInitializer extends AbstractWordpressService
{
public function __construct(
#[Autowire('%sword.child_theme_translation_domain%')] private readonly string $textDomain,
) {
}
public function initialize(): void
{
add_action('after_setup_theme', [$this, 'loadThemeLanguage']);
}
public function getLanguagesPath(): string
{
return get_stylesheet_directory() . '/languages';
}
public function loadThemeLanguage(): void
{
load_child_theme_textdomain($this->textDomain, $this->getLanguagesPath());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Translation/LocaleSwitcher.php | src/Translation/LocaleSwitcher.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Translation;
use Sword\SwordBundle\Service\AbstractWordpressService;
use Symfony\Component\Translation\LocaleSwitcher as SymfonyLocaleSwitcher;
final class LocaleSwitcher extends AbstractWordpressService
{
public function __construct(
private readonly SymfonyLocaleSwitcher $localeSwitcher
) {
}
public function getPriority(): int
{
return 1000;
}
public function initialize(): void
{
$this->localeSwitcher->setLocale(get_locale());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/DependencyInjection/SwordExtension.php | src/DependencyInjection/SwordExtension.php | <?php
namespace Sword\SwordBundle\DependencyInjection;
use Doctrine\Bundle\DoctrineBundle\Dbal\RegexSchemaAssetFilter;
use ReflectionClass;
use Sword\SwordBundle\Service\WordpressService;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
use Symfony\Component\Yaml\Yaml;
final class SwordExtension extends ConfigurableExtension implements PrependExtensionInterface
{
public function getAlias(): string
{
return 'sword';
}
public function prepend(ContainerBuilder $container): void
{
$swordConfig = $container->getExtensionConfig('sword');
$prioritizedConfigNames = array_diff(
['security', 'doctrine'],
$swordConfig[0]['overridden_configurations'] ?? []
);
$prioritizedConfigs = [];
$extensions = $container->getExtensions();
foreach (Yaml::parseFile(__DIR__ . '/../../config/app.yaml') as $name => $config) {
if (empty($extensions[$name])) {
continue;
}
if (\in_array($name, $prioritizedConfigNames, true)) {
if (!\array_key_exists($name, $prioritizedConfigs)) {
$prioritizedConfigs[$name] = [];
}
$prioritizedConfigs[$name][] = $config;
} else {
if ($name === 'doctrine') {
$config = $this->mergeDoctrineConfig($container, $config);
}
$this->mergeConfigIntoOne($container, $name, $config);
}
}
foreach ($prioritizedConfigNames as $name) {
if (empty($prioritizedConfigs[$name])) {
continue;
}
foreach ($prioritizedConfigs[$name] as $config) {
if ($name === 'doctrine') {
$config = $this->mergeDoctrineConfig($container, $config);
}
$this->mergeConfigIntoOne($container, $name, $config, true);
}
}
}
protected function loadInternal(array $mergedConfig, ContainerBuilder $container): void
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
$loader->load('services.yaml');
$container->registerForAutoconfiguration(WordpressService::class)
->addTag('sword.wordpress_service')
;
$container->setParameter('sword.wordpress_core_dir', $mergedConfig['wordpress_core_dir']);
$container->setParameter('sword.wordpress_content_dir', $mergedConfig['wordpress_content_dir']);
$container->setParameter(
'sword.child_theme_translation_domain',
$mergedConfig['child_theme_translation_domain'],
);
$container->setParameter('sword.table_prefix', $mergedConfig['table_prefix']);
$container->setParameter('sword.public_services', $mergedConfig['public_services']);
$container->setParameter('sword.widgets_path', $mergedConfig['widgets_path']);
$container->setParameter('sword.app_namespace', $mergedConfig['app_namespace']);
$container->setParameter('sword.wordpress_host', $mergedConfig['wordpress_host']);
if ($mergedConfig['widgets_path'] && file_exists($mergedConfig['widgets_path'])) {
$definition = (new Definition())
->setLazy(true)
->addTag('sword.wordpress_widget')
;
$loader->registerClasses($definition, $mergedConfig['widgets_namespace'], $mergedConfig['widgets_path']);
}
$definition = new Definition(RegexSchemaAssetFilter::class, ['~^(?!(%sword.table_prefix%))~']);
$definition->addTag('doctrine.dbal.schema_filter', [
'connection' => 'default',
]);
$container->setDefinition('doctrine.dbal.default_regex_schema_filter', $definition);
}
private function mergeDoctrineConfig(ContainerBuilder $container, array $config): array
{
$doctrineConfig = $container->getExtensionConfig('doctrine');
if (isset($doctrineConfig[0]['dbal']['connections'])) {
if (empty($doctrineConfig[0]['dbal']['connections']['default'])) {
$doctrineConfig[0]['dbal']['connections']['default'] = $config['dbal'];
}
$config['dbal'] = $doctrineConfig[0]['dbal'];
}
return $config;
}
private function mergeConfigIntoOne(
ContainerBuilder $container,
string $name,
array $config = [],
bool $reverse = false,
): void {
$originalConfig = $container->getExtensionConfig($name);
if (!\count($originalConfig)) {
$originalConfig[] = [];
}
$originalConfig[0] = $reverse
? $this->mergeDistinct($originalConfig[0], $config)
: $this->mergeDistinct($config, $originalConfig[0]);
$this->setExtensionConfig($container, $name, $originalConfig);
}
private function setExtensionConfig(ContainerBuilder $container, string $name, array $config = []): void
{
$classRef = new ReflectionClass(ContainerBuilder::class);
$extensionConfigsRef = $classRef->getProperty('extensionConfigs');
$newConfig = $extensionConfigsRef->getValue($container);
$newConfig[$name] = $config;
$extensionConfigsRef->setValue($container, $newConfig);
}
private function mergeDistinct(array $first, array $second): array
{
foreach ($second as $index => $value) {
if (\is_int($index) && !\in_array($value, $first, true)) {
$first[] = $value;
} elseif (!\array_key_exists($index, $first)) {
$first[$index] = $value;
} elseif (\is_array($value)) {
if (\is_array($first[$index])) {
$first[$index] = $this->mergeDistinct($first[$index], $value);
} else {
$first[$index] = $value;
}
} else {
$first[$index] = $value;
}
}
return $first;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/DependencyInjection/Configuration.php | src/DependencyInjection/Configuration.php | <?php
namespace Sword\SwordBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
final class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('sword');
$treeBuilder->getRootNode()
->children()
->scalarNode('wordpress_core_dir')->defaultValue('%kernel.project_dir%/wp/core')->end()
->scalarNode('wordpress_content_dir')->defaultValue('%kernel.project_dir%/wp/content')->end()
->scalarNode('child_theme_translation_domain')->isRequired()->end()
->scalarNode('child_theme_language_path')->defaultValue('%kernel.project_dir%/translations/%sword.child_theme_translation_domain%')->end()
->scalarNode('table_prefix')->defaultValue('wp_')->end()
->scalarNode('app_namespace')->defaultValue('App\\')->end()
->scalarNode('widgets_namespace')->defaultValue('App\\Widget\\')->end()
->scalarNode('widgets_path')->defaultValue('%kernel.project_dir%/src/Widget/')->end()
->scalarNode('wordpress_host')->defaultValue('')->end()
->arrayNode('overridden_configurations')
->scalarPrototype()->end()
->end()
->arrayNode('public_services')
->scalarPrototype()->end()
->end()
->end()
;
return $treeBuilder;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/DependencyInjection/Compiler/WordpressPass.php | src/DependencyInjection/Compiler/WordpressPass.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\DependencyInjection\Compiler;
use Sword\SwordBundle\Store\WordpressWidgetStore;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class WordpressPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$this->processWidgets($container);
$this->processPublicServices($container);
}
private function processWidgets(ContainerBuilder $container): void
{
$widgetStore = $container->findDefinition(WordpressWidgetStore::class);
$taggedServices = $container->findTaggedServiceIds('sword.wordpress_widget');
foreach (array_keys($taggedServices) as $widget) {
$widgetStore->addMethodCall('addWidget', [$widget]);
}
}
/**
* @param ContainerBuilder $container
* @return void
*/
private function processPublicServices(ContainerBuilder $container): void
{
$publicServices = $container->getParameter('sword.public_services');
foreach ($publicServices as $service) {
$definition = $container->findDefinition($service);
if ($container->hasAlias($service)) {
$alias = $container->getAlias($service);
$alias->setPublic(true);
} else {
$definition->setPublic(true);
}
}
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Exception/WordpressLoginSuccessfulException.php | src/Exception/WordpressLoginSuccessfulException.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Exception;
final class WordpressLoginSuccessfulException extends \Exception
{
public function __construct(
public readonly string $username,
public readonly string $password,
public readonly bool $rememberMe,
) {
parent::__construct();
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Exception/WordpressLougoutSuccessfulException.php | src/Exception/WordpressLougoutSuccessfulException.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Exception;
use Symfony\Component\HttpFoundation\Response;
final class WordpressLougoutSuccessfulException extends \Exception
{
public function __construct(
public readonly Response $response
) {
parent::__construct();
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Helper/ContainerHelper.php | src/Helper/ContainerHelper.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Helper;
use Sword\SwordBundle\Loader\WordpressLoader;
use Sword\SwordBundle\Service\WordpressService;
/**
* @template T
* @param class-string<T> $serviceId
* @return T
*/
function get_symfony_service(string $serviceId): mixed
{
/** @var WordpressLoader $wordpressLoader */
global $wordpressLoader;
return $wordpressLoader->container->get($serviceId);
}
function get_symfony_parameter(string $parameter): mixed
{
/** @var WordpressLoader $wordpressLoader */
global $wordpressLoader;
return $wordpressLoader->container->getParameter($parameter);
}
function initialize_services(): void
{
/** @var WordpressLoader $wordpressLoader */
global $wordpressLoader;
$services = iterator_to_array($wordpressLoader->wordpressServices->getIterator());
$wordpressLoader->lazyServiceInstantiator->requireAll();
usort(
$services,
static fn (WordpressService $a, WordpressService $b) => $b->getPriority() <=> $a->getPriority(),
);
foreach ($services as $service) {
$service->initialize();
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Loader/wp-load.php | src/Loader/wp-load.php | <?php
/**
* This file is included at the end of the project's `wp-config.php`.
*/
// Redefines globals that had been unset
global $action;
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Loader/WordpressLoader.php | src/Loader/WordpressLoader.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Loader;
use Sword\SwordBundle\Event\WooCommerceRegistrationEvent;
use Sword\SwordBundle\Exception\WordpressLoginSuccessfulException;
use Sword\SwordBundle\Exception\WordpressLougoutSuccessfulException;
use Sword\SwordBundle\Security\UserAuthenticator;
use Sword\SwordBundle\Store\WordpressWidgetStore;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
final class WordpressLoader implements EventSubscriberInterface
{
private ?array $auth = null;
public function __construct(
#[Autowire('@service_container')]
public readonly Container $container,
#[TaggedIterator('sword.wordpress_service')]
public readonly iterable $wordpressServices,
public readonly WordpressWidgetStore $widgetStore,
public readonly LazyServiceInstantiator $lazyServiceInstantiator,
private readonly RequestStack $requestStack,
private readonly UserAuthenticator $userAuthenticator,
private readonly CsrfTokenManagerInterface $csrfTokenManager,
#[Autowire('%sword.wordpress_core_dir%')]
private readonly string $wordpressDirectory,
) {
}
public static function getSubscribedEvents(): array
{
return [
WooCommerceRegistrationEvent::class => 'onWooCommerceRegistration',
];
}
public function onWooCommerceRegistration(WooCommerceRegistrationEvent $event): void
{
$this->auth = [
'id' => $event->customerId,
'data' => $event->customerData,
];
}
public function createWordpressResponse(string $urlPathName): Response
{
$request = $this->requestStack->getCurrentRequest();
ob_start();
$obLevel = ob_get_level();
global $wordpressLoader;
$wordpressLoader = $this;
foreach (WordpressGlobals::GLOBALS as $global) {
global $$global;
}
$entryPoint = $this->wordpressDirectory . '/index.php';
if (\in_array(basename($urlPathName), ['wp-login.php', 'wp-signup.php', 'wp-comments-post.php'], true)) {
$_SERVER['PHP_SELF'] = '/' . basename($urlPathName);
$entryPoint = $this->wordpressDirectory . '/' . basename($urlPathName);
} elseif (str_starts_with($urlPathName, 'wp-admin/')) {
if ($urlPathName === 'wp-admin/') {
$urlPathName = 'wp-admin/index.php';
}
$_SERVER['PHP_SELF'] = '/' . $urlPathName;
$entryPoint = $this->wordpressDirectory . '/' . $urlPathName;
} else {
$_SERVER['PHP_SELF'] = '/' . $urlPathName;
}
$_SERVER['SCRIPT_FILENAME'] = $entryPoint;
try {
require_once $entryPoint;
} catch (WordpressLoginSuccessfulException $exception) {
return $this->getAuthResponse($exception->username, $exception->password, $exception->rememberMe);
} catch (WordpressLougoutSuccessfulException) {
return new RedirectResponse($this->userAuthenticator->getLoginUrl($request));
}
if ($this->auth) {
wc_set_customer_auth_cookie($this->auth['id']);
return $this->getAuthResponse(
$this->auth['data']['user_login'] ?? '',
$this->auth['data']['user_pass'] ?? '',
false,
);
}
while (ob_get_level() > $obLevel) {
ob_end_flush();
}
return new Response(ob_get_clean(), is_404() ? 404 : 200);
}
public function loadWordpress(): void
{
global $wordpressLoader;
$wordpressLoader = $this;
foreach (WordpressGlobals::GLOBALS as $global) {
global $$global;
}
require_once $this->wordpressDirectory . '/wp-load.php';
}
private function getAuthResponse(string $username, string $password, bool $rememberMe): RedirectResponse
{
$session = $this->requestStack->getSession();
$session->getFlashBag()
->set(
'wp_login',
[$username, $password, $rememberMe, $this->csrfTokenManager->getToken('authenticate') ->getValue()],
);
return new RedirectResponse($this->requestStack->getCurrentRequest()?->getRequestUri(), 302);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Loader/WordpressGlobals.php | src/Loader/WordpressGlobals.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Loader;
final class WordpressGlobals
{
public const GLOBALS = [
'_links_add_base',
'_links_add_target',
'_menu_item_sort_prop',
'_nav_menu_placeholder',
'_new_bundled_files',
'_old_files',
'_parent_pages',
'_registered_pages',
'_updated_user_settings',
'_wp_additional_image_sizes',
'_wp_admin_css_colors',
'_wp_default_headers',
'_wp_deprecated_widgets_callbacks',
'_wp_last_object_menu',
'_wp_last_utility_menu',
'_wp_menu_nopriv',
'_wp_nav_menu_max_depth',
'_wp_post_type_features',
'_wp_real_parent_file',
'_wp_registered_nav_menus',
'_wp_sidebars_widgets',
'_wp_submenu_nopriv',
'_wp_suspend_cache_invalidation',
'_wp_theme_features',
'_wp_using_ext_object_cache',
'action',
'active_signup',
'admin_body_class',
'admin_page_hooks',
'all_links',
'allowedentitynames',
'allowedposttags',
'allowedtags',
'auth_secure_cookie',
'authordata',
'avail_post_mime_types',
'avail_post_stati',
'blog_id',
'blog_title',
'blogname',
'cat',
'cat_id',
'charset_collate',
'comment',
'comment_alt',
'comment_depth',
'comment_status',
'comment_thread_alt',
'comment_type',
'comments',
'compress_css',
'compress_scripts',
'concatenate_scripts',
'current_screen',
'current_site',
'current_user',
'currentcat',
'currentday',
'currentmonth',
'custom_background',
'custom_image_header',
'default_menu_order',
'descriptions',
'domain',
'editor_styles',
'error',
'errors',
'EZSQL_ERROR',
'feeds',
'GETID3_ERRORARRAY',
'hook_suffix',
'HTTP_RAW_POST_DATA',
'id',
'in_comment_loop',
'interim_login',
'is_apache',
'is_chrome',
'is_gecko',
'is_IE',
'is_IIS',
'is_iis7',
'is_macIE',
'is_NS4',
'is_opera',
'is_safari',
'is_winIE',
'l10n',
'link',
'link_id',
'locale',
'locked_post_status',
'lost',
'm',
'map',
'menu',
'menu_order',
'merged_filters',
'mode',
'monthnum',
'more',
'multipage',
'names',
'nav_menu_selected_id',
'new_whitelist_options',
'numpages',
'one_theme_location_no_menus',
'opml',
'option_page',
'order',
'orderby',
'overridden_cpage',
'page',
'paged',
'pagenow',
'pages',
'parent_file',
'pass_allowed_html',
'pass_allowed_protocols',
'path',
'per_page',
'PHP_SELF',
'phpmailer',
'plugin_page',
'plugins',
'post',
'post_default_category',
'post_default_title',
'post_ID',
'post_id',
'post_mime_types',
'post_type',
'post_type_object',
'posts',
'preview',
'previouscat',
'previousday',
'previousweekday',
'redir_tab',
'required_mysql_version',
'required_php_version',
'rnd_value',
'role',
's',
'search',
'self',
'shortcode_tags',
'show_admin_bar',
'sidebars_widgets',
'status',
'submenu',
'submenu_file',
'super_admins',
'tab',
'table_prefix',
'tabs',
'tag',
'targets',
'tax',
'taxnow',
'taxonomy',
'term',
'text_direction',
'theme_field_defaults',
'themes_allowedtags',
'template',
'timeend',
'timestart',
'tinymce_version',
'title',
'totals',
'type',
'typenow',
'updated_timestamp',
'upgrading',
'urls',
'user_email',
'user_ID',
'user_id',
'user_identity',
'user_level',
'user_login',
'user_url',
'userdata',
'usersearch',
'whitelist_options',
'withcomments',
'wp',
'wp_actions',
'wp_admin_bar',
'wp_cockneyreplace',
'wp_current_db_version',
'wp_current_filter',
'wp_customize',
'wp_dashboard_control_callbacks',
'wp_db_version',
'wp_did_header',
'wp_embed',
'wp_file_descriptions',
'wp_filesystem',
'wp_filter',
'wp_hasher',
'wp_header_to_desc',
'wp_http_referer',
'wp_importers',
'wp_json',
'wp_list_table',
'wp_local_package',
'wp_locale',
'wp_meta_boxes',
'wp_object_cache',
'wp_plugin_paths',
'wp_post_statuses',
'wp_post_types',
'wp_queries',
'wp_query',
'wp_registered_sidebars',
'wp_registered_widget_controls',
'wp_registered_widget_updates',
'wp_registered_widgets',
'wp_rewrite',
'wp_rich_edit',
'wp_rich_edit_exists',
'wp_roles',
'wp_scripts',
'wp_settings_errors',
'wp_settings_fields',
'wp_settings_sections',
'wp_smiliessearch',
'wp_styles',
'wp_taxonomies',
'wp_the_query',
'wp_theme_directories',
'wp_themes',
'wp_user_roles',
'wp_version',
'wp_widget_factory',
'wp_xmlrpc_server',
'wpcommentsjavascript',
'wpcommentspopupfile',
'wpdb',
'wpsmiliestrans',
'year',
];
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Loader/LazyServiceInstantiator.php | src/Loader/LazyServiceInstantiator.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Loader;
use Sword\SwordBundle\Store\WordpressWidgetStore;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
final class LazyServiceInstantiator
{
public function __construct(
private readonly WordpressWidgetStore $widgetsStore,
#[Autowire('%kernel.project_dir%')] private readonly string $projectDirectory,
) {
}
public function requireAll(): void
{
foreach ($this->widgetsStore->getWidgets() as $widget) {
$this->load($widget);
add_action('widgets_init', static fn () => register_widget($widget));
}
}
private function load(string $class): void
{
$prefix = 'App\\';
$baseDir = $this->projectDirectory . '/src/';
$length = \strlen($prefix);
if (strncmp($prefix, $class, $length) !== 0) {
return;
}
$relativeClass = substr($class, $length);
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Attribute/AsWordpressCommand.php | src/Attribute/AsWordpressCommand.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Attribute;
use Symfony\Component\Console\Attribute\AsCommand;
#[\Attribute(\Attribute::TARGET_CLASS)]
final class AsWordpressCommand extends AsCommand
{
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Widget/DefineWidgetTrait.php | src/Widget/DefineWidgetTrait.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Widget;
trait DefineWidgetTrait
{
private function defineWidget(
string $id,
string $name,
string $description,
string $cssClass,
array $fields,
): void {
$this->widget_id = $id;
$this->widget_name = $name;
$this->widget_description = $description;
$this->widget_cssclass = $cssClass;
$this->settings = $fields;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Store/WordpressWidgetStore.php | src/Store/WordpressWidgetStore.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Store;
final class WordpressWidgetStore
{
private array $widgets = [];
public function getWidgets(): array
{
return $this->widgets;
}
public function addWidget(string $widget): void
{
$this->widgets[$widget] = $widget;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/EnvVarProcessor/AutoFileEnvVarProcessor.php | src/EnvVarProcessor/AutoFileEnvVarProcessor.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\EnvVarProcessor;
use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
final class AutoFileEnvVarProcessor implements EnvVarProcessorInterface
{
public function getEnv(string $prefix, string $name, \Closure $getEnv): string|array|bool|null
{
if ($fileEnv = getenv($name . '_FILE')) {
return rtrim(file_get_contents($fileEnv), "\r\n");
}
if (($val = getenv($name)) !== false) {
return $val;
}
return null;
}
public static function getProvidedTypes(): array
{
return [
'auto_file' => 'string',
];
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/EventListener/WordpressTablePrefixEventListener.php | src/EventListener/WordpressTablePrefixEventListener.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\EventListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Sword\SwordBundle\Entity\WordpressEntityInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
#[AsDoctrineListener(event: Events::loadClassMetadata)]
final class WordpressTablePrefixEventListener
{
public function __construct(
#[Autowire('%sword.table_prefix%')] private readonly string $prefix
) {
}
public function loadClassMetadata(LoadClassMetadataEventArgs $args): void
{
$classMetadata = $args->getClassMetadata();
if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) {
return;
}
if (
$classMetadata->getReflectionClass()
&& $classMetadata->getReflectionClass()
->implementsInterface(WordpressEntityInterface::class)
) {
$classMetadata->setPrimaryTable([
'name' => $this->prefix . $classMetadata->getTableName()
]);
foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
if ($mapping['type'] === ClassMetadataInfo::MANY_TO_MANY) {
$mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
$classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
}
}
}
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/EventListener/WordpressLoggedInStatusCheckEventSubscriber.php | src/EventListener/WordpressLoggedInStatusCheckEventSubscriber.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\EventListener;
use Sword\SwordBundle\Controller\Routes;
use Sword\SwordBundle\Loader\WordpressLoader;
use Sword\SwordBundle\Security\UserReauthenticator;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class WordpressLoggedInStatusCheckEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly WordpressLoader $wordpressLoader,
private readonly UserReauthenticator $userReauthenticator,
#[Autowire('%sword.app_namespace%')]
private readonly string $appNamespace,
#[Autowire('%sword.wordpress_host%')]
private readonly string $wordpressHost,
) {
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'checkWordpressLoggedInStatus',
];
}
public function checkWordpressLoggedInStatus(RequestEvent $event): void
{
$controller = $event->getRequest()
->attributes->get('_controller');
if (
!(str_starts_with($controller, 'Sword\\SwordBundle\\') || str_starts_with($controller, $this->appNamespace))
|| $event->getRequest()
->attributes->get('_route') === Routes::REAUTHENTICATE
|| $this->tokenStorage->getToken()?->getUser()
) {
return;
}
$host = $this->wordpressHost ?: $event->getRequest()
->getSchemeAndHttpHost();
$cookieName = 'wordpress_logged_in_' . md5($host);
if (\array_key_exists($cookieName, $event->getRequest()->cookies->all())) {
$this->wordpressLoader->loadWordpress();
if (!is_user_logged_in()) {
$response = new RedirectResponse($event->getRequest()->getRequestUri());
$response->headers->clearCookie($cookieName);
$event->setResponse($response);
return;
}
$this->userReauthenticator->reauthenticate();
if (str_starts_with($controller, 'Sword\\SwordBundle\\')) {
$event->setResponse(new RedirectResponse($host . $event->getRequest()->getRequestUri()));
}
}
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/EventListener/WordpressTerminateEventListener.php | src/EventListener/WordpressTerminateEventListener.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\EventListener;
use Sword\SwordBundle\Controller\Routes;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
final class WordpressTerminateEventListener implements EventSubscriberInterface
{
public function __construct(
private readonly EventDispatcherInterface $dispatcher
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onResponse', -2048],
];
}
public function onResponse(ResponseEvent $event): void
{
if ($event->getRequest()->attributes->get('_route') === Routes::WORDPRESS) {
$response = $event->getResponse();
$response->sendHeaders();
$response->sendContent();
$this->dispatcher->dispatch(
new TerminateEvent($event->getKernel(), $event->getRequest(), $response),
KernelEvents::TERMINATE,
);
Response::closeOutputBuffers(0, true);
// Trigger WordPress register_shutdown_function() callbacks
exit;
}
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/UserAuthenticator.php | src/Security/UserAuthenticator.php | <?php
namespace Sword\SwordBundle\Security;
use Psr\EventDispatcher\EventDispatcherInterface;
use Sword\SwordBundle\Controller\Routes;
use Sword\SwordBundle\Event\WooCommerceRegistrationEvent;
use Sword\SwordBundle\Exception\WordpressLoginSuccessfulException;
use Sword\SwordBundle\Exception\WordpressLougoutSuccessfulException;
use Sword\SwordBundle\Service\WordpressService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use WC_Session_Handler;
use Williarin\WordpressInterop\Bridge\Entity\Option;
use Williarin\WordpressInterop\Bridge\Entity\Page;
use Williarin\WordpressInterop\EntityManagerInterface;
use Williarin\WordpressInterop\Exception\OptionNotFoundException;
use WP_User;
class UserAuthenticator extends AbstractLoginFormAuthenticator implements WordpressService
{
private ?string $wordpressUsername = null;
private ?string $wordpressPassword = null;
private bool $wordpressRememberMe = false;
private ?string $csrfToken = null;
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly RequestStack $requestStack,
private readonly TokenStorageInterface $tokenStorage,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly AuthorizationCheckerInterface $authorizationChecker,
private readonly UrlGeneratorInterface $urlGenerator,
) {
}
public function getPriority(): int
{
return 0;
}
public function initialize(): void
{
add_action('wp_login', [$this, 'onWordpressLogin'], 100, 2);
add_action('woocommerce_login_failed', [$this, 'onWooCommerceLoginTerminate'], -100);
add_action('wp_logout', [$this, 'onWordpressLogout'], -100);
add_action('woocommerce_created_customer', [$this, 'onWooCommerceRegister'], -100, 3);
add_filter('woocommerce_registration_auth_new_customer', '__return_false');
}
public function onWordpressLogin(string $username, WP_User $wordpressUser): void
{
$request = $this->requestStack->getCurrentRequest();
$this->wordpressUsername = $username;
$this->wordpressPassword = $request?->get('password', $request?->get('pwd', ''));
$this->wordpressRememberMe = (bool) $request?->get('rememberme');
$this->onWordpressLoginSuccess();
}
public function onWooCommerceLoginTerminate(): void
{
if (!$this->wordpressUsername || !$this->wordpressPassword) {
return;
}
$this->onWordpressLoginSuccess();
}
public function onWordpressLogout(): void
{
if (!$this->authorizationChecker->isGranted('ROLE_USER')) {
return;
}
if (class_exists('WC_Session_Handler')) {
$woocommerceSession = apply_filters('woocommerce_session_handler', 'WC_Session_Handler');
if ($woocommerceSession instanceof WC_Session_Handler) {
$woocommerceSession->destroy_session();
}
}
$logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
$this->eventDispatcher->dispatch($logoutEvent);
$response = $logoutEvent->getResponse();
if (!$response instanceof Response) {
$response = new RedirectResponse($this->urlGenerator->generate(Routes::WORDPRESS, [
'path' => ''
]));
}
$this->tokenStorage->setToken();
$this->requestStack->getSession()
->invalidate();
throw new WordpressLougoutSuccessfulException($response);
}
public function onWooCommerceRegister(int $customerId, array $newCustomerData, bool $passwordGenerated): void
{
$this->eventDispatcher->dispatch(new WooCommerceRegistrationEvent($customerId, $newCustomerData));
}
public function supports(Request $request): bool
{
$data = $this->requestStack->getSession()
->getFlashBag()
->get('wp_login');
if (!empty($data)) {
[$this->wordpressUsername, $this->wordpressPassword, $this->wordpressRememberMe, $this->csrfToken] = $data;
}
return $this->wordpressUsername && $this->wordpressPassword && \in_array(
$request->getPathInfo(),
[$this->getLoginUrl($request), '/wp-login.php'],
true,
);
}
public function start(Request $request, AuthenticationException $authException = null): RedirectResponse
{
$url = '/wp-login.php?' . http_build_query([
'redirect_to' => $request->getUri(),
'reauth' => 0,
]);
return new RedirectResponse($url, 302);
}
public function getLoginUrl(Request $request): string
{
try {
$myAccountId = (int) $this->entityManager->getRepository(Option::class)
->find('woocommerce_myaccount_page_id');
return sprintf(
'/%s/',
$this->entityManager->getRepository(Page::class)
->find($myAccountId)
->postName,
);
} catch (OptionNotFoundException) {
return '/wp-login.php';
}
}
public function authenticate(Request $request): Passport
{
$badges = [new CsrfTokenBadge('authenticate', $this->csrfToken)];
if ($this->wordpressRememberMe) {
$badges[] = new RememberMeBadge();
}
return new Passport(
new UserBadge($this->wordpressUsername),
new PasswordCredentials($this->wordpressPassword),
$badges,
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$redirectPath = $this->getRedirectPath($request);
if ($request->getPathInfo() === '/wp-login.php') {
if ($redirectPath) {
return new RedirectResponse($redirectPath);
}
return new RedirectResponse($this->urlGenerator->generate(Routes::WORDPRESS, [
'path' => ''
]));
}
return $redirectPath
? new RedirectResponse($redirectPath)
: null;
}
private function getRedirectPath(Request $request): ?string
{
$referer = $request->headers->get('referer');
if ($referer && ($queryString = parse_url($referer, PHP_URL_QUERY))) {
parse_str($queryString, $result);
if (!empty($result['redirect_to'])) {
return $result['redirect_to'];
}
}
return null;
}
private function onWordpressLoginSuccess(): never
{
throw new WordpressLoginSuccessfulException(
$this->wordpressUsername,
$this->wordpressPassword,
$this->wordpressRememberMe,
);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/User.php | src/Security/User.php | <?php
namespace Sword\SwordBundle\Security;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Sword\SwordBundle\Entity\WordpressEntityInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity]
#[ORM\Table('users')]
class User implements UserInterface, PasswordAuthenticatedUserInterface, WordpressEntityInterface, EquatableInterface
{
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
#[ORM\Column(name: 'ID', type: 'bigint', options: [
'unsigned' => true
])]
protected ?int $id = null;
#[ORM\Column(name: 'user_login', type: 'string', length: 60)]
protected ?string $login = null;
#[ORM\Column(name: 'user_pass', type: 'string', length: 255)]
protected ?string $pass = null;
#[ORM\Column(name: 'user_nicename', type: 'string', length: 50)]
protected ?string $nicename = null;
#[ORM\Column(name: 'user_email', type: 'string', length: 100)]
protected ?string $email = null;
#[ORM\Column(name: 'user_url', type: 'string', length: 100)]
protected ?string $url = null;
#[ORM\Column(name: 'user_registered', type: 'datetime')]
protected ?DateTime $registered;
#[ORM\Column(name: 'user_activation_key', type: 'string', length: 255)]
protected ?string $activationKey = null;
#[ORM\Column(name: 'user_status', type: 'integer')]
protected ?int $status = null;
#[ORM\Column(name: 'display_name', type: 'string', length: 250)]
protected ?string $displayName = null;
protected ArrayCollection $metas;
private array $roles = [];
private array $capabilities = [];
public function __construct()
{
$this->registered = new DateTime('1970-01-01 00:00:00');
$this->metas = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLogin(): ?string
{
return $this->login;
}
public function setLogin(string $login): self
{
$this->login = $login;
return $this;
}
public function getPass(): ?string
{
return $this->pass;
}
public function setPass(?string $pass): self
{
$this->pass = $pass;
return $this;
}
public function getNicename(): ?string
{
return $this->nicename;
}
public function setNicename(?string $nicename): self
{
$this->nicename = $nicename;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(?string $url): self
{
$this->url = $url;
return $this;
}
public function getRegistered(): ?DateTime
{
return $this->registered;
}
public function setRegistered(?DateTime $registered): self
{
$this->registered = $registered;
return $this;
}
public function getActivationKey(): ?string
{
return $this->activationKey;
}
public function setActivationKey(?string $activationKey): self
{
$this->activationKey = $activationKey;
return $this;
}
public function getStatus(): ?int
{
return $this->status;
}
public function setStatus(?int $status): self
{
$this->status = $status;
return $this;
}
public function getDisplayName(): ?string
{
return $this->displayName;
}
public function setDisplayName(?string $displayName): self
{
$this->displayName = $displayName;
return $this;
}
public function getMetas(): ArrayCollection
{
return $this->metas;
}
public function setMetas(ArrayCollection $metas): self
{
$this->metas = $metas;
return $this;
}
public function getUserIdentifier(): string
{
return (string) $this->login;
}
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function getCapabilities(): array
{
$capabilities = $this->capabilities;
return array_unique($capabilities);
}
public function setCapabilities(array $capabilities): self
{
$this->capabilities = $capabilities;
return $this;
}
public function eraseCredentials(): void
{
}
public function getPassword(): ?string
{
return $this->getPass();
}
public function isEqualTo(UserInterface $user): bool
{
if ($user instanceof self) {
$isEqual =
\count($this->getRoles()) === \count($user->getRoles())
&& \count($this->getCapabilities()) === \count($user->getCapabilities())
;
if ($isEqual) {
foreach ($this->getRoles() as $role) {
$isEqual = $isEqual && \in_array($role, $user->getRoles(), true);
}
foreach ($this->getCapabilities() as $capability) {
$isEqual = $isEqual && \in_array($capability, $user->getCapabilities(), true);
}
}
return $isEqual;
}
return false;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/UserReauthenticator.php | src/Security/UserReauthenticator.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
final class UserReauthenticator
{
public function __construct(
private readonly UserAuthenticator $authenticator,
private readonly UserCheckerInterface $userChecker,
private readonly UserProvider $userProvider,
private readonly RequestStack $requestStack,
#[Autowire(service: 'security.authenticator.managers_locator')]
private readonly ServiceLocator $managersLocator,
) {
}
public function reauthenticate(): bool
{
if (!is_user_logged_in()) {
return false;
}
$user = $this->userProvider->loadUserByIdentifier(wp_get_current_user()->user_login);
$this->userChecker->checkPreAuth($user);
$this->managersLocator->get('main')
->authenticateUser($user, $this->authenticator, $this->requestStack->getMainRequest());
return true;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/UserProvider.php | src/Security/UserProvider.php | <?php
namespace Sword\SwordBundle\Security;
use Doctrine\ORM\EntityManagerInterface as DoctrineEntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Williarin\WordpressInterop\Bridge\Entity\Option;
use Williarin\WordpressInterop\Bridge\Entity\User as InteropUser;
use Williarin\WordpressInterop\Criteria\SelectColumns;
use Williarin\WordpressInterop\EntityManagerInterface as InteropEntityManagerInterface;
class UserProvider implements UserProviderInterface
{
public function __construct(
private readonly DoctrineEntityManagerInterface $doctrine,
private readonly InteropEntityManagerInterface $interop,
#[Autowire('%sword.table_prefix%')] private readonly string $tablePrefix,
) {
}
public function loadUserByIdentifier($identifier): UserInterface
{
$user = $this->doctrine->getRepository(User::class)
->findOneBy([
'login' => $identifier
]);
$userInterop = $this->interop->getRepository(InteropUser::class)
->findOneBy([
new SelectColumns(['id', 'capabilities']),
'user_login' => $identifier,
]);
$wordpressRoles = $this->interop->getRepository(Option::class)
->find($this->tablePrefix . 'user_roles');
$userRoles = [];
$userCapabilities = [];
foreach (array_keys($userInterop->capabilities->data, true) as $capability) {
if (\array_key_exists($capability, $wordpressRoles)) {
$userRoles[] = $capability;
$userCapabilities = [...$userCapabilities, ...array_keys(
$wordpressRoles[$capability]['capabilities'],
true,
)];
} else {
$userCapabilities[] = $capability;
}
}
$user->setRoles($userRoles);
$user->setCapabilities($userCapabilities);
return $user;
}
public function refreshUser(UserInterface $user): UserInterface
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Invalid user class "%s".', \get_class($user)));
}
return $this->loadUserByIdentifier($user->getUserIdentifier());
}
public function supportsClass(string $class): bool
{
return $class === User::class || is_subclass_of($class, User::class);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/Voter/CapabilityVoter.php | src/Security/Voter/CapabilityVoter.php | <?php
namespace Sword\SwordBundle\Security\Voter;
use Sword\SwordBundle\Security\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
final class CapabilityVoter implements VoterInterface
{
public function vote(TokenInterface $token, $subject, array $attributes): int
{
$result = self::ACCESS_ABSTAIN;
/** @var User $user */
$user = $token->getUser() instanceof User ? $token->getUser() : null;
if (!$user instanceof User) {
return $result;
}
foreach ($attributes as $attribute) {
$result = self::ACCESS_DENIED;
if (\in_array($attribute, $user->getCapabilities(), true)) {
return self::ACCESS_GRANTED;
}
}
return $result;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Security/Voter/RoleVoter.php | src/Security/Voter/RoleVoter.php | <?php
namespace Sword\SwordBundle\Security\Voter;
use Sword\SwordBundle\Security\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
final class RoleVoter implements VoterInterface
{
public function __construct(
private readonly RoleHierarchyInterface $roleHierarchy
) {
}
public function vote(TokenInterface $token, $subject, array $attributes): int
{
$result = VoterInterface::ACCESS_ABSTAIN;
/** @var User $user */
$user = $token->getUser() instanceof User ? $token->getUser() : null;
if (!$user instanceof User) {
return $result;
}
foreach ($attributes as $attribute) {
$result = VoterInterface::ACCESS_DENIED;
if (\in_array($attribute, $this->roleHierarchy->getReachableRoleNames($user->getRoles()), true)) {
return VoterInterface::ACCESS_GRANTED;
}
}
return $result;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Service/AbstractWordpressService.php | src/Service/AbstractWordpressService.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Service;
abstract class AbstractWordpressService implements WordpressService
{
public function getPriority(): int
{
return 0;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Service/WordpressService.php | src/Service/WordpressService.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Service;
interface WordpressService
{
/**
* Priority given to the service for its initialization. Higher number means higher priority. Defaults to 0.
*/
public function getPriority(): int;
public function initialize(): void;
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Command/WordpressCommand.php | src/Command/WordpressCommand.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Command;
use Sword\SwordBundle\Attribute\AsWordpressCommand;
use Sword\SwordBundle\Service\WordpressService;
use WP_CLI;
use WP_CLI_Command;
abstract class WordpressCommand extends WP_CLI_Command implements WordpressService
{
abstract public function __invoke(array $arguments, array $options);
public function getPriority(): int
{
return 0;
}
public function initialize(): void
{
if (!(\defined('WP_CLI') && WP_CLI)) {
return;
}
WP_CLI::add_command(static::getDefaultName(), static::class);
}
public static function getDefaultName(): ?string
{
$class = static::class;
if ($attribute = (new \ReflectionClass($class))->getAttributes(AsWordpressCommand::class)) {
return $attribute[0]->newInstance()->name;
}
return null;
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/src/Command/WpCommand.php | src/Command/WpCommand.php | <?php
namespace Sword\SwordBundle\Command;
use Sword\SwordBundle\Loader\WordpressGlobals;
use Sword\SwordBundle\Loader\WordpressLoader;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use WP_CLI\Bootstrap\BootstrapStep;
use WP_CLI\Bootstrap\ConfigureRunner;
use WP_CLI\Bootstrap\DeclareAbstractBaseCommand;
use WP_CLI\Bootstrap\DeclareMainClass;
use WP_CLI\Bootstrap\DefineProtectedCommands;
use WP_CLI\Bootstrap\IncludeFallbackAutoloader;
use WP_CLI\Bootstrap\IncludeFrameworkAutoloader;
use WP_CLI\Bootstrap\IncludePackageAutoloader;
use WP_CLI\Bootstrap\InitializeColorization;
use WP_CLI\Bootstrap\InitializeContexts;
use WP_CLI\Bootstrap\InitializeLogger;
use WP_CLI\Bootstrap\LaunchRunner;
use WP_CLI\Bootstrap\LoadExecCommand;
use WP_CLI\Bootstrap\LoadRequiredCommand;
use WP_CLI\Bootstrap\RegisterDeferredCommands;
use WP_CLI\Bootstrap\RegisterFrameworkCommands;
#[AsCommand(name: 'wp', description: 'Run wp-cli commands',)]
class WpCommand extends Command
{
public function __construct(
private readonly WordpressLoader $wordpressLoader,
#[Autowire('%sword.wordpress_core_dir%')] private readonly string $wordpressDirectory,
) {
parent::__construct();
}
protected function configure(): void
{
$this->ignoreValidationErrors();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
global $wordpressLoader, $argv, $argc, $wpCliBootstrapState;
$wordpressLoader = $this->wordpressLoader;
foreach (WordpressGlobals::GLOBALS as $global) {
global $$global;
}
$argv = \array_slice($argv, 1, $argc - 1);
$argv[] = sprintf('--path=%s', $this->wordpressDirectory);
$argv = array_unique($argv);
$argc = \count($argv);
foreach ($this->getBootstrapStates() as $step) {
/** @var BootstrapStep $stepInstance */
$stepInstance = new $step();
$wpCliBootstrapState = $stepInstance->process($wpCliBootstrapState);
}
return Command::SUCCESS;
}
private function getBootstrapStates(): array
{
return [
DeclareMainClass::class,
DeclareAbstractBaseCommand::class,
IncludeFrameworkAutoloader::class,
ConfigureRunner::class,
InitializeColorization::class,
InitializeLogger::class,
DefineProtectedCommands::class,
LoadExecCommand::class,
LoadRequiredCommand::class,
IncludePackageAutoloader::class,
IncludeFallbackAutoloader::class,
RegisterFrameworkCommands::class,
RegisterDeferredCommands::class,
InitializeContexts::class,
LaunchRunner::class,
];
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/WordpressTestCase.php | tests/WordpressTestCase.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test;
use PHPUnit\Framework\TestCase;
use function Brain\Monkey\setUp;
use function Brain\Monkey\tearDown;
abstract class WordpressTestCase extends TestCase
{
protected function setUp(): void
{
setUp();
}
protected function tearDown(): void
{
tearDown();
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/bootstrap.php | tests/bootstrap.php | <?php
declare(strict_types=1);
require dirname(__DIR__).'/vendor/autoload.php';
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Translation/ChildThemeTranslationInitializerTest.php | tests/Translation/ChildThemeTranslationInitializerTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Translation;
use Sword\SwordBundle\Test\WordpressTestCase;
use Sword\SwordBundle\Translation\ChildThemeTranslationInitializer;
use function Brain\Monkey\Functions\expect;
class ChildThemeTranslationInitializerTest extends WordpressTestCase
{
private readonly ChildThemeTranslationInitializer $service;
protected function setUp(): void
{
parent::setUp();
$this->service = new ChildThemeTranslationInitializer('foo');
}
public function testInitialize(): void
{
$this->service->initialize();
$this->assertSame(10, has_action(
'after_setup_theme',
ChildThemeTranslationInitializer::class . '->loadThemeLanguage()',
));
}
public function testGetLanguagesPath(): void
{
expect('get_stylesheet_directory')->once()->andReturn('wp/content/theme/mychildtheme');
$this->assertSame('wp/content/theme/mychildtheme/languages', $this->service->getLanguagesPath());
}
public function testLoadThemeLanguage(): void
{
expect('get_stylesheet_directory')->once()->andReturn('wp/content/theme/mychildtheme');
expect('load_child_theme_textdomain')
->once()
->with('foo', 'wp/content/theme/mychildtheme/languages')
->andReturn();
$this->service->loadThemeLanguage();
$this->assertTrue(true);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Translation/LocaleSwitcherTest.php | tests/Translation/LocaleSwitcherTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Translation;
use Sword\SwordBundle\Test\WordpressTestCase;
use Sword\SwordBundle\Translation\LocaleSwitcher;
use Symfony\Component\Translation\LocaleSwitcher as SymfonyLocaleSwitcher;
use function Brain\Monkey\Functions\expect;
class LocaleSwitcherTest extends WordpressTestCase
{
private readonly SymfonyLocaleSwitcher $symfonyLocaleSwitcher;
private readonly LocaleSwitcher $localeSwitcher;
protected function setUp(): void
{
parent::setUp();
$this->symfonyLocaleSwitcher = new SymfonyLocaleSwitcher('en', []);
$this->localeSwitcher = new LocaleSwitcher($this->symfonyLocaleSwitcher);
}
public function testInitialize(): void
{
$this->assertEquals('en', $this->symfonyLocaleSwitcher->getLocale());
expect('get_locale')->once()->withNoArgs()->andReturn('fr_FR');
$this->localeSwitcher->initialize();
$this->assertEquals('fr_FR', $this->symfonyLocaleSwitcher->getLocale());
}
public function testGetPriority(): void
{
$this->assertSame(1000, $this->localeSwitcher->getPriority());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/DependencyInjection/SwordExtensionTest.php | tests/DependencyInjection/SwordExtensionTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\DependencyInjection;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
use PHPUnit\Framework\TestCase;
use Sword\SwordBundle\DependencyInjection\SwordExtension;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Yaml\Yaml;
use Williarin\WordpressInteropBundle\DependencyInjection\WilliarinWordpressInteropExtension;
class SwordExtensionTest extends TestCase
{
private ContainerBuilder $container;
protected function setUp(): void
{
$extensions = [
'framework' => new FrameworkExtension(),
'security' => new SecurityExtension(),
'doctrine' => new DoctrineExtension(),
'wordpress_interop' => new WilliarinWordpressInteropExtension(),
'sword' => new SwordExtension(),
];
$container = new ContainerBuilder();
$container->registerExtension($extensions['framework']);
$container->registerExtension($extensions['security']);
$container->registerExtension($extensions['doctrine']);
$container->registerExtension($extensions['wordpress_interop']);
$container->registerExtension($extensions['sword']);
$container->setParameter('kernel.debug', true);
$this->container = $container;
}
public function testSecurityIsOverriddenBySword(): void
{
$this->loadSwordExtensionWithConfig('app.yaml');
$this->assertSame([
'customer' => 'ROLE_USER',
'subscriber' => 'customer',
'contributor' => 'subscriber',
'author' => 'contributor',
'editor' => 'author',
'shop_manager' => 'editor',
'administrator' => 'shop_manager',
'ROLE_SUPER_ADMIN' => [
'administrator',
'ROLE_ALLOWED_TO_SWITCH',
],
], $this->container->getExtensionConfig('security')[0]['role_hierarchy']);
}
public function testSecurityIsOverriddenByApp(): void
{
$this->loadSwordExtensionWithConfig('app2.yaml');
$this->assertSame([
'customer' => 'ROLE_ADMIN',
'subscriber' => 'customer',
'contributor' => 'subscriber',
'author' => 'contributor',
'editor' => 'author',
'shop_manager' => 'editor',
'administrator' => 'shop_manager',
'ROLE_SUPER_ADMIN' => [
'administrator',
'ROLE_ALLOWED_TO_SWITCH',
],
], $this->container->getExtensionConfig('security')[0]['role_hierarchy']);
}
public function testDoctrineIsOverriddenBySword(): void
{
$this->loadSwordExtensionWithConfig('app.yaml');
$this->assertSame([
'url' => null,
'dbname' => '%env(auto_file:WORDPRESS_DB_NAME)%',
'host' => '%env(auto_file:WORDPRESS_DB_HOST)%',
'user' => '%env(auto_file:WORDPRESS_DB_USER)%',
'password' => '%env(auto_file:WORDPRESS_DB_PASSWORD)%',
'charset' => '%env(auto_file:WORDPRESS_DB_CHARSET)%',
'driver' => 'mysqli',
'server_version' => '8.0',
], $this->container->getExtensionConfig('doctrine')[0]['dbal']);
}
public function testDefaultConnectionExistsWithMultipleDoctrineConnections(): void
{
$this->loadSwordExtensionWithConfig('app2.yaml');
$this->assertSame([
'default_connection' => 'default',
'connections' => [
'default' => [
'dbname' => '%env(auto_file:WORDPRESS_DB_NAME)%',
'host' => '%env(auto_file:WORDPRESS_DB_HOST)%',
'user' => '%env(auto_file:WORDPRESS_DB_USER)%',
'password' => '%env(auto_file:WORDPRESS_DB_PASSWORD)%',
'charset' => '%env(auto_file:WORDPRESS_DB_CHARSET)%',
'driver' => 'mysqli',
'server_version' => '8.0',
'url' => null,
],
'another' => [
'url' => '%env(DATABASE_URL)%',
],
],
], $this->container->getExtensionConfig('doctrine')[0]['dbal']);
}
public function testDefaultConnectionCanBeOverriddenByApp(): void
{
$this->loadSwordExtensionWithConfig('app3.yaml');
$this->assertSame([
'default_connection' => 'default',
'connections' => [
'default' => [
'url' => '%env(DATABASE_URL)%',
],
'another' => [
'url' => '%env(DATABASE_URL)%',
],
],
], $this->container->getExtensionConfig('doctrine')[0]['dbal']);
}
public function testDoctrineIsOverriddenByApp(): void
{
$this->loadSwordExtensionWithConfig('app4.yaml');
$this->assertSame([
'dbname' => 'newname',
'host' => 'newhost',
'user' => '%env(auto_file:WORDPRESS_DB_USER)%',
'password' => '%env(auto_file:WORDPRESS_DB_PASSWORD)%',
'charset' => '%env(auto_file:WORDPRESS_DB_CHARSET)%',
'driver' => 'mysqli',
'server_version' => '8.0',
'url' => null,
], $this->container->getExtensionConfig('doctrine')[0]['dbal']);
}
private function loadSwordExtensionWithConfig(string $file): void
{
$loader = new YamlFileLoader($this->container, new FileLocator(__DIR__ . '/../config'));
$loader->load($file);
$config = Yaml::parseFile(__DIR__ . "/../config/$file");
$this->container->getExtension('sword')->prepend($this->container);
$this->container->getExtension('sword')->load([$config['sword']], $this->container);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Loader/LazyServiceInstantiatorTest.php | tests/Loader/LazyServiceInstantiatorTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Loader;
use Mockery;
use Sword\SwordBundle\Loader\LazyServiceInstantiator;
use Sword\SwordBundle\Store\WordpressWidgetStore;
use Sword\SwordBundle\Test\WordpressTestCase;
use function Brain\Monkey\Actions\expectAdded;
class LazyServiceInstantiatorTest extends WordpressTestCase
{
public function testRequireAll(): void
{
$store = new WordpressWidgetStore();
$store->addWidget('Some\\Widget');
$store->addWidget('Some\\OtherWidget');
$instantiator = new LazyServiceInstantiator($store, __DIR__);
expectAdded('widgets_init')->twice()->with(Mockery::type('Closure'));
$instantiator->requireAll();
$this->assertTrue(true);
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Store/WordpressWidgetStoreTest.php | tests/Store/WordpressWidgetStoreTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Store;
use Sword\SwordBundle\Store\WordpressWidgetStore;
use PHPUnit\Framework\TestCase;
class WordpressWidgetStoreTest extends TestCase
{
public function testAddingWidgets(): void
{
$widgets = ['Some\\Widget', 'Some\\OtherWidget'];
$store = new WordpressWidgetStore();
$store->addWidget($widgets[0]);
$store->addWidget($widgets[1]);
$this->assertSame(array_combine($widgets, $widgets), $store->getWidgets());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/EnvVarProcessor/AutoFileEnvVarProcessorTest.php | tests/EnvVarProcessor/AutoFileEnvVarProcessorTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\EnvVarProcessor;
use PHPUnit\Framework\TestCase;
use Sword\SwordBundle\EnvVarProcessor\AutoFileEnvVarProcessor;
class AutoFileEnvVarProcessorTest extends TestCase
{
private const ENV_VAR_FILE = __DIR__ . '/../../var/test/env_var.test';
protected function setUp(): void
{
if (!file_exists(dirname(self::ENV_VAR_FILE))) {
mkdir(dirname(self::ENV_VAR_FILE), 0755, true);
}
}
protected function tearDown(): void
{
putenv('FOO');
putenv('FOO_FILE');
if (file_exists(self::ENV_VAR_FILE)) {
unlink(self::ENV_VAR_FILE);
}
}
/**
* @dataProvider validValues
*/
public function testGetEnvFile($value, $expected): void
{
file_put_contents(self::ENV_VAR_FILE, $value);
putenv('FOO_FILE=' . self::ENV_VAR_FILE);
$processor = new AutoFileEnvVarProcessor();
$result = $processor->getEnv('auto_file', 'FOO', static fn () => null);
$this->assertSame((string) $expected, $result);
}
/**
* @dataProvider validValues
* @covers ::getEnv
*/
public function testGetEnvValue($value, $expected): void
{
putenv('FOO=' . $value);
$processor = new AutoFileEnvVarProcessor();
$result = $processor->getEnv('auto_file', 'FOO', static fn () => null);
$this->assertSame($expected, $result);
}
public function validValues(): array
{
return [
['some_value', 'some_value'],
['135', '135'],
['true', 'true'],
['', ''],
[false, ''],
];
}
/**
* @covers ::getProvidedTypes
*/
public function testGetProvidedTypes(): void
{
$this->assertSame(['auto_file' => 'string'], AutoFileEnvVarProcessor::getProvidedTypes());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Security/Voter/CapabilityVoterTest.php | tests/Security/Voter/CapabilityVoterTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Security\Voter;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Sword\SwordBundle\Security\User;
use Sword\SwordBundle\Security\Voter\CapabilityVoter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
class CapabilityVoterTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @dataProvider capabilities
*/
public function testVote(string $capability, int $expected): void
{
$user = Mockery::mock(User::class);
$user->shouldReceive('getCapabilities')
->once()
->andReturn([
'edit_posts',
'edit_pages',
'create_posts',
'delete_users',
'manage_options',
]);
$token = Mockery::mock(TokenInterface::class);
$token->shouldReceive('getUser')
->withNoArgs()
->twice()
->andReturn($user);
$voter = new CapabilityVoter();
$this->assertSame($expected, $voter->vote($token, null, [$capability]));
}
public function testVoteUnauthenticatedUser(): void
{
$token = Mockery::mock(TokenInterface::class);
$token->shouldReceive('getUser')
->withNoArgs()
->once()
->andReturn(null);
$voter = new CapabilityVoter();
$this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($token, null, ['edit_posts']));
}
public function capabilities(): array
{
return [
['edit_posts', VoterInterface::ACCESS_GRANTED],
['edit_pages', VoterInterface::ACCESS_GRANTED],
['create_posts', VoterInterface::ACCESS_GRANTED],
['delete_users', VoterInterface::ACCESS_GRANTED],
['manage_options', VoterInterface::ACCESS_GRANTED],
['edit_products', VoterInterface::ACCESS_DENIED],
['', VoterInterface::ACCESS_DENIED],
];
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/tests/Service/AbstractWordpressServiceTest.php | tests/Service/AbstractWordpressServiceTest.php | <?php
declare(strict_types=1);
namespace Sword\SwordBundle\Test\Service;
use Sword\SwordBundle\Service\AbstractWordpressService;
use PHPUnit\Framework\TestCase;
class AbstractWordpressServiceTest extends TestCase
{
public function testGetPriority(): void
{
$this->assertSame(0, (new class extends AbstractWordpressService {
public function initialize(): void
{
}
})->getPriority());
}
}
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
phpsword/sword-bundle | https://github.com/phpsword/sword-bundle/blob/29d8e4c86dd9b873cf70051af234b6b3e3a27f52/install/wp/wp-config.php | install/wp/wp-config.php | <?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// IMPORTANT: this file needs to stay in-sync with https://github.com/WordPress/WordPress/blob/master/wp-config-sample.php
// (it gets parsed by the upstream wizard in https://github.com/WordPress/WordPress/blob/f27cb65e1ef25d11b535695a660e7282b98eb742/wp-admin/setup-config.php#L356-L392)
// a helper function to lookup "env_FILE", "env", then fallback
if (!function_exists('getenv_docker')) {
function getenv_docker($env, $default) {
if ($fileEnv = getenv($env . '_FILE')) {
return rtrim(file_get_contents($fileEnv), "\r\n");
}
if (($val = getenv($env)) !== false) {
return $val;
}
return $default;
}
}
// ** Database settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', getenv_docker('WORDPRESS_DB_NAME', 'wordpress'));
/** MySQL database username */
define('DB_USER', getenv_docker('WORDPRESS_DB_USER', 'user'));
/** MySQL database password */
define('DB_PASSWORD', getenv_docker('WORDPRESS_DB_PASSWORD', 'password'));
/** MySQL hostname */
define('DB_HOST', getenv_docker('WORDPRESS_DB_HOST', 'mysql'));
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', getenv_docker('WORDPRESS_DB_CHARSET', 'utf8mb4'));
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', getenv_docker('WORDPRESS_DB_COLLATE', ''));
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define( 'AUTH_KEY', getenv_docker('WORDPRESS_AUTH_KEY', '-3{ZGi /i2u9Sfi2I?6z/4*>qEz?<;dqgKIodM@Tp(aO.%?Y;[X(Si{e{6??lhHI') );
define( 'SECURE_AUTH_KEY', getenv_docker('WORDPRESS_SECURE_AUTH_KEY', 'CgT Q9P13xC+96TQ?}kt|X&?+i6lg8hxyceDQd=+<[*?_>`jE[mfOD ?eEhYB(2v') );
define( 'LOGGED_IN_KEY', getenv_docker('WORDPRESS_LOGGED_IN_KEY', '-;7}G6-h-HcyvR.Gq-X91pVW{u|_gAUE]yTR0g Ayf.[.Kj+&pFtb=DOy$;#gk-%') );
define( 'NONCE_KEY', getenv_docker('WORDPRESS_NONCE_KEY', 'd+tg52@Q#@HyUodDL8U}+%HU|lIy|O>%-i!wBmTEVFve9y#)t2k}k#D-~i+cd4:g') );
define( 'AUTH_SALT', getenv_docker('WORDPRESS_AUTH_SALT', '(zG&d7g0.qgC3ttU/*=~k|8{]%w1O68LW=j+tkJ81YtikE#GW))G[|Z9/ <ctCKp') );
define( 'SECURE_AUTH_SALT', getenv_docker('WORDPRESS_SECURE_AUTH_SALT', '8u|{2q=F+m:{UwT8$Z|igmtqa*L)A9|i[{>d!F~)kc&dp>+WoLQrV9s?D|?CgMcz') );
define( 'LOGGED_IN_SALT', getenv_docker('WORDPRESS_LOGGED_IN_SALT', 'yq7w~y03EL|ctX-|kR}v$=[E?P+[zNf8IhP@}?3-FtNY^-t|;8-8R0@K6HR!sm7o') );
define( 'NONCE_SALT', getenv_docker('WORDPRESS_NONCE_SALT', '1{1G%>#~Va8TRt-TU;pi.v{@;P-+M%g}Ud!- 4eWl](=pw?|-Rym:jGtU9|/#@4t') );
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = getenv_docker('WORDPRESS_TABLE_PREFIX', 'wp_');
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', filter_var(getenv_docker('WORDPRESS_DEBUG', 'false'), FILTER_VALIDATE_BOOLEAN));
/* Add any custom values between this line and the "stop editing" line. */
define('WP_DEBUG_LOG', filter_var(getenv_docker('WORDPRESS_DEBUG_LOG', 'false'), FILTER_VALIDATE_BOOLEAN));
define('WP_DEBUG_DISPLAY', filter_var(getenv_docker('WORDPRESS_DEBUG_DISPLAY', 'false'), FILTER_VALIDATE_BOOLEAN));
define('WP_DISABLE_FATAL_ERROR_HANDLER', filter_var(getenv_docker('WORDPRESS_DISABLE_FATAL_ERROR_HANDLER', 'true'), FILTER_VALIDATE_BOOLEAN));
define('WP_REDIS_HOST', getenv_docker('WORDPRESS_REDIS_HOST', 'redis'));
define('WP_REDIS_PASSWORD', getenv_docker('WORDPRESS_REDIS_PASSWORD', 'password'));
define('WP_CACHE_KEY_SALT', getenv_docker('WORDPRESS_CACHE_KEY_SALT', 'R!0uA_0:DmiDAX|18owsU[{9f-]+}p`,;lGaU:}}f#T}f-K%#I>:?DvpPuv|_8Bl'));
define('DISABLE_WP_CRON', filter_var(getenv_docker('WORDPRESS_DISABLE_WP_CRON', 'true'), FILTER_VALIDATE_BOOLEAN));
/** WP-Optimize Cache */
define('WP_CACHE', filter_var(getenv_docker('WORDPRESS_CACHE', 'true'), FILTER_VALIDATE_BOOLEAN));
/** Automatic updates */
define('WP_HTTP_BLOCK_EXTERNAL', filter_var(getenv_docker('WORDPRESS_HTTP_BLOCK_EXTERNAL', 'false'), FILTER_VALIDATE_BOOLEAN));
define('WP_AUTO_UPDATE_CORE', filter_var(getenv_docker('WORDPRESS_AUTO_UPDATE_CORE', 'false'), FILTER_VALIDATE_BOOLEAN));
define('AUTOMATIC_UPDATER_DISABLED', filter_var(getenv_docker('WORDPRESS_AUTOMATIC_UPDATER_DISABLED', 'true'), FILTER_VALIDATE_BOOLEAN));
/** Move directories */
define('WP_CONTENT_DIR', __DIR__ . '/content');
define('WP_CONTENT_URL', getenv_docker('WORDPRESS_SITE_URL', 'https://localhost') . '/wp-content');
define('WP_PLUGIN_DIR', __DIR__ . '/content/plugins');
define('WP_PLUGIN_URL', getenv_docker('WORDPRESS_SITE_URL', 'https://localhost') . '/wp-content/plugins');
define('PLUGINDIR', __DIR__ . '/content/plugins');
/**
* Handle SSL reverse proxy
*/
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && str_contains($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https')) {
$_SERVER['HTTPS'] = 'on';
}
if ($configExtra = getenv_docker('WORDPRESS_CONFIG_EXTRA', '')) {
eval($configExtra);
}
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if (!defined('ABSPATH')) {
define('ABSPATH', __DIR__ . '/core/');
}
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
/** Handles additional stuff in global scope. */
require_once __DIR__ . '/../vendor/phpsword/sword-bundle/src/Loader/wp-load.php';
| php | MIT | 29d8e4c86dd9b873cf70051af234b6b3e3a27f52 | 2026-01-05T04:54:40.429142Z | false |
moonlandsoft/yii2-phpexcel | https://github.com/moonlandsoft/yii2-phpexcel/blob/ccf28ff8ce2c665a7769dd6516098b4a35c8c309/Excel.php | Excel.php | <?php
namespace moonland\phpexcel;
use yii\helpers\ArrayHelper;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\i18n\Formatter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
* Excel Widget for generate Excel File or for load Excel File.
*
* Usage
* -----
*
* Exporting data into an excel file.
*
* ~~~
*
* // export data only one worksheet.
*
* \moonland\phpexcel\Excel::widget([
* 'models' => $allModels,
* 'mode' => 'export', //default value as 'export'
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'headers' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* \moonland\phpexcel\Excel::export([
* 'models' => $allModels,
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'headers' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* // export data with multiple worksheet.
*
* \moonland\phpexcel\Excel::widget([
* 'isMultipleSheet' => true,
* 'models' => [
* 'sheet1' => $allModels1,
* 'sheet2' => $allModels2,
* 'sheet3' => $allModels3
* ],
* 'mode' => 'export', //default value as 'export'
* 'columns' => [
* 'sheet1' => ['column1','column2','column3'],
* 'sheet2' => ['column1','column2','column3'],
* 'sheet3' => ['column1','column2','column3']
* ],
* //without header working, because the header will be get label from attribute label.
* 'headers' => [
* 'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
* ],
* ]);
*
* \moonland\phpexcel\Excel::export([
* 'isMultipleSheet' => true,
* 'models' => [
* 'sheet1' => $allModels1,
* 'sheet2' => $allModels2,
* 'sheet3' => $allModels3
* ],
* 'columns' => [
* 'sheet1' => ['column1','column2','column3'],
* 'sheet2' => ['column1','column2','column3'],
* 'sheet3' => ['column1','column2','column3']
* ],
* //without header working, because the header will be get label from attribute label.
* 'headers' => [
* 'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* 'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
* ],
* ]);
*
* ~~~
*
* New Feature for exporting data, you can use this if you familiar yii gridview.
* That is same with gridview data column.
* Columns in array mode valid params are 'attribute', 'header', 'format', 'value', and footer (TODO).
* Columns in string mode valid layout are 'attribute:format:header:footer(TODO)'.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => Post::find()->all(),
* 'columns' => [
* 'author.name:text:Author Name',
* [
* 'attribute' => 'content',
* 'header' => 'Content Post',
* 'format' => 'text',
* 'value' => function($model) {
* return ExampleClass::removeText('example', $model->content);
* },
* ],
* 'like_it:text:Reader like this content',
* 'created_at:datetime',
* [
* 'attribute' => 'updated_at',
* 'format' => 'date',
* ],
* ],
* 'headers' => [
* 'created_at' => 'Date Created Content',
* ],
* ]);
*
* ~~~
*
*
* Import file excel and return into an array.
*
* ~~~
*
* $data = \moonland\phpexcel\Excel::import($fileName, $config); // $config is an optional
*
* $data = \moonland\phpexcel\Excel::widget([
* 'mode' => 'import',
* 'fileName' => $fileName,
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* $data = \moonland\phpexcel\Excel::import($fileName, [
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* // import data with multiple file.
*
* $data = \moonland\phpexcel\Excel::widget([
* 'mode' => 'import',
* 'fileName' => [
* 'file1' => $fileName1,
* 'file2' => $fileName2,
* 'file3' => $fileName3,
* ],
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* $data = \moonland\phpexcel\Excel::import([
* 'file1' => $fileName1,
* 'file2' => $fileName2,
* 'file3' => $fileName3,
* ], [
* 'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* 'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
* 'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
* ]);
*
* ~~~
*
* Result example from the code on the top :
*
* ~~~
*
* // only one sheet or specified sheet.
*
* Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2));
*
* // data with multiple worksheet
*
* Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));
*
* // data with multiple file and specified sheet or only one worksheet
*
* Array([file1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [file2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));
*
* // data with multiple file and multiple worksheet
*
* Array([file1] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))),
* [file2] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)),
* [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2),
* [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))));
*
* ~~~
*
* @property string $mode is an export mode or import mode. valid value are 'export' and 'import'
* @property boolean $isMultipleSheet for set the export excel with multiple sheet.
* @property array $properties for set property on the excel object.
* @property array $models Model object or DataProvider object with much data.
* @property array $columns to get the attributes from the model, this valid value only the exist attribute on the model.
* If this is not set, then all attribute of the model will be set as columns.
* @property array $headers to set the header column on first line. Set this if want to custom header.
* If not set, the header will get attributes label of model attributes.
* @property string|array $fileName is a name for file name to export or import. Multiple file name only use for import mode, not work if you use the export mode.
* @property string $savePath is a directory to save the file or you can blank this to set the file as attachment.
* @property string $format for excel to export. Valid value are 'Xls','Xlsx','Xml','Ods','Slk','Gnumeric','Csv', and 'Html'.
* @property boolean $setFirstTitle to set the title column on the first line. The columns will have a header on the first line.
* @property boolean $asAttachment to set the file excel to download mode.
* @property boolean $setFirstRecordAsKeys to set the first record on excel file to a keys of array per line.
* If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
* @property boolean $setIndexSheetByName to set the sheet index by sheet name or array result if the sheet not only one
* @property string $getOnlySheet is a sheet name to getting the data. This is only get the sheet with same name.
* @property array|Formatter $formatter the formatter used to format model attribute values into displayable texts.
* This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
* instance. If this property is not set, the "formatter" application component will be used.
*
* @author Moh Khoirul Anam <moh.khoirul.anaam@gmail.com>
* @copyright 2014
* @since 1
*/
class Excel extends \yii\base\Widget
{
// Border style
const BORDER_NONE = 'none';
const BORDER_DASHDOT = 'dashDot';
const BORDER_DASHDOTDOT = 'dashDotDot';
const BORDER_DASHED = 'dashed';
const BORDER_DOTTED = 'dotted';
const BORDER_DOUBLE = 'double';
const BORDER_HAIR = 'hair';
const BORDER_MEDIUM = 'medium';
const BORDER_MEDIUMDASHDOT = 'mediumDashDot';
const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot';
const BORDER_MEDIUMDASHED = 'mediumDashed';
const BORDER_SLANTDASHDOT = 'slantDashDot';
const BORDER_THICK = 'thick';
const BORDER_THIN = 'thin';
// Colors
const COLOR_BLACK = 'FF000000';
const COLOR_WHITE = 'FFFFFFFF';
const COLOR_RED = 'FFFF0000';
const COLOR_DARKRED = 'FF800000';
const COLOR_BLUE = 'FF0000FF';
const COLOR_DARKBLUE = 'FF000080';
const COLOR_GREEN = 'FF00FF00';
const COLOR_DARKGREEN = 'FF008000';
const COLOR_YELLOW = 'FFFFFF00';
const COLOR_DARKYELLOW = 'FF808000';
// Horizontal alignment styles
const HORIZONTAL_GENERAL = 'general';
const HORIZONTAL_LEFT = 'left';
const HORIZONTAL_RIGHT = 'right';
const HORIZONTAL_CENTER = 'center';
const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous';
const HORIZONTAL_JUSTIFY = 'justify';
const HORIZONTAL_FILL = 'fill';
const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only
// Vertical alignment styles
const VERTICAL_BOTTOM = 'bottom';
const VERTICAL_TOP = 'top';
const VERTICAL_CENTER = 'center';
const VERTICAL_JUSTIFY = 'justify';
const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only
// Read order
const READORDER_CONTEXT = 0;
const READORDER_LTR = 1;
const READORDER_RTL = 2;
// Fill types
const FILL_NONE = 'none';
const FILL_SOLID = 'solid';
const FILL_GRADIENT_LINEAR = 'linear';
const FILL_GRADIENT_PATH = 'path';
const FILL_PATTERN_DARKDOWN = 'darkDown';
const FILL_PATTERN_DARKGRAY = 'darkGray';
const FILL_PATTERN_DARKGRID = 'darkGrid';
const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal';
const FILL_PATTERN_DARKTRELLIS = 'darkTrellis';
const FILL_PATTERN_DARKUP = 'darkUp';
const FILL_PATTERN_DARKVERTICAL = 'darkVertical';
const FILL_PATTERN_GRAY0625 = 'gray0625';
const FILL_PATTERN_GRAY125 = 'gray125';
const FILL_PATTERN_LIGHTDOWN = 'lightDown';
const FILL_PATTERN_LIGHTGRAY = 'lightGray';
const FILL_PATTERN_LIGHTGRID = 'lightGrid';
const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal';
const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis';
const FILL_PATTERN_LIGHTUP = 'lightUp';
const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical';
const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
// Pre-defined formats
const FORMAT_GENERAL = 'General';
const FORMAT_TEXT = '@';
const FORMAT_NUMBER = '0';
const FORMAT_NUMBER_00 = '0.00';
const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
const FORMAT_PERCENTAGE = '0%';
const FORMAT_PERCENTAGE_00 = '0.00%';
const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';
const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd';
const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy';
const FORMAT_DATE_DMYSLASH = 'd/m/yy';
const FORMAT_DATE_DMYMINUS = 'd-m-yy';
const FORMAT_DATE_DMMINUS = 'd-m';
const FORMAT_DATE_MYMINUS = 'm-yy';
const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
const FORMAT_DATE_XLSX16 = 'd-mmm';
const FORMAT_DATE_XLSX17 = 'mmm-yy';
const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
const FORMAT_DATE_DATETIME = 'd/m/yy h:mm';
const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
const FORMAT_DATE_TIME3 = 'h:mm';
const FORMAT_DATE_TIME4 = 'h:mm:ss';
const FORMAT_DATE_TIME5 = 'mm:ss';
const FORMAT_DATE_TIME6 = 'h:mm:ss';
const FORMAT_DATE_TIME7 = 'i:s.S';
const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@';
const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-';
const FORMAT_CURRENCY_USD = '$#,##0_-';
const FORMAT_CURRENCY_EUR_SIMPLE = '#,##0.00_-"€"';
const FORMAT_CURRENCY_EUR = '#,##0_-"€"';
/**
* @var string mode is an export mode or import mode. valid value are 'export' and 'import'.
*/
public $mode = 'export';
/**
* @var boolean for set the export excel with multiple sheet.
*/
public $isMultipleSheet = false;
/**
* @var array properties for set property on the excel object.
*/
public $properties;
/**
* @var Model object or DataProvider object with much data.
*/
public $models;
/**
* @var array columns to get the attributes from the model, this valid value only the exist attribute on the model.
* If this is not set, then all attribute of the model will be set as columns.
*/
public $columns = [];
/**
* @var array header to set the header column on first line. Set this if want to custom header.
* If not set, the header will get attributes label of model attributes.
*/
public $headers = [];
/**
* @var string|array name for file name to export or save.
*/
public $fileName;
/**
* @var string save path is a directory to save the file or you can blank this to set the file as attachment.
*/
public $savePath;
/**
* @var string format for excel to export. Valid value are 'Xls','Xlsx','Xml','Ods','Slk','Gnumeric','Csv', and 'Html'.
*/
public $format;
/**
* @var boolean to set the title column on the first line.
*/
public $setFirstTitle = true;
/**
* @var boolean to set the file excel to download mode.
*/
public $asAttachment = false;
/**
* @var boolean to set the first record on excel file to a keys of array per line.
* If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
*/
public $setFirstRecordAsKeys = true;
/**
* @var boolean to set the sheet index by sheet name or array result if the sheet not only one.
*/
public $setIndexSheetByName = false;
/**
* @var string sheetname to getting. This is only get the sheet with same name.
*/
public $getOnlySheet;
/**
* @var boolean to set the import data will return as array.
*/
public $asArray;
/**
* @var array to unread record by index number.
*/
public $leaveRecordByIndex = [];
/**
* @var array to read record by index, other will leave.
*/
public $getOnlyRecordByIndex = [];
/**
* @var array|Formatter the formatter used to format model attribute values into displayable texts.
* This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
* instance. If this property is not set, the "formatter" application component will be used.
*/
public $formatter;
/**
* @var boolean define the column autosize
*/
public $autoSize = false;
/**
* @var boolean if true, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted.
*/
public $preCalculationFormula = false;
/**
* @var boolean Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation)
*/
public $compatibilityOffice2003 = false;
/**
* @var custom CSV delimiter for import. Works only with CSV files
*/
public $CSVDelimiter = ";";
/**
* @var custom CSV encoding for import. Works only with CSV files
*/
public $CSVEncoding = "UTF-8";
/**
* (non-PHPdoc)
* @see \yii\base\Object::init()
*/
public function init()
{
parent::init();
if ($this->formatter == null) {
$this->formatter = \Yii::$app->getFormatter();
} elseif (is_array($this->formatter)) {
$this->formatter = \Yii::createObject($this->formatter);
}
if (!$this->formatter instanceof Formatter) {
throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
}
}
/**
* Setting data from models
*/
public function executeColumns(&$activeSheet = null, $models, $columns = [], $headers = [])
{
if ($activeSheet == null) {
$activeSheet = $this->activeSheet;
}
$hasHeader = false;
$row = 1;
$char = 26;
foreach ($models as $model) {
if (empty($columns)) {
$columns = $model->attributes();
}
if ($this->setFirstTitle && !$hasHeader) {
$isPlus = false;
$colplus = 0;
$colnum = 1;
foreach ($columns as $key=>$column) {
$col = '';
if ($colnum > $char) {
$colplus += 1;
$colnum = 1;
$isPlus = true;
}
if ($isPlus) {
$col .= chr(64+$colplus);
}
$col .= chr(64+$colnum);
$header = '';
if (is_array($column)) {
if (isset($column['header'])) {
$header = $column['header'];
} elseif (isset($column['attribute']) && isset($headers[$column['attribute']])) {
$header = $headers[$column['attribute']];
} elseif (isset($column['attribute'])) {
$header = $model->getAttributeLabel($column['attribute']);
} elseif (isset($column['cellFormat']) && is_array($column['cellFormat'])) {
$activeSheet->getStyle($col.$row)->applyFromArray($column['cellFormat']);
}
} else {
if(isset($headers[$column])) {
$header = $headers[$column];
} else {
$header = $model->getAttributeLabel($column);
}
}
if (isset($column['width'])) {
$activeSheet->getColumnDimension(strtoupper($col))->setWidth($column['width']);
}
$activeSheet->setCellValue($col.$row,$header);
$colnum++;
}
$hasHeader=true;
$row++;
}
$isPlus = false;
$colplus = 0;
$colnum = 1;
foreach ($columns as $key=>$column) {
$col = '';
if ($colnum > $char) {
$colplus++;
$colnum = 1;
$isPlus = true;
}
if ($isPlus) {
$col .= chr(64+$colplus);
}
$col .= chr(64+$colnum);
if (is_array($column)) {
$column_value = $this->executeGetColumnData($model, $column);
if (isset($column['cellFormat']) && is_array($column['cellFormat'])) {
$activeSheet->getStyle($col.$row)->applyFromArray($column['cellFormat']);
}
} else {
$column_value = $this->executeGetColumnData($model, ['attribute' => $column]);
}
$activeSheet->setCellValue($col.$row,$column_value);
$colnum++;
}
$row++;
if($this->autoSize){
foreach (range(0, $colnum) as $col) {
$activeSheet->getColumnDimensionByColumn($col)->setAutoSize(true);
}
}
}
}
/**
* Setting label or keys on every record if setFirstRecordAsKeys is true.
* @param array $sheetData
* @return multitype:multitype:array
*/
public function executeArrayLabel($sheetData)
{
$keys = ArrayHelper::remove($sheetData, '1');
$new_data = [];
foreach ($sheetData as $values)
{
$new_data[] = array_combine($keys, $values);
}
return $new_data;
}
/**
* Leave record with same index number.
* @param array $sheetData
* @param array $index
* @return array
*/
public function executeLeaveRecords($sheetData = [], $index = [])
{
foreach ($sheetData as $key => $data)
{
if (in_array($key, $index))
{
unset($sheetData[$key]);
}
}
return $sheetData;
}
/**
* Read record with same index number.
* @param array $sheetData
* @param array $index
* @return array
*/
public function executeGetOnlyRecords($sheetData = [], $index = [])
{
foreach ($sheetData as $key => $data)
{
if (!in_array($key, $index))
{
unset($sheetData[$key]);
}
}
return $sheetData;
}
/**
* Getting column value.
* @param Model $model
* @param array $params
* @return Ambigous <NULL, string, mixed>
*/
public function executeGetColumnData($model, $params = [])
{
$value = null;
if (isset($params['value']) && $params['value'] !== null) {
if (is_string($params['value'])) {
$value = ArrayHelper::getValue($model, $params['value']);
} else {
$value = call_user_func($params['value'], $model, $this);
}
} elseif (isset($params['attribute']) && $params['attribute'] !== null) {
$value = ArrayHelper::getValue($model, $params['attribute']);
}
if (isset($params['format']) && $params['format'] != null)
$value = $this->formatter()->format($value, $params['format']);
return $value;
}
/**
* Populating columns for checking the column is string or array. if is string this will be checking have a formatter or header.
* @param array $columns
* @throws InvalidParamException
* @return multitype:multitype:array
*/
public function populateColumns($columns = [])
{
$_columns = [];
foreach ($columns as $key => $value)
{
if (is_string($value))
{
$value_log = explode(':', $value);
$_columns[$key] = ['attribute' => $value_log[0]];
if (isset($value_log[1]) && $value_log[1] !== null) {
$_columns[$key]['format'] = $value_log[1];
}
if (isset($value_log[2]) && $value_log[2] !== null) {
$_columns[$key]['header'] = $value_log[2];
}
} elseif (is_array($value)) {
if (!isset($value['attribute']) && !isset($value['value'])) {
throw new \InvalidArgumentException('Attribute or Value must be defined.');
}
$_columns[$key] = $value;
}
}
return $_columns;
}
/**
* Formatter for i18n.
* @return Formatter
*/
public function formatter()
{
if (!isset($this->formatter))
$this->formatter = \Yii::$app->getFormatter();
return $this->formatter;
}
/**
* Setting header to download generated file xls
*/
public function setHeaders()
{
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $this->getFileName() .'"');
header('Cache-Control: max-age=0');
}
/**
* Getting the file name of exporting xls file
* @return string
*/
public function getFileName()
{
$fileName = 'exports.xlsx';
if (isset($this->fileName)) {
$fileName = $this->fileName;
if (strpos($fileName, '.xlsx') === false)
$fileName .= '.xlsx';
}
return $fileName;
}
/**
* Setting properties for excel file
* @param PHPExcel $objectExcel
* @param array $properties
*/
public function properties(&$objectExcel, $properties = [])
{
foreach ($properties as $key => $value)
{
$keyname = "set" . ucfirst($key);
$objectExcel->getProperties()->{$keyname}($value);
}
}
/**
* saving the xls file to download or to path
*/
public function writeFile($sheet)
{
if (!isset($this->format))
$this->format = 'Xlsx';
$objectwriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($sheet, $this->format);
$path = 'php://output';
if (isset($this->savePath) && $this->savePath != null) {
$path = $this->savePath . '/' . $this->getFileName();
}
$objectwriter->setOffice2003Compatibility($this->compatibilityOffice2003);
$objectwriter->setPreCalculateFormulas($this->preCalculationFormula);
$objectwriter->save($path);
if ($path == 'php://output')
exit();
return true;
}
/**
* reading the xls file
*/
public function readFile($fileName)
{
if (!isset($this->format))
$this->format = \PhpOffice\PhpSpreadsheet\IOFactory::identify($fileName);
$objectreader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($this->format);
if ($this->format == "Csv") {
$objectreader->setDelimiter($this->CSVDelimiter);
$objectreader->setInputEncoding($this->CSVEncoding);
}
$objectPhpExcel = $objectreader->load($fileName);
$sheetCount = $objectPhpExcel->getSheetCount();
$sheetDatas = [];
if ($sheetCount > 1) {
foreach ($objectPhpExcel->getSheetNames() as $sheetIndex => $sheetName) {
if (isset($this->getOnlySheet) && $this->getOnlySheet != null) {
if(!$objectPhpExcel->getSheetByName($this->getOnlySheet)) {
return $sheetDatas;
}
$objectPhpExcel->setActiveSheetIndexByName($this->getOnlySheet);
$indexed = $this->getOnlySheet;
$sheetDatas[$indexed] = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas[$indexed] = $this->executeArrayLabel($sheetDatas[$indexed]);
}
if (!empty($this->getOnlyRecordByIndex)) {
$sheetDatas[$indexed] = $this->executeGetOnlyRecords($sheetDatas[$indexed], $this->getOnlyRecordByIndex);
}
if (!empty($this->leaveRecordByIndex)) {
$sheetDatas[$indexed] = $this->executeLeaveRecords($sheetDatas[$indexed], $this->leaveRecordByIndex);
}
return $sheetDatas[$indexed];
} else {
$objectPhpExcel->setActiveSheetIndexByName($sheetName);
$indexed = $this->setIndexSheetByName==true ? $sheetName : $sheetIndex;
$sheetDatas[$indexed] = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas[$indexed] = $this->executeArrayLabel($sheetDatas[$indexed]);
}
if (!empty($this->getOnlyRecordByIndex) && isset($this->getOnlyRecordByIndex[$indexed]) && is_array($this->getOnlyRecordByIndex[$indexed])) {
$sheetDatas = $this->executeGetOnlyRecords($sheetDatas, $this->getOnlyRecordByIndex[$indexed]);
}
if (!empty($this->leaveRecordByIndex) && isset($this->leaveRecordByIndex[$indexed]) && is_array($this->leaveRecordByIndex[$indexed])) {
$sheetDatas[$indexed] = $this->executeLeaveRecords($sheetDatas[$indexed], $this->leaveRecordByIndex[$indexed]);
}
}
}
} else {
$sheetDatas = $objectPhpExcel->getActiveSheet()->toArray(null, true, true, true);
if ($this->setFirstRecordAsKeys) {
$sheetDatas = $this->executeArrayLabel($sheetDatas);
}
if (!empty($this->getOnlyRecordByIndex)) {
$sheetDatas = $this->executeGetOnlyRecords($sheetDatas, $this->getOnlyRecordByIndex);
}
if (!empty($this->leaveRecordByIndex)) {
$sheetDatas = $this->executeLeaveRecords($sheetDatas, $this->leaveRecordByIndex);
}
}
return $sheetDatas;
}
/**
* (non-PHPdoc)
* @see \yii\base\Widget::run()
*/
public function run()
{
if ($this->mode == 'export')
{
$sheet = new Spreadsheet();
if (!isset($this->models))
throw new InvalidConfigException('Config models must be set');
if (isset($this->properties))
{
$this->properties($sheet, $this->properties);
}
if ($this->isMultipleSheet) {
$index = 0;
$worksheet = [];
foreach ($this->models as $title => $models) {
$sheet->createSheet($index);
$sheet->getSheet($index)->setTitle($title);
$worksheet[$index] = $sheet->getSheet($index);
$columns = isset($this->columns[$title]) ? $this->columns[$title] : [];
$headers = isset($this->headers[$title]) ? $this->headers[$title] : [];
$this->executeColumns($worksheet[$index], $models, $this->populateColumns($columns), $headers);
$index++;
}
} else {
$worksheet = $sheet->getActiveSheet();
$this->executeColumns($worksheet, $this->models, isset($this->columns) ? $this->populateColumns($this->columns) : [], isset($this->headers) ? $this->headers : []);
}
if ($this->asAttachment) {
$this->setHeaders();
}
$this->writeFile($sheet);
$sheet->disconnectWorksheets();
unset($sheet);
}
elseif ($this->mode == 'import')
{
if (is_array($this->fileName)) {
$datas = [];
foreach ($this->fileName as $key => $filename) {
$datas[$key] = $this->readFile($filename);
}
return $datas;
} else {
return $this->readFile($this->fileName);
}
}
}
/**
* Exporting data into an excel file.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => $allModels,
* 'columns' => ['column1','column2','column3'],
* //without header working, because the header will be get label from attribute label.
* 'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
* ]);
*
* ~~~
*
* New Feature for exporting data, you can use this if you familiar yii gridview.
* That is same with gridview data column.
* Columns in array mode valid params are 'attribute', 'header', 'format', 'value', and footer (TODO).
* Columns in string mode valid layout are 'attribute:format:header:footer(TODO)'.
*
* ~~~
*
* \moonland\phpexcel\Excel::export([
* 'models' => Post::find()->all(),
* 'columns' => [
* 'author.name:text:Author Name',
* [
* 'attribute' => 'content',
* 'header' => 'Content Post',
* 'format' => 'text',
* 'value' => function($model) {
* return ExampleClass::removeText('example', $model->content);
* },
* ],
* 'like_it:text:Reader like this content',
* 'created_at:datetime',
* [
* 'attribute' => 'updated_at',
* 'format' => 'date',
* ],
* ],
* 'headers' => [
* 'created_at' => 'Date Created Content',
* ],
* ]);
*
* ~~~
*
* @param array $config
* @return string
*/
| php | MIT | ccf28ff8ce2c665a7769dd6516098b4a35c8c309 | 2026-01-05T04:54:48.747475Z | true |
rap2hpoutre/similar-text-finder | https://github.com/rap2hpoutre/similar-text-finder/blob/89fa6b59483b42ee670c3959fbe20f8cc1ccd177/src/Finder.php | src/Finder.php | <?php
namespace SimilarText;
/**
* Class Finder
* @package SimilarText
*
* Thanks to: http://php.net/manual/fr/function.levenshtein.php#113702
*/
class Finder
{
/**
* @var string Needle
*/
protected $needle;
/**
* @var array Haystack
*/
protected $haystack;
/**
* Hold the sorted comparison stack.
*
* @var array Haystack
*/
protected $sorted_haystack;
/**
* @var null|int Threshold
*/
protected $threshold;
/**
* Finder constructor.
*
* @param string $needle
* @param array $haystack
* @return void
*/
public function __construct($needle, $haystack)
{
$this->needle = $needle;
$this->haystack = $haystack;
}
/**
* Sort Haystack.
*
* @return void
*/
protected function sortHaystack()
{
$sorted_haystack = [];
foreach ($this->haystack as $string) {
$sorted_haystack[$string] = $this->levenshteinUtf8($this->needle, $string);
}
// Apply threshold when set.
if(!is_null($this->threshold)){
$sorted_haystack = array_filter($sorted_haystack, function ($score){
return $score <= $this->threshold;
});
}
asort($sorted_haystack);
$this->sorted_haystack = $sorted_haystack;
}
/**
* Apply threshold to filter only relevant results. The higher
* the threshold the more results there will be returned.
*
* @param int|null $threshold
* @return Finder
*/
public function threshold($threshold = null)
{
$this->threshold = $threshold;
return $this;
}
/**
* Return the highest match.
*
* @return mixed
*/
public function first()
{
$this->sortHaystack();
reset($this->sorted_haystack);
return key($this->sorted_haystack);
}
/**
* Return all strings in sorted match order.
*
* @return array
*/
public function all()
{
$this->sortHaystack();
return array_keys($this->sorted_haystack);
}
/**
* Return whether there is an exact match.
*
* @return bool
*/
public function hasExactMatch()
{
return in_array($this->needle, $this->haystack);
}
/**
* Ensure a string only uses ascii characters.
*
* @param string $str
* @param array $map
* @return string
*/
protected function utf8ToExtendedAscii($str, &$map)
{
// Find all multi-byte characters (cf. utf-8 encoding specs).
$matches = array();
if (!preg_match_all('/[\xC0-\xF7][\x80-\xBF]+/', $str, $matches)) {
return $str; // plain ascii string
}
// Update the encoding map with the characters not already met.
foreach ($matches[0] as $mbc) {
if (!isset($map[$mbc])) {
$map[$mbc] = chr(128 + count($map));
}
}
// Finally remap non-ascii characters.
return strtr($str, $map);
}
/**
* Calculate the levenshtein distance between two strings.
*
* @param string $string1
* @param string $string2
* @return int
*/
protected function levenshteinUtf8($string1, $string2)
{
$charMap = array();
$string1 = $this->utf8ToExtendedAscii($string1, $charMap);
$string2 = $this->utf8ToExtendedAscii($string2, $charMap);
return levenshtein($string1, $string2);
}
}
| php | MIT | 89fa6b59483b42ee670c3959fbe20f8cc1ccd177 | 2026-01-05T04:54:57.053589Z | false |
rap2hpoutre/similar-text-finder | https://github.com/rap2hpoutre/similar-text-finder/blob/89fa6b59483b42ee670c3959fbe20f8cc1ccd177/test/FinderTest.php | test/FinderTest.php | <?php namespace SimilarText\Test;
use SimilarText\Finder;
use PHPUnit\Framework\TestCase;
/**
* Class FinderTest
* @package SimilarText\Test
*/
class FinderTest extends TestCase
{
/**
* Test first() method
*/
public function testFirst()
{
$text_finder = new Finder('bananna', ['apple', 'kiwi', 'banana', 'orange', 'banner']);
$this->assertEquals('banana', $text_finder->first());
}
/**
* Test all() method
*/
public function testAll()
{
$text_finder = new Finder('bananna', ['apple', 'kiwi', 'Ü◘ö']);
$this->assertCount(3, $text_finder->all());
}
/**
* Test hasExactMatch() method
*/
public function testHasExactMatch() {
$text_finder = new Finder('banana', ['apple', 'kiwi', 'banana']);
$this->assertTrue($text_finder->hasExactMatch());
}
/**
* Test hasExactMatch() method
*/
public function testHasNotExactMatch() {
$text_finder = new Finder('banana', ['apple', 'kiwi']);
$this->assertFalse($text_finder->hasExactMatch());
}
/**
* Test threshold() method
*/
public function testThreshold() {
$text_finder = new Finder('bananna', ['apple', 'kiwi', 'banana', 'orange', 'bandana', 'banana', 'canary']);
$this->assertEquals(['banana', 'bandana', 'canary'], $text_finder->threshold(4)->all());
$text_finder = new Finder('bananna', ['apple', 'kiwi', 'banana', 'orange', 'bandana', 'banana', 'canary']);
$this->assertEquals('banana', $text_finder->threshold(2)->first());
$text_finder = new Finder('banana', ['apple', 'kiwi', 'banana', 'orange', 'bandana', 'banana', 'canary']);
$this->assertEquals('banana', $text_finder->threshold(0)->first());
$text_finder = new Finder('bananna', ['apple', 'kiwi', 'orange', 'melon']);
$this->assertNull($text_finder->threshold(2)->first());
}
}
| php | MIT | 89fa6b59483b42ee670c3959fbe20f8cc1ccd177 | 2026-01-05T04:54:57.053589Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/GeminiServiceProvider.php | src/GeminiServiceProvider.php | <?php
namespace HosseinHezami\LaravelGemini;
use Illuminate\Support\ServiceProvider;
use HosseinHezami\LaravelGemini\Console\ModelsCommand;
use HosseinHezami\LaravelGemini\Factory\ProviderFactory;
use HosseinHezami\LaravelGemini\Gemini;
class GeminiServiceProvider extends ServiceProvider
{
/**
* Register services
*/
public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/Config/gemini.php', 'gemini');
$this->app->singleton(ProviderFactory::class, function ($app) {
return new ProviderFactory();
});
$this->app->singleton('gemini', function ($app) {
return new Gemini($app->make(ProviderFactory::class));
});
}
/**
* Bootstrap services
*/
public function boot(): void
{
$this->publishes([
__DIR__ . '/Config/gemini.php' => config_path('gemini.php'),
], ['gemini-config']);
if ($this->app->runningInConsole()) {
$this->commands([
ModelsCommand::class,
]);
}
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Gemini.php | src/Gemini.php | <?php
namespace HosseinHezami\LaravelGemini;
use HosseinHezami\LaravelGemini\Builders\TextBuilder;
use HosseinHezami\LaravelGemini\Builders\ImageBuilder;
use HosseinHezami\LaravelGemini\Builders\VideoBuilder;
use HosseinHezami\LaravelGemini\Builders\AudioBuilder;
use HosseinHezami\LaravelGemini\Builders\FileBuilder;
use HosseinHezami\LaravelGemini\Builders\CacheBuilder;
use HosseinHezami\LaravelGemini\Factory\ProviderFactory;
class Gemini
{
protected ProviderFactory $factory;
protected ?string $apiKey = null;
public function __construct(ProviderFactory $factory)
{
$this->factory = $factory;
}
public function setApiKey(string $apiKey): self
{
$this->apiKey = $apiKey;
return $this;
}
public function text(): TextBuilder
{
return new TextBuilder($this->getProvider());
}
public function image(): ImageBuilder
{
return new ImageBuilder($this->getProvider());
}
public function video(): VideoBuilder
{
return new VideoBuilder($this->getProvider());
}
public function audio(): AudioBuilder
{
return new AudioBuilder($this->getProvider());
}
public function files(): FileBuilder
{
return new FileBuilder($this->getProvider());
}
public function caches(): CacheBuilder
{
return new CacheBuilder($this->getProvider());
}
public function models()
{
return $this->getProvider()->models();
}
public function embeddings(array $params): array
{
return $this->getProvider()->embeddings($params);
}
public function getProvider(?string $alias = null)
{
return $this->factory->create($alias, $this->apiKey);
}
}
| php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/RateLimitException.php | src/Exceptions/RateLimitException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class RateLimitException extends BaseException
{
public ?int $retryAfter;
public function __construct(string $message = 'Rate limit exceeded', ?int $retryAfter = null)
{
parent::__construct($message);
$this->retryAfter = $retryAfter;
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/NetworkException.php | src/Exceptions/NetworkException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class NetworkException extends BaseException
{
public function __construct(string $message = 'Network issue')
{
parent::__construct($message);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/StreamException.php | src/Exceptions/StreamException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class StreamException extends BaseException
{
public function __construct(string $message = 'Streaming interrupted')
{
parent::__construct($message);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/BaseException.php | src/Exceptions/BaseException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
use Exception;
class BaseException extends Exception
{
//
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/ApiException.php | src/Exceptions/ApiException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class ApiException extends BaseException
{
public function __construct(string $message = 'API error occurred')
{
parent::__construct($message);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/ValidationException.php | src/Exceptions/ValidationException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class ValidationException extends BaseException
{
public function __construct(string $message = 'Invalid input parameters')
{
parent::__construct($message);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Exceptions/AuthenticationException.php | src/Exceptions/AuthenticationException.php | <?php
namespace HosseinHezami\LaravelGemini\Exceptions;
class AuthenticationException extends BaseException
{
public function __construct(string $message = 'Invalid API key or authentication issue')
{
parent::__construct($message);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Helpers/helpers.php | src/Helpers/helpers.php | <?php
if (! function_exists('safe_base64_encode')) {
function safe_base64_encode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Http/HttpClient.php | src/Http/HttpClient.php | <?php
namespace HosseinHezami\LaravelGemini\Http;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\PendingRequest;
use HosseinHezami\LaravelGemini\Exceptions\RateLimitException;
class HttpClient
{
protected PendingRequest $client;
public function __construct(?string $baseUrl = null, ?string $apiKey = null)
{
$baseUrl = $baseUrl ?? config('gemini.base_uri');
$apiKey = $apiKey ?? config('gemini.api_key');
$this->client = Http::baseUrl($baseUrl)
->withHeaders(['x-goog-api-key' => $apiKey])
->timeout(config('gemini.timeout'))
->retry(config('gemini.retry_policy.max_retries'), config('gemini.retry_policy.retry_delay'), function ($exception, $request) {
if ($exception instanceof RateLimitException) {
sleep($exception->retryAfter ?? 1);
return true;
}
return $exception->response->status() >= 500;
});
}
public function withHeaders(array $headers): self
{
$this->client = $this->client->withHeaders($headers);
return $this;
}
public function withBody($content, string $contentType = 'application/json'): self
{
$this->client = $this->client->withBody($content, $contentType);
return $this;
}
public function withOptions(array $options): self
{
$this->client = $this->client->withOptions($options);
return $this;
}
public function post(string $url, array $data = []): \Illuminate\Http\Client\Response
{
return $this->client->post($url, $data);
}
public function get(string $url): \Illuminate\Http\Client\Response
{
return $this->client->get($url);
}
public function patch(string $url, array $data): \Illuminate\Http\Client\Response
{
return $this->client->patch($url, $data);
}
public function delete(string $url): \Illuminate\Http\Client\Response
{
return $this->client->delete($url);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Contracts/ProviderInterface.php | src/Contracts/ProviderInterface.php | <?php
namespace HosseinHezami\LaravelGemini\Contracts;
use HosseinHezami\LaravelGemini\Responses;
interface ProviderInterface
{
public function generateText(array $payload): Responses\TextResponse;
public function generateImage(array $payload): Responses\ImageResponse;
public function generateVideo(array $payload): Responses\VideoResponse;
public function generateAudio(array $payload): Responses\AudioResponse;
public function embeddings(array $params): array;
public function uploadFile(array $params): string;
public function listFiles(array $params): Responses\FileResponse;
public function getFile(string $fileName): Responses\FileResponse;
public function deleteFile(string $fileName): bool;
public function models(): array;
public function streaming(array $params, callable $callback): void;
}
| php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/TextBuilder.php | src/Builders/TextBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Enums\Capability;
use HosseinHezami\LaravelGemini\Responses\TextResponse;
class TextBuilder extends BaseBuilder
{
protected function getCapability(): string
{
return Capability::TEXT->value;
}
public function generate(): TextResponse
{
return $this->provider->generateText($this->params);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/CacheBuilder.php | src/Builders/CacheBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Providers\GeminiProvider;
use HosseinHezami\LaravelGemini\Responses\CacheResponse;
use HosseinHezami\LaravelGemini\Exceptions\ValidationException;
class CacheBuilder
{
protected GeminiProvider $provider;
public function __construct(GeminiProvider $provider)
{
$this->provider = $provider;
}
// Create a cached content with direct parameters
public function create(
string $model,
array $contents,
?string $systemInstruction = null,
array $tools = [],
array $toolConfig = [],
?string $displayName = null,
?string $ttl = null,
?string $expireTime = null
): CacheResponse {
if (empty($model) || empty($contents)) {
throw new ValidationException('Model and contents are required for creating cache.');
}
$params = compact('model', 'contents', 'systemInstruction', 'tools', 'toolConfig', 'displayName', 'ttl', 'expireTime');
return $this->provider->createCachedContent($params);
}
// List cached contents with optional params
public function list(?int $pageSize = null, ?string $pageToken = null): CacheResponse
{
$params = array_filter(compact('pageSize', 'pageToken'));
return $this->provider->listCachedContents($params);
}
// Get a cached content by name
public function get(string $name): CacheResponse
{
if (empty($name)) {
throw new ValidationException('Cache name is required.');
}
return $this->provider->getCachedContent($name);
}
// Update cache expiration
public function update(
string $name,
?string $ttl = null,
?string $expireTime = null
): CacheResponse {
if (empty($name)) {
throw new ValidationException('Cache name is required.');
}
if (empty($ttl) && empty($expireTime)) {
throw new ValidationException('TTL or expireTime is required for update.');
}
$expiration = array_filter(compact('ttl', 'expireTime'));
return $this->provider->updateCachedContent($name, $expiration);
}
// Delete a cached content by name
public function delete(string $name): bool
{
if (empty($name)) {
throw new ValidationException('Cache name is required.');
}
return $this->provider->deleteCachedContent($name);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/VideoBuilder.php | src/Builders/VideoBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Enums\Capability;
use HosseinHezami\LaravelGemini\Responses\VideoResponse;
class VideoBuilder extends BaseBuilder
{
protected function getCapability(): string
{
return Capability::VIDEO->value;
}
public function generate(): VideoResponse
{
return $this->provider->generateVideo($this->params);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/BaseBuilder.php | src/Builders/BaseBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Contracts\ProviderInterface;
use HosseinHezami\LaravelGemini\Exceptions\ValidationException;
use HosseinHezami\LaravelGemini\Responses\CacheResponse;
abstract class BaseBuilder
{
protected ProviderInterface $provider;
protected array $params = [];
public function __construct(ProviderInterface $provider)
{
$this->provider = $provider;
$this->params['capability'] = $this->getCapability();
$this->params['defaultProvider'] = config('gemini.default_provider');
$this->params['model'] = config('gemini.providers.' . $this->params['defaultProvider'] . '.models.' . $this->params['capability']);
$this->params['method'] = config('gemini.providers.' . $this->params['defaultProvider'] . '.methods.' . $this->params['capability']);
if (empty($this->params['model'])) {
throw new ValidationException("Default model for {$this->params['capability']} not found in configuration.");
}
if (empty($this->params['method'])) {
throw new ValidationException("Default method for {$this->params['capability']} not found in configuration.");
}
}
abstract protected function getCapability(): string;
public function model(string $model = null): self
{
$this->params['model'] = $model ?? $this->params['model'];
return $this;
}
public function method(string $method): self
{
if (!in_array($method, ['generateContent', 'predict', 'predictLongRunning'])) {
throw new ValidationException("Invalid method: {$method}. Supported: generateContent, predict, predictLongRunning.");
}
$this->params['method'] = $method ?? $this->params['method'];
return $this;
}
public function prompt(string $prompt): self
{
$this->params['prompt'] = $prompt;
return $this;
}
public function system(string $system): self
{
$this->params['system'] = $system;
return $this;
}
public function history(array $history): self
{
$this->params['history'] = $history;
return $this;
}
public function historyFromModel($query, $bodyColumn, $roleColumn): self
{
$history = $query->get()->map(function ($item) use ($bodyColumn, $roleColumn) {
return ['role' => $item->{$roleColumn}, 'parts' => [['text' => $item->{$bodyColumn}]]];
})->toArray();
return $this->history($history);
}
public function temperature(float $value): self
{
$this->params['temperature'] = $value;
return $this;
}
public function maxTokens(int $value): self
{
$this->params['maxTokens'] = $value;
return $this;
}
public function safetySettings(array $settings): self
{
$this->params['safetySettings'] = $settings;
return $this;
}
public function functionCalls(array $functions): self
{
$this->params['functions'] = $functions;
return $this;
}
public function structuredSchema(array $schema): self
{
$this->params['structuredSchema'] = $schema;
return $this;
}
public function upload(string $fileType, string $filePath): self
{
$this->params['fileType'] = $fileType;
$this->params['filePath'] = $filePath;
return $this;
}
public function file(string $fileType, string $fileUri): self
{
$this->params['fileType'] = $fileType;
$this->params['fileUri'] = $fileUri;
return $this;
}
public function cache(
?array $tools = [],
?array $toolConfig = [],
?string $displayName = null,
?string $ttl = null,
?string $expireTime = null
): string {
// Build contents from existing params (like prompt, history)
$contents = [];
if (isset($this->params['history'])) {
$contents = array_merge($contents, $this->params['history']);
}
if (isset($this->params['prompt'])) {
$contents[] = ['role' => 'user', 'parts' => [['text' => $this->params['prompt']]]];
}
// Use system if set
$systemInstruction = isset($this->params['system']) ? $this->params['system'] : null;
// Prepare params for provider
$cacheParams = [
'model' => $this->params['model'],
'contents' => $contents,
'systemInstruction' => $systemInstruction,
'tools' => $tools,
'toolConfig' => $toolConfig,
'displayName' => $displayName,
'ttl' => $ttl ?? config('gemini.caching.default_ttl'),
'expireTime' => $expireTime,
];
// Call provider to create
$response = $this->provider->createCachedContent($cacheParams);
// Return the cache name for chaining or use
return $response->name();
}
public function getCache(string $name): CacheResponse
{
if (empty($name)) {
throw new ValidationException('Cache name is required.');
}
return $this->provider->getCachedContent($name);
}
public function cachedContent(string $name): self
{
$this->params['cachedContent'] = $name;
return $this;
}
abstract public function generate();
public function stream(callable $callback): void
{
$this->provider->streaming($this->params, $callback);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/AudioBuilder.php | src/Builders/AudioBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Enums\Capability;
use HosseinHezami\LaravelGemini\Responses\AudioResponse;
use HosseinHezami\LaravelGemini\Exceptions\ValidationException;
class AudioBuilder extends BaseBuilder
{
protected function getCapability(): string
{
return Capability::AUDIO->value;
}
/**
* Set voice name for single-speaker TTS.
*
* @param string $voiceName e.g., 'Kore', 'Puck'
* @return self
*/
public function voiceName(string $voiceName): self
{
$this->params['voiceName'] = $voiceName;
$this->params['multiSpeaker'] = false;
return $this;
}
/**
* Set speaker voices for multi-speaker TTS.
*
* @param array $speakerVoices e.g., [['speaker' => 'Joe', 'voiceName' => 'Kore'], ['speaker' => 'Jane', 'voiceName' => 'Puck']]
* @return self
*/
public function speakerVoices(array $speakerVoices): self
{
$this->params['speakerVoices'] = $speakerVoices;
$this->params['multiSpeaker'] = true;
return $this;
}
public function generate(): AudioResponse
{
// Validate voiceName for single-speaker
if (!isset($this->params['multiSpeaker']) || !$this->params['multiSpeaker']) {
if (!isset($this->params['voiceName']) || empty($this->params['voiceName'])) {
throw new ValidationException('Voice name is required for single-speaker TTS.');
}
}
// Validate speakerVoices for multi-speaker
if (isset($this->params['multiSpeaker']) && $this->params['multiSpeaker']) {
if (!isset($this->params['speakerVoices']) || empty($this->params['speakerVoices'])) {
throw new ValidationException('Speaker voices are required for multi-speaker TTS.');
}
}
return $this->provider->generateAudio($this->params);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/FileBuilder.php | src/Builders/FileBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Providers\GeminiProvider;
use HosseinHezami\LaravelGemini\Responses\FileResponse;
use HosseinHezami\LaravelGemini\Exceptions\ValidationException;
class FileBuilder
{
protected array $params = [];
protected GeminiProvider $provider;
public function __construct(GeminiProvider $provider)
{
$this->provider = $provider;
}
public function upload(string $fileType, string $filePath): string
{
if (empty($fileType) || empty($filePath)) {
throw new ValidationException('File type and path are required for upload.');
}
$this->params['fileType'] = $fileType;
$this->params['filePath'] = $filePath;
return $this->provider->uploadFile($this->params);
}
public function get(string $fileName): FileResponse
{
if (empty($fileName)) {
throw new ValidationException('File name is required.');
}
return $this->provider->getFile($fileName);
}
public function delete(string $fileName): bool
{
if (empty($fileName)) {
throw new ValidationException('File name is required.');
}
return $this->provider->deleteFile($fileName);
}
public function list(array $params = []): FileResponse
{
$this->params = array_merge($this->params, $params);
return $this->provider->listFiles($this->params);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Builders/ImageBuilder.php | src/Builders/ImageBuilder.php | <?php
namespace HosseinHezami\LaravelGemini\Builders;
use HosseinHezami\LaravelGemini\Enums\Capability;
use HosseinHezami\LaravelGemini\Responses\ImageResponse;
class ImageBuilder extends BaseBuilder
{
protected function getCapability(): string
{
return Capability::IMAGE->value;
}
public function generate(): ImageResponse
{
return $this->provider->generateImage($this->params);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Facades/Gemini.php | src/Facades/Gemini.php | <?php
namespace HosseinHezami\LaravelGemini\Facades;
use Illuminate\Support\Facades\Facade;
use HosseinHezami\LaravelGemini\Builders\TextBuilder;
use HosseinHezami\LaravelGemini\Builders\ImageBuilder;
use HosseinHezami\LaravelGemini\Builders\VideoBuilder;
use HosseinHezami\LaravelGemini\Builders\AudioBuilder;
use HosseinHezami\LaravelGemini\Builders\FileBuilder;
use HosseinHezami\LaravelGemini\Builders\CacheBuilder;
class Gemini extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'gemini';
}
public static function text(): TextBuilder
{
return static::getFacadeRoot()->text();
}
public static function image(): ImageBuilder
{
return static::getFacadeRoot()->image();
}
public static function video(): VideoBuilder
{
return static::getFacadeRoot()->video();
}
public static function audio(): AudioBuilder
{
return static::getFacadeRoot()->audio();
}
public static function files(): FileBuilder
{
return static::getFacadeRoot()->files();
}
public static function caches(): CacheBuilder
{
return static::getFacadeRoot()->caches();
}
public static function setApiKey(string $apiKey): self
{
static::getFacadeRoot()->setApiKey($apiKey);
return new static;
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Console/ModelsCommand.php | src/Console/ModelsCommand.php | <?php
namespace HosseinHezami\LaravelGemini\Console;
use Illuminate\Console\Command;
use HosseinHezami\LaravelGemini\Facades\Gemini;
class ModelsCommand extends Command
{
protected $signature = 'gemini:models';
protected $description = 'List available Gemini models';
public function handle(): void
{
$models = Gemini::models();
$tableData = array_map(function ($model) {
return [
$model['name'],
$model['displayName'],
$model['version'] ?? 'N/A',
implode(', ', $model['supportedGenerationMethods'] ?? []),
];
}, $models);
$this->table(['Model', 'Name', 'Version', 'Capabilities'], $tableData);
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Config/gemini.php | src/Config/gemini.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Gemini API Key
|--------------------------------------------------------------------------
|
| Your Google Gemini API key. You can get it from:
| https://aistudio.google.com/app/apikey
|
*/
'api_key' => env('GEMINI_API_KEY', ''),
/*
|--------------------------------------------------------------------------
| Base URI
|--------------------------------------------------------------------------
|
| The base URI for the Gemini API.
|
*/
'base_uri' => env('GEMINI_BASE_URI', 'https://generativelanguage.googleapis.com'),
/*
|--------------------------------------------------------------------------
| Default Provider
|--------------------------------------------------------------------------
|
| The default provider to use for API requests.
|
*/
'default_provider' => env('GEMINI_DEFAULT_PROVIDER', 'gemini'),
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Configuration for different providers. Each provider should specify
| the class and default models and methods for different capabilities.
|
*/
'providers' => [
'gemini' => [
'class' => \HosseinHezami\LaravelGemini\Providers\GeminiProvider::class,
'models' => [
'text' => 'gemini-2.5-flash-lite',
'image' => 'gemini-2.5-flash-image-preview',
'video' => 'veo-3.0-fast-generate-001',
'audio' => 'gemini-2.5-flash-preview-tts',
'embedding' => 'gemini-embedding-001',
],
'methods' => [
'text' => 'generateContent',
'image' => 'generateContent', // generateContent, predict
'video' => 'predictLongRunning',
'audio' => 'generateContent',
],
/**
* Set voice name for single-speaker TTS.
* @param string $voiceName e.g., 'Kore', 'Puck'
* Set speaker voices for multi-speaker TTS.
* @param array $speakerVoices e.g., [['speaker' => 'Joe', 'voiceName' => 'Kore'], ['speaker' => 'Jane', 'voiceName' => 'Puck']]
*/
'default_speech_config' => [
'voiceName' => 'Kore'
],
],
],
/*
|--------------------------------------------------------------------------
| Request Timeout
|--------------------------------------------------------------------------
|
| The timeout in seconds for API requests.
|
*/
'timeout' => env('GEMINI_TIMEOUT', 30),
/*
|--------------------------------------------------------------------------
| Retry Policy
|--------------------------------------------------------------------------
|
| Configuration for retrying failed requests.
|
*/
'retry_policy' => [
'max_retries' => env('GEMINI_MAX_RETRIES', 30),
'retry_delay' => env('GEMINI_RETRY_DELAY', 1000), // milliseconds
],
/*
|--------------------------------------------------------------------------
| Safety Settings
|--------------------------------------------------------------------------
|
| Default safety settings for content generation.
|
*/
'safety_settings' => [
[
'category' => 'HARM_CATEGORY_HARASSMENT',
'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
],
[
'category' => 'HARM_CATEGORY_HATE_SPEECH',
'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
],
[
'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
],
[
'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
],
],
/*
|--------------------------------------------------------------------------
| Logging
|--------------------------------------------------------------------------
|
| Enable or disable logging of API requests and responses.
|
*/
'logging' => env('GEMINI_LOGGING', false),
/*
|--------------------------------------------------------------------------
| Stream Configuration
|--------------------------------------------------------------------------
|
| Configuration for streaming responses.
|
*/
'stream' => [
'chunk_size' => env('GEMINI_STREAM_CHUNK_SIZE', 1024),
'timeout' => env('GEMINI_STREAM_TIMEOUT', 1000),
],
/*
|--------------------------------------------------------------------------
| Caching Configuration
|--------------------------------------------------------------------------
|
| Cache Configuration.
|
*/
'caching' => [
'default_ttl' => '3600s', // Default expiration TTL (e.g., '300s', '1h')
'max_page_size' => 50, // Default page size for listing caches
],
];
| php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Enums/Capability.php | src/Enums/Capability.php | <?php
namespace HosseinHezami\LaravelGemini\Enums;
enum Capability: string
{
case TEXT = 'text';
case IMAGE = 'image';
case VIDEO = 'video';
case AUDIO = 'audio';
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Providers/BaseProvider.php | src/Providers/BaseProvider.php | <?php
namespace HosseinHezami\LaravelGemini\Providers;
use HosseinHezami\LaravelGemini\Http\HttpClient;
use HosseinHezami\LaravelGemini\Exceptions;
use Illuminate\Support\Facades\Http;
abstract class BaseProvider
{
protected HttpClient $http;
public function __construct(?string $apiKey = null)
{
$this->http = new HttpClient(apiKey: $apiKey);
}
protected function handleResponse($response, string $type)
{
if ($response->failed()) {
$status = $response->status();
if ($status === 401) {
throw new Exceptions\AuthenticationException();
} elseif ($status === 429) {
throw new Exceptions\RateLimitException(retryAfter: $response->header('Retry-After'));
} elseif ($status >= 500) {
throw new Exceptions\ApiException();
} elseif ($status === 400) {
throw new Exceptions\ValidationException();
} else {
throw new Exceptions\NetworkException();
}
}
$data = $response->json();
return new ("HosseinHezami\\LaravelGemini\\Responses\\" . $type . "Response")($data);
}
/**
* Upload a file to Gemini API and return its URI.
*
* @param string $fileType Type of file (e.g., 'image', 'video', 'audio', 'document')
* @param string $filePath Path to the file
* @return string File URI returned by the API
* @throws Exceptions\ValidationException If file type is invalid or file not found
* @throws Exceptions\ApiException
* @throws Exceptions\RateLimitException
*/
protected function upload(string $fileType, string $filePath): string
{
if (!file_exists($filePath) || !is_readable($filePath)) {
throw new Exceptions\ValidationException("File does not exist or is not readable: {$filePath}");
}
$validTypes = ['image', 'video', 'audio', 'document'];
if (!in_array($fileType, $validTypes)) {
throw new Exceptions\ValidationException("Invalid file type: {$fileType}. Allowed types: " . implode(', ', $validTypes));
}
$mimeType = $this->getMimeType($fileType, $filePath);
$fileSize = filesize($filePath);
$displayName = basename($filePath);
/**
* Step 1: Initiate resumable upload session
*/
$initialResponse = $this->http
->withHeaders([
'Content-Type' => 'application/json',
])
->post('/upload/v1beta/files?uploadType=resumable', [
'file' => [
'display_name' => $displayName,
],
]);
$uploadUrl = $initialResponse->header('Location');
if (!$uploadUrl) {
throw new Exceptions\ApiException('Upload URL not received from API');
}
/**
* Step 2: Upload the entire file in a single chunk and finalize
*/
$uploadResponse = $this->http
->withHeaders([
'Content-Range' => "bytes 0-" . ($fileSize - 1) . "/$fileSize",
])
->withBody(
file_get_contents($filePath),
$mimeType
)
->post($uploadUrl);
if (!$uploadResponse->successful()) {
throw new Exceptions\ApiException('Upload failed: ' . $uploadResponse->body());
}
$json = $uploadResponse->json();
if (!isset($json['file']['uri'])) {
throw new Exceptions\ApiException('File URI not found in API response');
}
return $json['file']['uri'];
}
protected function getMimeType(string $fileType, string $filePath): string
{
$mimeTypes = [
'image' => ['png' => 'image/png', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'webp' => 'image/webp', 'heic' => 'image/heic', 'heif' => 'image/heif'],
'video' => ['mp4' => 'video/mp4', 'mpeg' => 'video/mpeg', 'mov' => 'video/mov', 'avi' => 'video/avi', 'flv' => 'video/x-flv', 'mpg' => 'video/mpg', 'webm' => 'video/webm', 'wmv' => 'video/wmv', '3gpp' => 'video/3gpp'],
'audio' => ['wav' => 'audio/x-wav', 'mp3' => 'audio/mp3', 'aiff' => 'audio/aiff', 'aac' => 'audio/aac', 'ogg' => 'audio/ogg', 'flac' => 'audio/flac'],
'document' => ['pdf' => 'application/pdf', 'txt' => 'text/plain', 'md' => 'text/markdown']
];
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
return $mimeTypes[$fileType][$extension] ?? throw new Exceptions\ValidationException("Unsupported {$fileType} format: {$extension}");
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Providers/GeminiProvider.php | src/Providers/GeminiProvider.php | <?php
namespace HosseinHezami\LaravelGemini\Providers;
use HosseinHezami\LaravelGemini\Contracts\ProviderInterface;
use HosseinHezami\LaravelGemini\Responses;
use HosseinHezami\LaravelGemini\Exceptions\ApiException;
use HosseinHezami\LaravelGemini\Exceptions\StreamException;
use HosseinHezami\LaravelGemini\Exceptions\RateLimitException;
use HosseinHezami\LaravelGemini\Exceptions\ValidationException;
use Illuminate\Support\Facades\Log;
class GeminiProvider extends BaseProvider implements ProviderInterface
{
public function __construct(array $config = [], ?string $apiKey = null)
{
parent::__construct($apiKey);
}
public function generateText(array $params): Responses\TextResponse
{
return $this->executeRequest($params, 'Text');
}
public function generateImage(array $params): Responses\ImageResponse
{
return $this->executeRequest($params, 'Image');
}
public function generateVideo(array $params): Responses\VideoResponse
{
return $this->executeRequest($params, 'Video');
}
public function generateAudio(array $params): Responses\AudioResponse
{
return $this->executeRequest($params, 'Audio');
}
public function embeddings(array $params): array
{
$response = $this->http->post("/v1beta/models/{$params['model']}:embedContent", $params);
return $response->json();
}
public function uploadFile(array $params): string
{
if (!isset($params['fileType']) || !isset($params['filePath'])) {
throw new ValidationException('File type and path are required.');
}
return $this->upload($params['fileType'], $params['filePath']);
}
public function listFiles(array $params = []): Responses\FileResponse
{
try {
$response = $this->http->get('/v1beta/files');
return $this->handleResponse($response, 'File');
} catch (\Exception $e) {
throw new ApiException("Get files list error: {$e->getMessage()}");
}
}
public function getFile(string $fileName): Responses\FileResponse
{
if (empty($fileName)) {
throw new ValidationException('File name is required.');
}
try {
$response = $this->http->get("/v1beta/files/{$fileName}");
return $this->handleResponse($response, 'File');
} catch (\Exception $e) {
throw new ApiException("Get file error: {$e->getMessage()}");
}
}
public function deleteFile(string $fileName): bool
{
if (empty($fileName)) {
throw new ValidationException('File name is required.');
}
try {
$response = $this->http->delete("/v1beta/files/{$fileName}");
return $response->successful();
} catch (\Exception $e) {
throw new ApiException("Delete file error: {$e->getMessage()}");
}
}
// Create cached content
public function createCachedContent(array $params): Responses\CacheResponse
{
$payload = [
'model' => "models/{$params['model']}",
'contents' => $params['contents'],
];
if (!empty($params['systemInstruction'])) {
$payload['systemInstruction'] = ['parts' => [['text' => $params['systemInstruction']]]];
}
if (!empty($params['tools'])) {
$payload['tools'] = $params['tools'];
}
if (!empty($params['toolConfig'])) {
$payload['toolConfig'] = $params['toolConfig'];
}
if (!empty($params['displayName'])) {
$payload['displayName'] = $params['displayName'];
}
if (!empty($params['expireTime'])) {
$payload['expireTime'] = $params['expireTime'];
} elseif (!empty($params['ttl'])) {
$payload['ttl'] = $params['ttl'] ?? config('gemini.caching.default_ttl');
}
try {
$response = $this->http->post('/v1beta/cachedContents', $payload);
return $this->handleResponse($response, 'Cache');
} catch (\Exception $e) {
throw new ApiException("Create cache error: {$e->getMessage()}");
}
}
// List cached contents
public function listCachedContents(array $params = []): Responses\CacheResponse
{
$queryParams = http_build_query(array_filter([
'pageSize' => $params['pageSize'] ?? config('gemini.caching.default_page_size'),
'pageToken' => $params['pageToken'] ?? null,
]));
try {
$response = $this->http->get("/v1beta/cachedContents?{$queryParams}");
return $this->handleResponse($response, 'Cache');
} catch (\Exception $e) {
throw new ApiException("List caches error: {$e->getMessage()}");
}
}
// Get cached content
public function getCachedContent(string $name): Responses\CacheResponse
{
try {
$response = $this->http->get("/v1beta/$name");
return $this->handleResponse($response, 'Cache');
} catch (\Exception $e) {
throw new ApiException("Get cache error: {$e->getMessage()}");
}
}
// Update cached content (expiration only)
public function updateCachedContent(string $name, array $expiration): Responses\CacheResponse
{
$payload = [];
if (!empty($expiration['ttl']) || !empty($expiration['expireTime'])) {
$payload = [];
if (!empty($expiration['expireTime'])) {
$payload['expireTime'] = $expiration['expireTime'];
} elseif (!empty($expiration['ttl'])) {
$payload['ttl'] = $expiration['ttl'];
} else {
$payload['ttl'] = config('gemini.caching.default_ttl');
}
} else {
throw new ValidationException('TTL or expireTime is required for update.');
}
try {
$response = $this->http->patch("/v1beta/{$name}", $payload);
return $this->handleResponse($response, 'Cache');
} catch (\Exception $e) {
throw new ApiException("Update cache error: {$e->getMessage()}");
}
}
// Delete cached content
public function deleteCachedContent(string $name): bool
{
try {
$response = $this->http->delete("/v1beta/$name");
return $response->successful();
} catch (\Exception $e) {
throw new ApiException("Delete cache error: {$e->getMessage()}");
}
}
public function models(): array
{
$response = $this->http->get('/v1beta/models');
return $response->json()['models'];
}
public function streaming(array $params, callable $callback): void
{
$method = $params['method'] ?? 'generateContent';
if ($method !== 'generateContent') {
throw new ValidationException('Streaming only supported for generateContent method.');
}
try {
$response = $this->http->withOptions([
'stream' => true,
])->post("/v1beta/models/{$params['model']}:streamGenerateContent", $this->buildRequestBody($params));
$body = $response->getBody();
$buffer = '';
while (!$body->eof()) {
$chunk = $body->read(config('gemini.stream.chunk_size', '1024'));
if (!empty($chunk)) {
$buffer .= $chunk;
$lines = explode("\n", $buffer);
$buffer = array_pop($lines); // Keep last incomplete line
foreach ($lines as $line) {
if (strpos($line, 'data: ') === 0) {
$jsonStr = substr($line, 5); // Remove 'data: ' prefix
$data = json_decode(trim($jsonStr), true);
if (json_last_error() === JSON_ERROR_NONE) {
$part = $data['candidates'][0]['content']['parts'][0] ?? [];
$callback($part);
}
}
}
}
}
} catch (\Exception $e) {
throw new StreamException(
$e->getMessage(),
$e->getCode(),
$e
);
}
}
protected function executeRequest(array $params, string $responseType)
{
$method = $params['method'] ?? 'generateContent';
$body = $this->buildRequestBody($params, $method === 'predictLongRunning', $responseType === 'Audio');
$endpoint = "/v1beta/models/{$params['model']}:" . $method;
$response = $this->http->post($endpoint, $body);
if ($method === 'predictLongRunning') {
$operation = $response->json()['name'];
do {
sleep(5);
$status = $this->http->get($operation)->json();
} while (!$status['done']);
return $this->handleResponse($this->http->get("/v1beta/".$status['response']['generatedSamples'][0][$responseType === 'Video' ? 'video' : 'uri']), $responseType);
}
// Check for error response
if (isset($response->json()['candidates'][0]['finishReason']) && $response->json()['candidates'][0]['finishReason'] != 'STOP') {
Log::error('Gemini API error response', ['response' => $response->json()]);
throw new ApiException("API request failed with finishReason: {$response->json()['candidates'][0]['finishReason']}");
}
return $this->handleResponse($response, $responseType);
}
protected function buildRequestBody(array $params, bool $forLongRunning = false, bool $forAudio = false): array
{
$method = $params['method'] ?? 'generateContent';
$isPredict = $method === 'predict' || $method === 'predictLongRunning';
if ($isPredict) {
// Structure for predict/predictLongRunning
$instance = ['prompt' => $params['prompt'] ?? ''];
if (isset($params['filePath']) && isset($params['fileType'])) {
$filePart = $params['fileType'] === 'image' ? [
'inlineData' => [
'mimeType' => $this->getMimeType($params['fileType'], $params['filePath']),
'data' => base64_encode(file_get_contents($params['filePath']))
]
] : [
'fileData' => [
'mimeType' => $this->getMimeType($params['fileType'], $params['filePath']),
'fileUri' => $this->upload($params['fileType'], $params['filePath'])
]
];
$instance = array_merge($instance, $filePart);
} elseif (isset($params['fileUri']) && isset($params['fileType'])) {
$filePart = [
'fileData' => [
'mimeType' => $params['fileType'],
'fileUri' => $params['fileUri']
]
];
$instance = array_merge($instance, $filePart);
}
$body = [
'instances' => [$instance],
'parameters' => [
'temperature' => $params['temperature'] ?? 0.7,
'maxOutputTokens' => $params['maxTokens'] ?? 1024,
],
];
if (isset($params['safetySettings'])) {
$body['parameters']['safetySettings'] = $params['safetySettings'];
}
} else {
// Structure for generateContent
if (!isset($params['prompt']) || empty($params['prompt'])) {
throw new ValidationException('Prompt is required for audio generation (TTS).');
}
$body = [
'contents' => $params['contents'] ?? [['parts' => [['text' => $params['prompt'] ?? '']]]],
'generationConfig' => [
'temperature' => $params['temperature'] ?? 0.7,
'maxOutputTokens' => $params['maxTokens'] ?? 1024,
],
'safetySettings' => $params['safetySettings'] ?? config('gemini.safety_settings'),
];
if (isset($params['filePath']) && isset($params['fileType'])) {
$filePart = $params['fileType'] === 'image' ? [
'inlineData' => [
'mimeType' => $this->getMimeType($params['fileType'], $params['filePath']),
'data' => base64_encode(file_get_contents($params['filePath']))
]
] : [
'fileData' => [
'mimeType' => $this->getMimeType($params['fileType'], $params['filePath']),
'fileUri' => $this->upload($params['fileType'], $params['filePath'])
]
];
$body['contents'][0]['parts'][] = $filePart;
} elseif (isset($params['fileUri']) && isset($params['fileType'])) {
$filePart = [
'fileData' => [
'mimeType' => $params['fileType'],
'fileUri' => $params['fileUri']
]
];
$body['contents'][0]['parts'][] = $filePart;
}
if ($forAudio) {
$body['generationConfig']['responseModalities'] = ['AUDIO'];
$speechConfig = config('gemini.default_speech_config', []);
if (isset($params['multiSpeaker']) && $params['multiSpeaker']) {
$speechConfig['multiSpeakerVoiceConfig'] = [
'speakerVoiceConfigs' => $params['speakerVoices'] ?? []
];
} else {
$speechConfig['voiceConfig'] = [
'prebuiltVoiceConfig' => [
'voiceName' => $params['voiceName'] ?? $speechConfig['voiceName'] ?? config('gemini.providers.gemini.default_speech_config.voiceName')
]
];
}
$body['generationConfig']['speechConfig'] = $speechConfig;
}
}
if (isset($params['system'])) {
$body[$isPredict ? 'parameters' : 'systemInstruction'] = ['parts' => [['text' => $params['system']]]];
}
if (isset($params['history'])) {
$body['contents'] = [['role' => 'user', 'parts' => [['text' => $params['prompt'] ?? '']]]];
$body[$isPredict ? 'instances' : 'contents'] = array_merge($params['history'], $body[$isPredict ? 'instances' : 'contents']);
}
if (isset($params['functions'])) {
$body[$isPredict ? 'parameters' : 'tools'] = ['functionDeclarations' => $params['functions']];
}
if (isset($params['structuredSchema'])) {
$body[$isPredict ? 'parameters' : 'generationConfig']['responseMimeType'] = 'application/json';
$body[$isPredict ? 'parameters' : 'generationConfig']['responseSchema'] = $params['structuredSchema'];
}
if ($forLongRunning) {
// For predictLongRunning, no additional changes needed as per docs
}
return $body;
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/BaseResponse.php | src/Responses/BaseResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
abstract class BaseResponse
{
protected array $data;
public function __construct(array $data)
{
$this->data = $data;
}
abstract public function content(): string;
public function toArray(): array
{
return $this->data;
}
public function json(): string
{
return json_encode($this->data);
}
public function model(): string
{
return $this->data['modelVersion'] ?? '';
}
public function usage(): array
{
return $this->data['usageMetadata'] ?? [];
}
public function requestId(): string
{
return $this->data['responseId'] ?? '';
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/VideoResponse.php | src/Responses/VideoResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
class VideoResponse extends BaseResponse
{
public function content(): string
{
return $this->data['video'] ?? '';
}
public function url(): string
{
return $this->data['uri'] ?? '';
}
public function save(string $path): void
{
file_put_contents($path, $this->content());
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/AudioResponse.php | src/Responses/AudioResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
use HosseinHezami\LaravelGemini\Exceptions\ApiException;
class AudioResponse extends BaseResponse
{
public function content(): string
{
if (isset($this->data['candidates'][0]['finishReason']) && $this->data['candidates'][0]['finishReason'] != 'STOP') {
$finishReason = $this->data['candidates'][0]['finishReason'] ?? 'UNKNOWN';
throw new ApiException("Failed to retrieve audio content. Finish reason: {$finishReason}");
}
return base64_decode($this->data['candidates'][0]['content']['parts'][0]['inlineData']['data']);
}
/**
* Extract audio metadata from mimeType
*/
public function getAudioMeta(): array
{
$inlineData = $this->data['candidates'][0]['content']['parts'][0]['inlineData'] ?? [];
$mime = $inlineData['mimeType'] ?? null;
// Defaults
$sampleRate = 16000;
$channels = 1;
$bitsPerSample = 16;
if ($mime && str_starts_with($mime, 'audio/L16')) {
$parts = explode(';', $mime);
foreach ($parts as $part) {
$part = trim($part);
if (str_starts_with($part, 'rate=')) {
$sampleRate = (int)substr($part, 5);
} elseif (str_starts_with($part, 'channels=')) {
$channels = (int)substr($part, 9);
}
}
}
return [
'mimeType' => $mime,
'sampleRate' => $sampleRate,
'channels' => $channels,
'bitsPerSample' => $bitsPerSample,
];
}
public function save(string $path): void
{
$raw = $this->content();
$meta = $this->getAudioMeta();
if ($meta['mimeType'] && str_starts_with($meta['mimeType'], 'audio/L16')) {
// Wrap raw PCM to WAV
$wav = $this->pcmToWav(
$raw,
$meta['sampleRate'],
$meta['channels'],
$meta['bitsPerSample']
);
file_put_contents($path, $wav);
} else {
// fallback: raw dump
file_put_contents($path, $raw);
}
}
private function pcmToWav(string $pcmData, int $sampleRate, int $channels, int $bitsPerSample): string
{
$byteRate = $sampleRate * $channels * $bitsPerSample / 8;
$blockAlign = $channels * $bitsPerSample / 8;
$dataSize = strlen($pcmData);
// WAV header
$header = pack('N4', 0x52494646, 36 + $dataSize, 0x57415645, 0x666d7420);
$header .= pack('V', 16); // Subchunk1Size
$header .= pack('v', 1); // PCM format
$header .= pack('v', $channels);
$header .= pack('V', $sampleRate);
$header .= pack('V', $byteRate);
$header .= pack('v', $blockAlign);
$header .= pack('v', $bitsPerSample);
$header .= pack('N2', 0x64617461, $dataSize);
return $header . $pcmData;
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/CacheResponse.php | src/Responses/CacheResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
class CacheResponse
{
protected array $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function toArray(): array
{
return $this->data;
}
public function name(): string
{
return $this->data['name'] ?? '';
}
public function model(): string
{
return $this->data['model'] ?? '';
}
public function createTime(): string
{
return $this->data['createTime'] ?? '';
}
public function updateTime(): string
{
return $this->data['updateTime'] ?? '';
}
public function expireTime(): string
{
return $this->data['expireTime'] ?? '';
}
public function displayName(): string
{
return $this->data['displayName'] ?? '';
}
public function usageMetadata(): array
{
return $this->data['usageMetadata'] ?? [];
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/ImageResponse.php | src/Responses/ImageResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
use HosseinHezami\LaravelGemini\Exceptions\ApiException;
class ImageResponse extends BaseResponse
{
public function content(): string
{
foreach($this->data['candidates'][0]['content']['parts'] as $parts){
if(key_exists('inlineData', $parts))
$part = $parts;
}
if(!isset($part))
throw new ApiException("Failed to retrieve image content. No inlineData found.");
return base64_decode($part['inlineData']['data']);
}
public function url(): string
{
return $this->data['uri'] ?? '';
}
public function save(string $path): void
{
file_put_contents($path, $this->content());
}
}
| php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/FileResponse.php | src/Responses/FileResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
use HosseinHezami\LaravelGemini\Exceptions\ApiException;
class FileResponse
{
protected array $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function toArray(): array
{
return $this->data;
}
public function files(): array
{
return $this->data['files'] ?? [];
}
public function name(): ?string
{
return $this->data['name'] ?? null;
}
public function uri(): ?string
{
return $this->data['uri'] ?? null;
}
public function state(): ?string
{
return $this->data['state'] ?? null;
}
public function mimeType(): ?string
{
return $this->data['mimeType'] ?? null;
}
public function displayName(): ?string
{
return $this->data['displayName'] ?? null;
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
hosseinhezami/laravel-gemini | https://github.com/hosseinhezami/laravel-gemini/blob/4ab7bae02f0cc88f3e93455e8363d9a517c6eafe/src/Responses/TextResponse.php | src/Responses/TextResponse.php | <?php
namespace HosseinHezami\LaravelGemini\Responses;
class TextResponse extends BaseResponse
{
public function content(): string
{
return $this->data['candidates'][0]['content']['parts'][0]['text'] ?? '';
}
} | php | MIT | 4ab7bae02f0cc88f3e93455e8363d9a517c6eafe | 2026-01-05T04:55:15.491730Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.