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 |
|---|---|---|---|---|---|---|---|---|
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2015_06_11_041926_add_mark_items_as_read.php | database/migrations/2015_06_11_041926_add_mark_items_as_read.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMarkItemsAsRead extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('items', function($table)
{
$table->boolean('is_mark_as_read');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('items'))
{
Schema::table('items', function($table)
{
$table->dropColumn('is_mark_as_read');
});
}
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2014_10_12_000000_create_users_table.php | database/migrations/2014_10_12_000000_create_users_table.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2014_10_12_100000_create_password_resets_table.php | database/migrations/2014_10_12_100000_create_password_resets_table.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePasswordResetsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function(Blueprint $table)
{
$table->string('email')->index();
$table->string('token')->index();
$table->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('password_resets');
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2015_06_13_190123_add_mark_item_as_favorite.php | database/migrations/2015_06_13_190123_add_mark_item_as_favorite.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMarkItemAsFavorite extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('items', function($table)
{
$table->boolean('is_mark_as_favorite');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('items'))
{
Schema::table('items', function($table)
{
$table->dropColumn('is_mark_as_favorite');
});
}
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2015_06_07_015255_create_podcasts_table.php | database/migrations/2015_06_07_015255_create_podcasts_table.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePodcastsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('podcasts', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('machine_name');
$table->string('feed_url');
$table->string('feed_thumbnail_location')->nullable();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->unique(['machine_name','user_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('podcasts');
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2015_06_13_172515_add_podcast_web_url.php | database/migrations/2015_06_13_172515_add_podcast_web_url.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddPodcastWebUrl extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('podcasts', function($table)
{
$table->string('web_url');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('podcasts'))
{
Schema::table('podcasts', function($table)
{
$table->dropColumn('web_url');
});
}
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/database/migrations/2015_06_07_220046_create_items_table.php | database/migrations/2015_06_07_220046_create_items_table.php | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration {
/**
* Setup database table for items in each podcast
*
* @return void
*/
public function up()
{
Schema::create('items', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->string('title');
$table->longText('description');
$table->string('url');
$table->string('audio_url');
$table->date('published_at');
$table->integer('podcast_id')->unsigned();
$table->foreign('podcast_id')
->references('id')
->on('podcasts')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('items');
}
}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/lang/en/passwords.php | resources/lang/en/passwords.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
"password" => "Passwords must be at least six characters and match the confirmation.",
"user" => "We can't find a user with that e-mail address.",
"token" => "This password reset token is invalid.",
"sent" => "We have e-mailed your password reset link!",
"reset" => "Your password has been reset!",
];
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/lang/en/pagination.php | resources/lang/en/pagination.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« Previous',
'next' => 'Next »',
];
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/lang/en/validation.php | resources/lang/en/validation.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
"accepted" => "The :attribute must be accepted.",
"active_url" => "The :attribute is not a valid URL.",
"after" => "The :attribute must be a date after :date.",
"alpha" => "The :attribute may only contain letters.",
"alpha_dash" => "The :attribute may only contain letters, numbers, and dashes.",
"alpha_num" => "The :attribute may only contain letters and numbers.",
"array" => "The :attribute must be an array.",
"before" => "The :attribute must be a date before :date.",
"between" => [
"numeric" => "The :attribute must be between :min and :max.",
"file" => "The :attribute must be between :min and :max kilobytes.",
"string" => "The :attribute must be between :min and :max characters.",
"array" => "The :attribute must have between :min and :max items.",
],
"boolean" => "The :attribute field must be true or false.",
"confirmed" => "The :attribute confirmation does not match.",
"date" => "The :attribute is not a valid date.",
"date_format" => "The :attribute does not match the format :format.",
"different" => "The :attribute and :other must be different.",
"digits" => "The :attribute must be :digits digits.",
"digits_between" => "The :attribute must be between :min and :max digits.",
"email" => "The :attribute must be a valid email address.",
"filled" => "The :attribute field is required.",
"exists" => "The selected :attribute is invalid.",
"image" => "The :attribute must be an image.",
"in" => "The selected :attribute is invalid.",
"integer" => "The :attribute must be an integer.",
"ip" => "The :attribute must be a valid IP address.",
"max" => [
"numeric" => "The :attribute may not be greater than :max.",
"file" => "The :attribute may not be greater than :max kilobytes.",
"string" => "The :attribute may not be greater than :max characters.",
"array" => "The :attribute may not have more than :max items.",
],
"mimes" => "The :attribute must be a file of type: :values.",
"min" => [
"numeric" => "The :attribute must be at least :min.",
"file" => "The :attribute must be at least :min kilobytes.",
"string" => "The :attribute must be at least :min characters.",
"array" => "The :attribute must have at least :min items.",
],
"not_in" => "The selected :attribute is invalid.",
"numeric" => "The :attribute must be a number.",
"regex" => "The :attribute format is invalid.",
"required" => "The :attribute field is required.",
"required_if" => "The :attribute field is required when :other is :value.",
"required_with" => "The :attribute field is required when :values is present.",
"required_with_all" => "The :attribute field is required when :values is present.",
"required_without" => "The :attribute field is required when :values is not present.",
"required_without_all" => "The :attribute field is required when none of :values are present.",
"same" => "The :attribute and :other must match.",
"size" => [
"numeric" => "The :attribute must be :size.",
"file" => "The :attribute must be :size kilobytes.",
"string" => "The :attribute must be :size characters.",
"array" => "The :attribute must contain :size items.",
],
"unique" => "The :attribute has already been taken.",
"url" => "The :attribute format is invalid.",
"timezone" => "The :attribute must be a valid zone.",
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/app.blade.php | resources/views/app.blade.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>Podcast</title>
<link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
<link href="{{ asset('/css/app.css') }}" rel="stylesheet">
<!-- Fonts -->
<!-- HTML5 shim and Respond.js for 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/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Podcast</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
@if (Auth::check())
<li><a href="{{ url('/podcast/manage') }}">Manage Feeds</a></li>
<li><a href="{{ url('/podcast/favorites') }}">Favorites</a></li>
<li><a href="{{ url('/podcast/player') }}">Listen</a></li>
{!! Form::open(['url' => '/item/search', 'method' => 'get', 'class' => 'navbar-form navbar-left', 'role' => 'search']) !!}
<div class="form-group">
{!! Form::text('query', null, ['class' => 'form-control', 'placeholder' => 'Search ...']) !!}
</div>
{!! Form::close() !!}
@endif
</ul>
<ul class="nav navbar-nav navbar-right">
@if (Auth::guest())
<li><a href="{{ url('/auth/login') }}">Login</a></li>
<li><a href="{{ url('/auth/register') }}">Register</a></li>
@else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ Auth::user()->name }} <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="{{ url('/auth/logout') }}">Logout</a></li>
</ul>
</li>
@endif
</ul>
</div>
</div>
</nav>
@yield('content')
<!-- Scripts -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
@yield('js-footer')
</body>
</html>
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/auth/reset.blade.php | resources/views/auth/reset.blade.php | @extends('app')
@section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/password/reset') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/auth/login.blade.php | resources/views/auth/login.blade.php | @extends('app')
@section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Login</button>
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/auth/register.blade.php | resources/views/auth/register.blade.php | @extends('app')
@section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/register') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" value="{{ old('name') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/auth/password.blade.php | resources/views/auth/password.blade.php | @extends('app')
@section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/password/email') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/errors/503.blade.php | resources/views/errors/503.blade.php | <html>
<head>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
</div>
</div>
</body>
</html>
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/emails/password.blade.php | resources/views/emails/password.blade.php | Click here to reset your password: {{ url('password/reset/'.$token) }}
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/podcasts/settings.blade.php | resources/views/podcasts/settings.blade.php | @extends('app')
@section('content')
<div class="container-fluid main container-podcast-settings">
<div class="col-md-8">
<h3>Settings</h3>
<hr/>
</div>
</div>
@stop | php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/podcasts/favorites.blade.php | resources/views/podcasts/favorites.blade.php | @extends('app')
@section('content')
@if($items)
<div id="player-container" class="container-fluid">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="now-playing">
<h4 class="podcast-item-title"></h4>
</div>
<audio id='player' controls preload="none">
<source src="" type="audio/mpeg">
</audio>
</div>
<div class="col-md-3"></div>
</div>
@endif
<div class="main container-fluid container-podcast-list">
<div class="col-md-3"></div>
<div class="col-md-6">
@if($items)
@foreach ($items as $item)
<div class="row podcast-item-row">
<div class="col-md-3 podcast-thumbnail-container">
<img class="podcast-thumbnail" width="100" height="100"
src="{{asset(App\Item::find($item->id)->podcast->feed_thumbnail_location)}}" />
<p><small>{{ date_format(date_create($item->published_at),'jS M Y') }}</small></p>
</div>
<div class="col-md-9">
<h4 class="podcast-title"><small>{{App\Item::find($item->id)->podcast->name}}</small></h4>
<h3 class="podcast-item-title">
<a target="_blank" href="{{ $item->url }}">{{ $item->title }}</a>
</h3>
<p class="podcast-item-description">{{ $item->description}}
<br/>
<a class="read-more" target="_blank" href="{{ $item->url }}"><small>Read More</small></a>
</p>
<div class="player-action-list">
<ul class="list-inline">
<li class="mark-as-favorite" data-src="{{$item->id}}">
@if($item->is_mark_as_favorite)
<img width="24" height="24" alt="favorited" src="{{asset('css/icons/ic_favorite_white_36dp.png')}}" /> <span>Favorited</span>
@else
<img width="24" height="24" alt="mark as favorite" src="{{asset('css/icons/ic_favorite_grey600_36dp.png')}}" /> <span>Mark as Fav</span>
@endif
</li>
<li class='play' data-src='{{ $item->audio_url}}'>
<img width="24" height="24" alt="play" src="{{asset('css/icons/ic_play_circle_filled_white_36dp.png')}}" /> <span>Play</span>
</li>
</ul>
</div>
</div>
</div>
@endforeach
@if($items)
<div class="row container-fluid">
<?php echo $items->render()?>
</div>
@endif
@endif
</div>
<div class="col-md-3">
</div>
</div>
@section('js-footer')
<script>
jQuery(document).ready(function($) {
$('.podcast-item-row .play').on('click', function() {
$('#player-container').css('display','block');
$('#player source').attr('src', $(this).attr('data-src'));
$('#player').trigger('load').trigger('play');
$('#player-container .now-playing .podcast-item-title').text(
'Now playing - ' +
$(this).parents('.podcast-item-row').find('.podcast-item-title > a').text());
$('.podcast-item-row').removeClass('active');
$(this).parents('.podcast-item-row').addClass('active');
});
});
$('.mark-as-favorite').on('click', function() {
var itemId = $(this).attr('data-src');
$.ajax({
type: "POST",
cache: false,
url: "/item/mark-as-favorite",
data: {
'itemId': itemId,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
// change fav img
if(result.currentValue === true)
{
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_white_36dp.png')}}');
$(".mark-as-favorite[data-src=" + itemId + "] span").text('Favorited');
} else {
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_grey600_36dp.png')}}');
$(".mark-as-favorite[data-src=" + itemId + "] span").text('Mark as Fav');
}
}
}
});
});
</script>
@endsection
@endsection | php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/podcasts/manage.blade.php | resources/views/podcasts/manage.blade.php | @extends('app')
@section('content')
<div class="container-fluid main container-podcast-manage">
<div class="col-md-9">
<h3 class="page-title">Manage Podcast Feeds</h3>
<hr/>
@if(DB::table('podcasts')->where('user_id','=',Auth::user()->id)->count() > 0)
@foreach(DB::table('podcasts')->where('user_id','=',Auth::user()->id)->get() as $cast)
<div class="col-md-4">
<div class="podcast-container">
<span class="podcast-added-on">Added on {{ date('F d, Y', strtotime($cast->created_at)) }}</span>
<h4 class="podcast-title">{{$cast->name}}</h4>
<a target="_blank" href="{{$cast->web_url}}">
<img class="podcast-thumbnail" width="100" height="100"
src="{{asset($cast->feed_thumbnail_location)}}" />
</a>
<br/>
<div class="podcast-action-list">
<ul class="list-inline">
<li class='feed-delete' data-feed-machine-name="{{$cast->machine_name}}">
<img width="20" height="20" alt="Delete"
src="{{asset('css/icons/ic_clear_white_36dp.png')}}" /> Delete
</li>
</ul>
</div>
</div>
</div>
@endforeach
@endif
</div>
<div class="row container-fluid">
<div class="col-md-6">
<h4 class="section-title">Add a podcast feed</h4>
{!! Form::model($podcast = new \App\Podcast, ['method' =>'POST','action' => ['PodcastController@add']]) !!}
<div class="form-group">
{!! Form::text('feed_url', null,
['class' => 'form-control','required','placeholder' => 'Enter a Podcast Feed Url here: http://example.com/feed']) !!}
</div>
<div class="form-group">
{!! Form::submit('Add Feed', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
@stop
@section('js-footer')
<script>
jQuery(document).ready(function($) {
$('.feed-delete').on('click', function() {
if (confirm('Are you sure you want to delete this feed?')) {
var feedMachineName = $.trim($(this).attr('data-feed-machine-name'));
$.ajax({
type: "POST",
cache: false,
url: "/podcast/delete",
data: {
'feedMachineName': feedMachineName,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
location.reload(); // @todo add a response msg
}
}
});
}
});
});
</script>
@stop
| php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/podcasts/list.blade.php | resources/views/podcasts/list.blade.php | @extends('app')
@section('content')
@if($items)
<div id="player-container" class="container-fluid">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="now-playing">
<h4 class="podcast-item-title"></h4>
</div>
<audio id='player' controls preload="none">
<source src="" type="audio/mpeg">
</audio>
</div>
<div class="col-md-3"></div>
</div>
@endif
<div class="main container-fluid container-podcast-list">
<div class="col-md-2"></div>
<div class="col-md-8">
@if($items)
@foreach ($items as $item)
<div class="row podcast-item-row">
<div class="col-md-3 podcast-thumbnail-container">
<img class="podcast-thumbnail" width="100" height="100"
src="{{asset(App\Item::find($item->id)->podcast->feed_thumbnail_location)}}" />
<p><small>{{ date_format(date_create($item->published_at),'jS M Y') }}</small></p>
</div>
<div class="col-md-9">
<h4 class="podcast-title"><small>{{App\Item::find($item->id)->podcast->name}}</small></h4>
<h3 class="podcast-item-title">
<a target="_blank" href="{{ $item->url }}">{{ $item->title }}</a>
</h3>
<p class="podcast-item-description">{{ $item->description}}
<br/>
<a class="read-more" target="_blank" href="{{ $item->url }}"><small>Read More</small></a>
</p>
<div class="player-action-list">
<ul class="list-inline">
<li class='play' data-src='{{ $item->audio_url}}'>
<img width="24" height="24" title="Play" alt="Play" src="{{asset('css/icons/ic_play_circle_filled_white_36dp.png')}}" />
</li>
<li class="mark-as-favorite" data-src="{{$item->id}}">
@if($item->is_mark_as_favorite)
<img alt="Remove from favorites" title="Remove from favorites" width="24" height="24" alt="favorited" src="{{asset('css/icons/ic_favorite_white_36dp.png')}}" />
@else
<img width="24" height="24" title="Mark as favorite" alt="Mark as favorite" src="{{asset('css/icons/ic_favorite_grey600_36dp.png')}}" />
@endif
</li>
<li class="mark-as-read" data-src="{{$item->id}}">
<img width="24" height="24" title="Mark as read" alt="Mark as read" src="{{asset('css/icons/ic_done_white_36dp.png')}}" />
</li>
<li class="mark-all-prev-read" data-src="{{$item->id}}">
<img width="24" height="24" title="Mark all previous as read" alt="Mark all previous as read" src="{{asset('css/icons/ic_done_all_white_36dp.png')}}" />
</li>
<li class='download'>
<a href='{{ $item->audio_url}}' download='{{ $item->audio_url}}'>
<img width="24" height="24" title="Download" alt="Download" src="{{asset('css/icons/ic_file_download_white_36dp.png')}}" />
</a>
</li>
</ul>
</div>
</div>
</div>
@endforeach
@if($items)
<div class="row container-fluid">
<?php echo $items->render()?>
</div>
@endif
@else
<p class="text-white">Please <a href="{{ url('/podcast/manage') }}">add a feed</a> to view podcasts here...</p>
@endif
</div>
<div class="col-md-2">
</div>
</div>
@section('js-footer')
<script>
jQuery(document).ready(function($) {
$('.podcast-item-row .play').on('click', function() {
$('#player-container').css('display','block');
$('#player source').attr('src', $(this).attr('data-src'));
$('#player').trigger('load').trigger('play');
$('#player-container .now-playing .podcast-item-title').text(
'Now playing - ' +
$(this).parents('.podcast-item-row').find('.podcast-item-title > a').text());
$('.podcast-item-row').removeClass('active');
$(this).parents('.podcast-item-row').addClass('active');
});
});
$('.mark-as-read').on('click', function() {
if (confirm('Are you sure you want to mark this as read?')) {
var itemId = $(this).attr('data-src');
var itemRow = $(".mark-as-read[data-src=" + itemId + "]").parents(".podcast-item-row");
$.ajax({
type: "POST",
cache: false,
url: "/item/mark-as-read",
data: {
'itemId': itemId,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
$(itemRow).fadeOut(1000);
}
}
});
}
});
$('.mark-as-favorite').on('click', function() {
var itemId = $(this).attr('data-src');
$.ajax({
type: "POST",
cache: false,
url: "/item/mark-as-favorite",
data: {
'itemId': itemId,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
// change fav img
if(result.currentValue === true)
{
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_white_36dp.png')}}').attr('title', 'Remove from Favorites');
} else {
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_grey600_36dp.png')}}').attr('title', 'Add to Favorites');
}
}
}
});
});
$('.mark-all-prev-read').on('click', function() {
if (confirm('Are you sure you want to mark all previous episodes in this podcast as read?')) {
var itemId = $(this).attr('data-src');
$.ajax({
type: "POST",
cache: false,
url: "/item/mark-all-prev-read",
data: {
'itemId': itemId,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
for(var i = 0; i < result.data.length; i++)
{
if($(".mark-all-prev-read[data-src=" + result.data[i] + "]"))
{
$(".mark-all-prev-read[data-src=" + result.data[i] + "]")
.parents(".podcast-item-row")
.fadeOut(1000);
}
}
}
}
});
}
});
</script>
@endsection
@endsection | php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
Srikanth-AD/Podcastwala | https://github.com/Srikanth-AD/Podcastwala/blob/9444ad9fddbd6999606c8828345f871b8bff6348/resources/views/items/searchresults.blade.php | resources/views/items/searchresults.blade.php | @extends('app')
@section('content')
@if($items)
<div id="player-container" class="container-fluid">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="now-playing">
<h4 class="podcast-item-title"></h4>
</div>
<audio id='player' controls preload="none">
<source src="" type="audio/mpeg">
</audio>
</div>
<div class="col-md-3"></div>
</div>
@endif
<div class="main container-fluid container-podcast-list">
<div class="col-md-3"></div>
<div class="col-md-6">
@if($items)
@foreach ($items as $item)
<div class="row podcast-item-row">
<div class="col-md-3 podcast-thumbnail-container">
<img class="podcast-thumbnail" width="100" height="100"
src="{{asset(App\Item::find($item->id)->podcast->feed_thumbnail_location)}}" />
<p><small>{{ date_format(date_create($item->published_at),'jS M Y') }}</small></p>
</div>
<div class="col-md-9">
<h4 class="podcast-title"><small>{{App\Item::find($item->id)->podcast->name}}</small></h4>
<h3 class="podcast-item-title">
<a target="_blank" href="{{ $item->url }}">{{ $item->title }}</a>
</h3>
<p class="podcast-item-description">{{ $item->description}}
<br/>
<a class="read-more" target="_blank" href="{{ $item->url }}"><small>Read More</small></a>
</p>
<div class="player-action-list">
<ul class="list-inline">
<li class="mark-as-favorite" data-src="{{$item->id}}">
@if($item->is_mark_as_favorite)
<img width="24" height="24" alt="favorited" src="{{asset('css/icons/ic_favorite_white_36dp.png')}}" /> <span>Favorited</span>
@else
<img width="24" height="24" alt="mark as favorite" src="{{asset('css/icons/ic_favorite_grey600_36dp.png')}}" /> <span>Mark as Fav</span>
@endif
</li>
<li class='play' data-src='{{ $item->audio_url}}'>
<img width="24" height="24" alt="play" src="{{asset('css/icons/ic_play_circle_filled_white_36dp.png')}}" /> <span>Play</span>
</li>
</ul>
</div>
</div>
</div>
@endforeach
@endif
</div>
<div class="col-md-3">
</div>
</div>
@section('js-footer')
<script>
jQuery(document).ready(function($) {
$('.podcast-item-row .play').on('click', function() {
$('#player-container').css('display','block');
$('#player source').attr('src', $(this).attr('data-src'));
$('#player').trigger('load').trigger('play');
$('#player-container .now-playing .podcast-item-title').text(
'Now playing - ' +
$(this).parents('.podcast-item-row').find('.podcast-item-title > a').text());
$('.podcast-item-row').removeClass('active');
$(this).parents('.podcast-item-row').addClass('active');
});
});
$('.mark-as-favorite').on('click', function() {
var itemId = $(this).attr('data-src');
$.ajax({
type: "POST",
cache: false,
url: "/item/mark-as-favorite",
data: {
'itemId': itemId,
'_token': "{{ csrf_token() }}"
},
success: function(result) {
if(result.status === 1)
{
// change fav img
if(result.currentValue === true)
{
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_white_36dp.png')}}');
$(".mark-as-favorite[data-src=" + itemId + "] span").text('Favorited');
} else {
$(".mark-as-favorite[data-src=" + itemId + "]").find('img').attr('src','{{asset('css/icons/ic_favorite_grey600_36dp.png')}}');
$(".mark-as-favorite[data-src=" + itemId + "] span").text('Mark as Fav');
}
}
}
});
});
</script>
@endsection
@endsection | php | MIT | 9444ad9fddbd6999606c8828345f871b8bff6348 | 2026-01-05T04:39:48.576378Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/bootstrap.php | tests/bootstrap.php | <?php
error_reporting(E_ALL | E_STRICT);
// Ensure that composer has installed all dependencies
if (!file_exists(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'composer.lock')) {
die("Dependencies must be installed using composer:\n\nphp composer.phar install --dev\n\n"
. "See http://getcomposer.org for help with installing composer\n");
}
// Include the Composer autoloader
include realpath(dirname(__FILE__) . '/../vendor/autoload.php');
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Mongo/PhactoryTest.php | tests/Phactory/Mongo/PhactoryTest.php | <?php
namespace Phactory\Mongo;
class PhactoryTest extends \PHPUnit_Framework_TestCase
{
protected $db;
protected $phactory;
protected function setUp()
{
$this->mongo = new \Mongo();
$this->db = $this->mongo->testdb;
$this->phactory = new Phactory($this->db);
}
protected function tearDown()
{
$this->phactory->reset();
$this->db->users->drop();
$this->db->roles->drop();
$this->mongo->close();
}
public function testSetDb()
{
$mongo = new \Mongo();
$db = $mongo->testdb;
$this->phactory->setDb($db);
$db = $this->phactory->getDb();
$this->assertInstanceOf('MongoDB', $db);
}
public function testGetDb()
{
$db = $this->phactory->getDb();
$this->assertInstanceOf('MongoDB', $db);
}
public function testDefine()
{
// test that define() doesn't throw an exception when called correctly
$this->phactory->define('user', array('name' => 'testuser'));
}
public function testDefineWithBlueprint()
{
$blueprint = new Blueprint('user', array('name' => 'testuser'), array(), $this->phactory);
$this->phactory->define('user', $blueprint);
$user = $this->phactory->create('user');
$this->assertEquals('testuser', $user['name']);
}
public function testDefineWithAssociations()
{
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->embedsOne('role')));
}
public function testCreate()
{
$name = 'testuser';
$tags = array('one','two','three');
// define and create user in db
$this->phactory->define('user', array('name' => $name, 'tags' => $tags));
$user = $this->phactory->create('user');
// test returned array
$this->assertInternalType('array', $user);
$this->assertEquals($user['name'], $name);
$this->assertEquals($user['tags'], $tags);
// retrieve and test expected document from database
$db_user = $this->db->users->findOne();
$this->assertEquals($name, $db_user['name']);
$this->assertEquals($tags, $db_user['tags']);
}
public function testCreateWithOverrides()
{
$name = 'testuser';
$override_name = 'override_user';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user', array('name' => $override_name));
// test returned array
$this->assertInternalType('array', $user);
$this->assertEquals($user['name'], $override_name);
// retrieve and test expected document from database
$db_user = $this->db->users->findOne();
$this->assertEquals($db_user['name'], $override_name);
}
public function testCreateWithAssociations()
{
$this->phactory->define('role',
array('name' => 'admin'));
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->embedsOne('role')));
$role = $this->phactory->build('role');
$user = $this->phactory->createWithAssociations('user', array('role' => $role));
$this->assertEquals($role['name'], $user['role']['name']);
}
public function testCreateWithEmbedsManyAssociation() {
$this->phactory->define('tag',
array('name' => 'Test Tag'));
$this->phactory->define('blog',
array('title' => 'Test Title'),
array('tags' => $this->phactory->embedsMany('tag')));
$tag = $this->phactory->build('tag');
$blog = $this->phactory->createWithAssociations('blog', array('tags' => array($tag)));
$this->assertEquals('Test Tag', $blog['tags'][0]['name']);
$this->db->blogs->drop();
}
public function testDefineAndCreateWithSequence()
{
$tags = array('foo$n','bar$n');
$this->phactory->define('user', array('name' => 'user\$n', 'tags' => $tags));
for($i = 0; $i < 5; $i++) {
$user = $this->phactory->create('user');
$this->assertEquals("user$i", $user['name']);
$this->assertEquals(array("foo$i","bar$i"),$user['tags']);
}
}
public function testGet()
{
$name = 'testuser';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user');
// get() expected row from database
$db_user = $this->phactory->get('user', array('name' => $name));
// test retrieved db row
$this->assertInternalType('array', $db_user);
$this->assertEquals($name, $db_user['name']);
}
public function testRecall()
{
$name = 'testuser';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user');
// recall() deletes from the db
$this->phactory->recall();
// test that the object is gone from the db
$db_user = $this->db->users->findOne();
$this->assertNull($db_user);
// test that the blueprints weren't destroyed too
$user = $this->phactory->create('user');
$this->assertEquals($user['name'], $name);
}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/InflectorTest.php | tests/Phactory/Sql/InflectorTest.php | <?php
namespace Phactory\Sql;
/**
* Test class for Phactory_Inflector.
*/
class InflectorTest extends \PHPUnit_Framework_TestCase
{
public function setUp() {
}
public function tearDown() {
Inflector::reset();
}
public function inflectionProvider() {
return array(
array('test', 'tests'),
array('octopus', 'octopi'),
array('fish', 'fish'),
array('user', 'users'));
}
public function inflectionExceptionProvider() {
return array(
array('fish', 'fishes'),
array('content', 'content'),
array('anecdote', 'data'));
}
/**
* @dataProvider inflectionProvider
*/
public function testPluralize($singular, $plural) {
$this->assertEquals(Inflector::pluralize($singular), $plural);
}
/**
* @dataProvider inflectionExceptionProvider
*/
public function testAddException($singular, $plural) {
$this->assertNotEquals(Inflector::pluralize($singular), $plural);
Inflector::addException($singular, $plural);
$this->assertEquals(Inflector::pluralize($singular), $plural);
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/BlueprintTest.php | tests/Phactory/Sql/BlueprintTest.php | <?php
namespace Phactory\Sql;
class BlueprintTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO("sqlite:test.db");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("CREATE TABLE `users` ( name VARCHAR(256) )");
$this->phactory = new Phactory($this->pdo);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->phactory->reset();
$this->pdo->exec("DROP TABLE `users`");
}
public function testCreate()
{
$name = 'testuser';
//create Phactory\Sql\Blueprint object and a new Phactory_Row object
$phactory_blueprint = new Blueprint('user', array('name' => $name), array(), $this->phactory);
$phactory_row = $phactory_blueprint->create();
//test $phactory_row is of type Phactory\Sql\Row and that object stored name correctly
$this->assertInstanceOf('Phactory\Sql\Row', $phactory_row);
$this->assertEquals($phactory_row->name, $name);
}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/PhactoryTest.php | tests/Phactory/Sql/PhactoryTest.php | <?php
namespace Phactory\Sql;
class PhactoryTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO("sqlite:test.db");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("CREATE TABLE `users` ( id INTEGER PRIMARY KEY, name TEXT, role_id INTEGER )");
$this->pdo->exec("CREATE TABLE `roles` ( id INTEGER PRIMARY KEY, name TEXT )");
$this->pdo->exec("CREATE TABLE blogs ( id INTEGER PRIMARY KEY, title TEXT )");
$this->pdo->exec("CREATE TABLE tags ( id INTEGER PRIMARY KEY, name TEXT )");
$this->pdo->exec("CREATE TABLE blogs_tags ( blog_id INTEGER, tag_id INTEGER )");
$this->phactory = new Phactory($this->pdo);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->phactory->reset();
$this->pdo->exec("DROP TABLE `users`");
$this->pdo->exec("DROP TABLE `roles`");
$this->pdo->exec("DROP TABLE blogs");
$this->pdo->exec("DROP TABLE tags");
$this->pdo->exec("DROP TABLE blogs_tags");
}
public function testSetConnection()
{
$pdo = new \PDO("sqlite:test.db");
$this->phactory->setConnection($pdo);
$pdo = $this->phactory->getConnection();
$this->assertInstanceOf('PDO', $pdo);
}
public function testGetConnection()
{
$pdo = $this->phactory->getConnection();
$this->assertInstanceOf('PDO', $pdo);
}
public function testDefine()
{
// test that define() doesn't throw an exception when called correctly
$this->phactory->define('user', array('name' => 'testuser'));
// define should only require one argument - the blueprint name
$this->phactory->define('user');
}
public function testDefineWithBlueprint()
{
$blueprint = new Blueprint('user', array('name' => 'testuser'), array(), $this->phactory);
$this->phactory->define('user', $blueprint);
$user = $this->phactory->create('user');
$this->assertEquals('testuser', $user->name);
}
public function testDefineWithAssociations()
{
// define with explicit $to_column
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->manyToOne('roles', 'role_id', 'id')));
// definie with implicit $to_column
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->manyToOne('roles', 'role_id')));
}
public function testBuild()
{
$name = 'testuser';
// define and build user
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->build('user');
// test returned Phactory\Sql\Row
$this->assertInstanceOf('Phactory\Sql\Row', $user);
$this->assertEquals($user->name, $name);
}
public function testBuildWithOverrides()
{
$name = 'testuser';
$override_name = 'override_user';
// define and build user
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->build('user', array('name' => $override_name));
// test returned Phactory\Sql\Row
$this->assertInstanceOf('Phactory\Sql\Row', $user);
$this->assertEquals($override_name, $user->name);
}
public function testBuildWithAssociations()
{
$this->phactory->define('role',
array('name' => 'admin'));
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->manyToOne('role', 'role_id')));
$role = $this->phactory->create('role');
$user = $this->phactory->buildWithAssociations('user', array('role' => $role));
$this->assertNotNull($role->id);
$this->assertEquals($role->id, $user->role_id);
}
public function testCreate()
{
$name = 'testuser';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user');
// test returned Phactory\Sql\Row
$this->assertInstanceOf('Phactory\Sql\Row', $user);
$this->assertEquals($user->name, $name);
// retrieve expected row from database
$stmt = $this->pdo->query("SELECT * FROM `users`");
$db_user = $stmt->fetch();
// test retrieved db row
$this->assertEquals($db_user['name'], $name);
}
public function testCreateWithOverrides()
{
$name = 'testuser';
$override_name = 'override_user';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user', array('name' => $override_name));
// test returned Phactory\Sql\Row
$this->assertInstanceOf('Phactory\Sql\Row', $user);
$this->assertEquals($user->name, $override_name);
// retrieve expected row from database
$stmt = $this->pdo->query("SELECT * FROM `users`");
$db_user = $stmt->fetch();
// test retrieved db row
$this->assertEquals($db_user['name'], $override_name);
}
public function testCreateWithAssociations()
{
$this->phactory->define('role',
array('name' => 'admin'));
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->manyToOne('role', 'role_id')));
$role = $this->phactory->create('role');
$user = $this->phactory->createWithAssociations('user', array('role' => $role));
$this->assertNotNull($role->id);
$this->assertEquals($role->id, $user->role_id);
}
public function testCreateWithAssociationsGuessingFromColumn()
{
$this->phactory->define('role',
array('name' => 'admin'));
$this->phactory->define('user',
array('name' => 'testuser'),
array('role' => $this->phactory->manyToOne('role')));
$role = $this->phactory->create('role');
$user = $this->phactory->createWithAssociations('user', array('role' => $role));
$this->assertNotNull($role->id);
$this->assertEquals($role->id, $user->role_id);
}
public function testCreateWithManyToManyAssociation() {
$this->phactory->define('tag',
array('name' => 'Test Tag'));
$this->phactory->define('blog',
array('title' => 'Test Title'),
array('tag' => $this->phactory->manyToMany('tags', 'blogs_tags', 'id', 'blog_id', 'tag_id', 'id')));
$tag = $this->phactory->create('tag');
$blog = $this->phactory->createWithAssociations('blog', array('tag' => $tag));
$result = $this->pdo->query("SELECT * FROM blogs_tags");
$row = $result->fetch();
$result->closeCursor();
$this->assertNotEquals(false, $row);
$this->assertEquals($blog->getId(), $row['blog_id']);
$this->assertEquals($tag->getId(), $row['tag_id']);
}
public function testCreateWithManyToManyAssociations() {
$this->phactory->define('tag',
array('name' => 'Test Tag'));
$this->phactory->define('blog',
array('title' => 'Test Title'),
array('tags' => $this->phactory->manyToMany('tags', 'blogs_tags', 'id', 'blog_id', 'tag_id', 'id')));
$tags = array($this->phactory->create('tag'), $this->phactory->create('tag'));
$blog = $this->phactory->createWithAssociations('blog', array('tags' => $tags));
$result = $this->pdo->query("SELECT * FROM blogs_tags");
foreach($tags as $tag) {
$row = $result->fetch();
$this->assertNotEquals(false, $row);
$this->assertEquals($blog->getId(), $row['blog_id']);
$this->assertEquals($tag->getId(), $row['tag_id']);
}
$result->closeCursor();
}
public function testDefineAndCreateWithSequence()
{
$this->phactory->define('user', array('name' => 'user$n'));
for($i = 0; $i < 5; $i++) {
$user = $this->phactory->create('user');
$this->assertEquals("user$i", $user->name);
}
}
public function testGet()
{
$data = array('id' => 1, 'name' => 'testname', 'role_id' => null);
$this->phactory->define('user', $data);
$this->phactory->create('user');
$user = $this->phactory->get('user', array('id' => 1));
$this->assertEquals($data, $user->toArray());
$this->assertInstanceOf('Phactory\Sql\Row', $user);
}
public function testGetAll()
{
$name = 'testuser';
// define and create users in db
$this->phactory->define('user', array('name' => $name));
$users = array($this->phactory->create('user'), $this->phactory->create('user'));
// get expected rows from database
$db_users = $this->phactory->getAll('user', array('name' => $name));
// test retrieved db rows
$this->assertEquals(2, count($db_users));
$this->assertEquals($name, $db_users[0]->name);
$this->assertEquals($name, $db_users[1]->name);
$this->assertInstanceOf('Phactory\Sql\Row', $db_users[0]);
}
public function testGetMultiAttributes()
{
$name = 'testuser';
$role_id = 2;
// define and create user in db
$this->phactory->define('user', array('name' => $name, 'role_id' => $role_id));
$user = $this->phactory->create('user');
// create 2nd user which shouldn't be returned
$this->phactory->create('user', array('name' => 'user2', 'role_id' => $role_id));
// get() expected row from database
$db_user = $this->phactory->get('user', array('name' => $name, 'role_id' => $role_id));
// test retrieved db row
$this->assertEquals($name, $db_user->name);
$this->assertEquals($role_id, $db_user->role_id);
$this->assertInstanceOf('Phactory\Sql\Row', $db_user);
}
public function testRecall()
{
$name = 'testuser';
// define and create user in db
$this->phactory->define('user', array('name' => $name));
$user = $this->phactory->create('user');
// recall() deletes from the db
$this->phactory->recall();
// test that the object is gone from the db
$stmt = $this->pdo->query("SELECT * FROM `users`");
$db_user = $stmt->fetch();
$this->assertFalse($db_user);
// test that the blueprints weren't destroyed too
$user = $this->phactory->create('user');
$this->assertEquals($user->name, $name);
}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/RowTest.php | tests/Phactory/Sql/RowTest.php | <?php
namespace Phactory\Sql;
class RowTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO("sqlite:test.db");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->exec("CREATE TABLE `users` ( id INTEGER PRIMARY KEY, name TEXT )");
$this->phactory = new Phactory($this->pdo);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->phactory->reset();
$this->pdo->exec("DROP TABLE `users`");
}
public function testGetId()
{
$row = new Row('user', array('name' => 'testuser'), $this->phactory);
$row->save();
$this->assertEquals($row->getId(), $row->id);
}
public function testSave()
{
$name = "testuser";
//create Phactory\Sql\Row object and add user to table
$phactory_row = new Row('user', array('name' => $name), $this->phactory);
$phactory_row->save();
// retrieve expected user from database
$stmt = $this->pdo->query("SELECT * FROM `users`");
$db_user = $stmt->fetch();
// test retrieved db row
$this->assertEquals($db_user['name'], $name);
}
public function testToArray()
{
$data = array('name' => 'testname');
$row = new Row('user', $data, $this->phactory);
$arr = $row->toArray();
$this->assertEquals($data, $arr);
//changing the returned array shouldn't change the row
$arr['name'] = 'foo';
$this->assertNotEquals($row->name, $arr['name']);
}
public function testToArrayAfterCreate()
{
$data = array('id' => 1, 'name' => 'testname');
$this->phactory->define('user', $data);
$user = $this->phactory->create('user');
$this->assertEquals($data, $user->toArray());
}
public function testFill()
{
$data = array('id' => 1);
$row = new Row('user', $data, $this->phactory);
$arr = $row->toArray();
$this->assertEquals($data, $arr);
$data['name'] = null;
$arr = $row->fill()->toArray();
$this->assertEquals($data, $arr);
}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/DbUtil/SqliteUtilTest.php | tests/Phactory/Sql/DbUtil/SqliteUtilTest.php | <?php
namespace Phactory\Sql\DbUtil;
use Phactory\Sql\Phactory;
class SqliteUtilTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO('sqlite:test.db');
$this->phactory = new Phactory($this->pdo);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
$this->pdo->exec("DROP TABLE test_table");
}
public function testGetPrimaryKey()
{
$this->pdo->exec("CREATE TABLE test_table ( id INTEGER PRIMARY KEY, name TEXT )");
$db_util = new SqliteUtil($this->phactory);
$pk = $db_util->getPrimaryKey('test_table');
$this->assertEquals('id', $pk);
}
public function testGetColumns() {
$this->pdo->exec("CREATE TABLE test_table ( id INTEGER PRIMARY KEY, name TEXT, email TEXT, age INTEGER )");
$db_util = new SqliteUtil($this->phactory);
$columns = $db_util->getColumns('test_table');
$this->assertEquals(array('id', 'name', 'email', 'age'), $columns);
}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/Association/ManyToManyTest.php | tests/Phactory/Sql/Association/ManyToManyTest.php | <?php
namespace Phactory\Sql\Association;
use Phactory\Sql\Phactory;
use Phactory\Sql\Table;
class ManyToManyTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO("sqlite:test.db");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->phactory = new Phactory($this->pdo);
$this->pdo->exec("CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT )");
$this->pdo->exec("CREATE TABLE images ( id INTEGER PRIMARY KEY, filename TEXT)");
$this->pdo->exec("CREATE TABLE users_images ( user_id INTEGER, image_id INTEGER)");
}
protected function tearDown()
{
$this->phactory->reset();
$this->pdo->exec("DROP TABLE users");
$this->pdo->exec("DROP TABLE images");
$this->pdo->exec("DROP TABLE users_images");
}
public function testGuessFromColumn()
{
$assoc = new ManyToMany(new Table('image', true, $this->phactory), new Table('users_images', false, $this->phactory));
$assoc->setFromTable(new Table('user', true, $this->phactory));
$this->assertEquals('id', $assoc->getFromColumn());
$this->assertEquals('user_id', $assoc->getFromJoinColumn());
$this->assertEquals('image_id', $assoc->getToJoinColumn());
$this->assertEquals('id', $assoc->getToColumn());
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/tests/Phactory/Sql/Association/ManyToOneTest.php | tests/Phactory/Sql/Association/ManyToOneTest.php | <?php
namespace Phactory\Sql\Association;
use Phactory\Sql\Phactory;
use Phactory\Sql\Table;
class ManyToOneTest extends \PHPUnit_Framework_TestCase
{
protected $pdo;
protected $phactory;
protected function setUp()
{
$this->pdo = new \PDO("sqlite:test.db");
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->phactory = new Phactory($this->pdo);
$this->pdo->exec("CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT )");
$this->pdo->exec("CREATE TABLE posts ( id INTEGER PRIMARY KEY, name TEXT, user_id INTEGER )");
}
protected function tearDown()
{
$this->phactory->reset();
$this->pdo->exec("DROP TABLE users");
$this->pdo->exec("DROP TABLE posts");
}
public function testGuessFromColumn()
{
$assoc = new ManyToOne(new Table('user', true, $this->phactory));
$assoc->setFromTable(new Table('post', true, $this->phactory));
$this->assertEquals('user_id', $assoc->getFromColumn());
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/autoload.php | lib/autoload.php | <?php
spl_autoload_register(function($className) {
if (strpos($className, 'Phactory\\') === 0) {
require_once __DIR__ . '/' . str_replace('\\', '/', $className) . '.php';
}
}); | php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Inflector.php | lib/Phactory/Inflector.php | <?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | Akelos PHP Application Framework |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.com/ |
// | Released under the GNU Lesser General Public License |
// +----------------------------------------------------------------------+
// | You should have received the following files along with this library |
// | - COPYRIGHT (Additional copyright notice) |
// | - DISCLAIMER (Disclaimer of warranty) |
// | - README (Important information regarding this library) |
// +----------------------------------------------------------------------+
namespace Phactory;
/**
* Inflector for pluralize and singularize English nouns.
*
* This Inflector is a port of Ruby on Rails Inflector.
*
* It can be really helpful for developers that want to
* create frameworks based on naming conventions rather than
* configurations.
*
* It was ported to PHP for the Akelos Framework, a
* multilingual Ruby on Rails like framework for PHP that will
* be launched soon.
*
* @author Bermi Ferrer Martinez <bermi akelos com>
* @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
* @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
* @since 0.1
* @version $Revision 0.1 $
*/
class Inflector
{
// ------ CLASS METHODS ------ //
// ---- Public methods ---- //
// {{{ pluralize()
/**
* Pluralizes English nouns.
*
* @access public
* @static
* @param string $word English noun to pluralize
* @return string Plural noun
*/
public static function pluralize($word)
{
$plural = array(
'/(quiz)$/i' => '\1zes',
'/^(ox)$/i' => '\1en',
'/([m|l])ouse$/i' => '\1ice',
'/(matr|vert|ind)ix|ex$/i' => '\1ices',
'/(x|ch|ss|sh)$/i' => '\1es',
'/([^aeiouy]|qu)ies$/i' => '\1y',
'/([^aeiouy]|qu)y$/i' => '\1ies',
'/(hive)$/i' => '\1s',
'/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
'/sis$/i' => 'ses',
'/([ti])um$/i' => '\1a',
'/(buffal|tomat)o$/i' => '\1oes',
'/(bu)s$/i' => '\1ses',
'/(alias|status)/i'=> '\1es',
'/(octop|vir)us$/i'=> '\1i',
'/(ax|test)is$/i'=> '\1es',
'/s$/i'=> 's',
'/$/'=> 's');
$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
$irregular = array(
'person' => 'people',
'man' => 'men',
'child' => 'children',
'sex' => 'sexes',
'move' => 'moves');
$lowercased_word = strtolower($word);
foreach ($uncountable as $_uncountable){
if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
return $word;
}
}
foreach ($irregular as $_plural=> $_singular){
if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
return preg_replace('/('.$_plural.')$/i', substr($arr[0],0,1).substr($_singular,1), $word);
}
}
foreach ($plural as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
}
}
return false;
}
// }}}
// {{{ singularize()
/**
* Singularizes English nouns.
*
* @access public
* @static
* @param string $word English noun to singularize
* @return string Singular noun.
*/
function singularize($word)
{
$singular = array (
'/(quiz)zes$/i' => '\\1',
'/(matr)ices$/i' => '\\1ix',
'/(vert|ind)ices$/i' => '\\1ex',
'/^(ox)en/i' => '\\1',
'/(alias|status)es$/i' => '\\1',
'/([octop|vir])i$/i' => '\\1us',
'/(cris|ax|test)es$/i' => '\\1is',
'/(shoe)s$/i' => '\\1',
'/(o)es$/i' => '\\1',
'/(bus)es$/i' => '\\1',
'/([m|l])ice$/i' => '\\1ouse',
'/(x|ch|ss|sh)es$/i' => '\\1',
'/(m)ovies$/i' => '\\1ovie',
'/(s)eries$/i' => '\\1eries',
'/([^aeiouy]|qu)ies$/i' => '\\1y',
'/([lr])ves$/i' => '\\1f',
'/(tive)s$/i' => '\\1',
'/(hive)s$/i' => '\\1',
'/([^f])ves$/i' => '\\1fe',
'/(^analy)ses$/i' => '\\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\\1\\2sis',
'/([ti])a$/i' => '\\1um',
'/(n)ews$/i' => '\\1ews',
'/s$/i' => '',
);
$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
$irregular = array(
'person' => 'people',
'man' => 'men',
'child' => 'children',
'sex' => 'sexes',
'move' => 'moves');
$lowercased_word = strtolower($word);
foreach ($uncountable as $_uncountable){
if(substr($lowercased_word,(-1*strlen($_uncountable))) == $_uncountable){
return $word;
}
}
foreach ($irregular as $_plural=> $_singular){
if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
return preg_replace('/('.$_singular.')$/i', substr($arr[0],0,1).substr($_plural,1), $word);
}
}
foreach ($singular as $rule => $replacement) {
if (preg_match($rule, $word)) {
return preg_replace($rule, $replacement, $word);
}
}
return $word;
}
// }}}
// {{{ titleize()
/**
* Converts an underscored or CamelCase word into a English
* sentence.
*
* The titleize function converts text like "WelcomePage",
* "welcome_page" or "welcome page" to this "Welcome
* Page".
* If second parameter is set to 'first' it will only
* capitalize the first character of the title.
*
* @access public
* @static
* @param string $word Word to format as tile
* @param string $uppercase If set to 'first' it will only uppercase the
* first character. Otherwise it will uppercase all
* the words in the title.
* @return string Text formatted as title
*/
function titleize($word, $uppercase = '')
{
$uppercase = $uppercase == 'first' ? 'ucfirst' : 'ucwords';
return $uppercase(Inflector::humanize(Inflector::underscore($word)));
}
// }}}
// {{{ camelize()
/**
* Returns given word as CamelCased
*
* Converts a word like "send_email" to "SendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "WhoSOnline"
*
* @access public
* @static
* @see variablize
* @param string $word Word to convert to camel case
* @return string UpperCamelCasedWord
*/
function camelize($word)
{
return str_replace(' ','',ucwords(preg_replace('/[^A-Z^a-z^0-9]+/',' ',$word)));
}
// }}}
// {{{ underscore()
/**
* Converts a word "into_it_s_underscored_version"
*
* Convert any "CamelCased" or "ordinary Word" into an
* "underscored_word".
*
* This can be really useful for creating friendly URLs.
*
* @access public
* @static
* @param string $word Word to underscore
* @return string Underscored word
*/
function underscore($word)
{
return strtolower(preg_replace('/[^A-Z^a-z^0-9]+/','_',
preg_replace('/([a-z\d])([A-Z])/','\1_\2',
preg_replace('/([A-Z]+)([A-Z][a-z])/','\1_\2',$word))));
}
// }}}
// {{{ humanize()
/**
* Returns a human-readable string from $word
*
* Returns a human-readable string from $word, by replacing
* underscores with a space, and by upper-casing the initial
* character by default.
*
* If you need to uppercase all the words you just have to
* pass 'all' as a second parameter.
*
* @access public
* @static
* @param string $word String to "humanize"
* @param string $uppercase If set to 'all' it will uppercase all the words
* instead of just the first one.
* @return string Human-readable word
*/
function humanize($word, $uppercase = '')
{
$uppercase = $uppercase == 'all' ? 'ucwords' : 'ucfirst';
return $uppercase(str_replace('_',' ',preg_replace('/_id$/', '',$word)));
}
// }}}
// {{{ variablize()
/**
* Same as camelize but first char is underscored
*
* Converts a word like "send_email" to "sendEmail". It
* will remove non alphanumeric character from the word, so
* "who's online" will be converted to "whoSOnline"
*
* @access public
* @static
* @see camelize
* @param string $word Word to lowerCamelCase
* @return string Returns a lowerCamelCasedWord
*/
function variablize($word)
{
$word = Inflector::camelize($word);
return strtolower($word[0]).substr($word,1);
}
// }}}
// {{{ tableize()
/**
* Converts a class name to its table name according to rails
* naming conventions.
*
* Converts "Person" to "people"
*
* @access public
* @static
* @see classify
* @param string $class_name Class name for getting related table_name.
* @return string plural_table_name
*/
function tableize($class_name)
{
return Inflector::pluralize(Inflector::underscore($class_name));
}
// }}}
// {{{ classify()
/**
* Converts a table name to its class name according to rails
* naming conventions.
*
* Converts "people" to "Person"
*
* @access public
* @static
* @see tableize
* @param string $table_name Table name for getting related ClassName.
* @return string SingularClassName
*/
function classify($table_name)
{
return Inflector::camelize(Inflector::singularize($table_name));
}
// }}}
// {{{ ordinalize()
/**
* Converts number to its ordinal English form.
*
* This method converts 13 to 13th, 2 to 2nd ...
*
* @access public
* @static
* @param integer $number Number to get its ordinal value
* @return string Ordinal representation of given string.
*/
function ordinalize($number)
{
if (in_array(($number % 100),range(11,13))){
return $number.'th';
}else{
switch (($number % 10)) {
case 1:
return $number.'st';
break;
case 2:
return $number.'nd';
break;
case 3:
return $number.'rd';
default:
return $number.'th';
break;
}
}
}
// }}}
}
?>
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Collection.php | lib/Phactory/Mongo/Collection.php | <?php
namespace Phactory\Mongo;
class Collection {
protected $_singular;
protected $_name;
protected $_collection;
public function __construct($singular_name, $pluralize = true, Phactory $phactory) {
$this->_singular = $singular_name;
if($pluralize) {
$this->_name = Inflector::pluralize($singular_name);
} else {
$this->_name = $singular_name;
}
$this->_collection = $phactory->getDb()->selectCollection($this->_name);
}
public function getName() {
return $this->_name;
}
public function getSingularName() {
return $this->_singular;
}
public function __toString() {
return $this->_name;
}
public function __call($func, $args) {
return call_user_func_array(array($this->_collection, $func), $args);
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Phactory.php | lib/Phactory/Mongo/Phactory.php | <?php
namespace Phactory\Mongo;
class Phactory {
/*
* Array of collection name => Blueprint
*/
protected $_blueprints = array();
/*
* Mongo database object
*/
protected $_db;
/**
* Constructs a Phactory object for testing MongoDB databases
*
* @param \MongoDB $mongo A MongoDB database connection to test with
*/
public function __construct(\MongoDB $mongo) {
$this->_db = $mongo;
}
/*
* Set the Mongo object to use for database connection.
*
* @param object $db Mongo object
*/
public function setDb(\MongoDB $db) {
$this->_db = $db;
}
/*
* Get the Mongo database object.
*
* @return object Mongo
*/
public function getDb() {
return $this->_db;
}
/*
* Define the default values to use when constructing
* a document in the specified collection.
*
* @param string $blueprint_name singular name of the collection in the database
* @param array $defaults key => value pairs of field => value, or a phactory_blueprint
* @param array $associations array of phactory_associations
*/
public function define($blueprint_name, $defaults, $associations = array()) {
if($defaults instanceof Blueprint) {
$blueprint = $defaults;
} else {
$blueprint = new Blueprint($blueprint_name, $defaults, $associations, $this);
}
$this->_blueprints[$blueprint_name] = $blueprint;
}
/*
* alias for define per @jblotus pull request
* eventually we should just rename the original function
*/
public function defineBlueprint($blueprint_name, $defaults, $associations = array()) {
$this->define($blueprint_name, $defaults, $associations);
}
/*
* Instantiate a document in the specified collection, optionally
* overriding some or all of the default values.
* The document is saved to the database and returned as an array.
*
* @param string $blueprint_name name of the blueprint
* @param array $overrides key => value pairs of column => value
* @return array
*/
public function create($blueprint_name, $overrides = array()) {
return $this->createWithAssociations($blueprint_name, array(), $overrides);
}
/*
* Build a document as an array, optionally
* overriding some or all of the default values.
* The document is not saved to the database.
*
* @param string $blueprint_name name of the blueprint
* @param array $overrides key => value pairs of column => value
* @return array
*/
public function build($blueprint_name, $overrides = array()) {
return $this->buildWithAssociations($blueprint_name, array(), $overrides);
}
/*
* Instantiate a document in the specified collection, optionally
* overriding some or all of the default values.
* The document is saved to the database, and returned as an array.
*
* @param string $blueprint_name name of the blueprint to use
* @param array $associations [collection name] => [array]
* @param array $overrides key => value pairs of field => value
* @return array
*/
public function createWithAssociations($blueprint_name, $associations = array(), $overrides = array()) {
if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) {
throw new \Exception("No blueprint defined for '$blueprint_name'");
}
return $blueprint->create($overrides, $associations);
}
/*
* Build a document as an array, optionally
* overriding some or all of the default values.
* The document is not saved to the database.
*
* @param string $blueprint_name name of the blueprint to use
* @param array $associations [collection name] => [array]
* @param array $overrides key => value pairs of field => value
* @return array
*/
public function buildWithAssociations($blueprint_name, $associations = array(), $overrides = array()) {
if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) {
throw new \Exception("No blueprint defined for '$blueprint_name'");
}
return $blueprint->build($overrides, $associations);
}
/*
* Get a document from the database as an array.
*
* @param string $collection_name name of the collection
* @param array $query a MongoDB query
* @return array
*/
public function get($collection_name, $query) {
if(!is_array($query)) {
throw new \Exception("\$query must be an associative array of 'field => value' pairs");
}
$collection = new Collection($collection_name, true, $this);
return $collection->findOne($query);
}
/*
* Get results from the database as a cursor.
*
* @param string $collection_name name of the collection
* @param array $query a MongoDB query
* @return MongoCursor
*/
public function getAll($collection_name, $query = array()) {
if(!is_array($query)) {
throw new \Exception("\$query must be an associative array of 'field => value' pairs");
}
$collection = new Collection($collection_name, true, $this);
return $collection->find($query);
}
/*
* Create an embeds-one association object for use in define().
*
* @param string $collection_name the singular name of the collection to associate with
*/
public function embedsOne($collection_name) {
return new Association\EmbedsOne($collection_name);
}
/*
* Create an embeds-many association object for use in define().
*
* @param string $collection_name the singular name of the collection to associate with
*/
public function embedsMany($collection_name) {
return new Association\EmbedsMany($collection_name);
}
/*
* Delete created documents from the database.
*/
public function recall() {
foreach($this->_blueprints as $blueprint) {
$blueprint->recall();
}
}
/*
* Delete created objects from the database, clear defined
* blueprints, and clear stored inflection exceptions.
*/
public function reset() {
$this->recall();
$this->_blueprints = array();
Inflector::reset();
}
/*
* Specify an exception for collection name inflection.
* For example, if your collection of fish is called 'fishes',
* call setInflection('fish', 'fishes')
*
* @param string $singular singular form of the word.
* @param string $plural plural form of the word.
*
*/
public function setInflection($singular, $plural){
Inflector::addException($singular, $plural);
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Sequence.php | lib/Phactory/Mongo/Sequence.php | <?php
namespace Phactory\Mongo;
class Sequence {
protected $_value;
public function __construct($initial_value = 0) {
$this->_value = $initial_value;
}
public function next() {
return $this->_value++;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Association.php | lib/Phactory/Mongo/Association.php | <?php
namespace Phactory\Mongo;
class Association {
protected $_name;
public function __construct($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Blueprint.php | lib/Phactory/Mongo/Blueprint.php | <?php
namespace Phactory\Mongo;
class Blueprint {
protected $_collection;
protected $_defaults;
protected $_sequence;
public function __construct($name, $defaults, $associations = array(), Phactory $phactory) {
$this->_collection = new Collection($name, true, $phactory);
$this->_defaults = $defaults;
$this->_sequence = new Sequence();
if(!is_array($associations)) {
throw new \Exception("\$associations must be an array of Association objects");
}
$this->setAssociations($associations);
}
public function setDefaults($defaults) {
$this->_defaults = $defaults;
}
public function addDefault($column, $value) {
$this->_defaults[$column] = $value;
}
public function removeDefault($column) {
unset($this->_defaults[$column]);
}
public function setAssociations($associations) {
$this->_associations = $associations;
}
public function addAssociation($name, $association) {
$this->_associations[$name] = $association;
}
public function removeAssociation($name) {
unset($this->_associations[$name]);
}
/*
* Build the document as an array, but don't save it to the db.
*
* @param array $overrides field => value pairs which override the defaults for this blueprint
* @param array $associated [name] => [Association] pairs
* @return array the document
*/
public function build($overrides = array(), $associated = array()) {
$data = $this->_defaults;
if($associated) {
foreach($associated as $name => $document) {
if(!isset($this->_associations[$name])) {
throw new \Exception("No association '$name' defined");
}
$association = $this->_associations[$name];
if(!$association instanceof Association\EmbedsMany &&
!$association instanceof Association\EmbedsOne) {
throw new \Exception("Invalid association object for '$name'");
}
$overrides[$name] = $document;
}
}
$this->_evalSequence($data);
if($overrides) {
foreach($overrides as $field => $value) {
$data[$field] = $value;
}
}
return $data;
}
/*
* Create document in the database and return it.
*
* @param array $overrides field => value pairs which override the defaults for this blueprint
* @param array $associated [name] => [Association] pairs
* @return array the created document
*/
public function create($overrides = array(), $associated = array()) {
$data = $this->build($overrides, $associated);
$this->_collection->insert($data,array("w"=>1));
return $data;
}
/*
* Empty the collection in the database.
*/
public function recall() {
$this->_collection->remove();
}
protected function _evalSequence(&$data) {
$n = $this->_sequence->next();
array_walk_recursive($data,function(&$value) use ($n) {
if(is_string($value) && false !== strpos($value, '$')) {
$value = eval('return "'. stripslashes($value) . '";');
}
});
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Inflector.php | lib/Phactory/Mongo/Inflector.php | <?php
namespace Phactory\Mongo;
class Inflector extends \Phactory\Inflector {
private static $_exceptions = array();
/*
* Static class forbids instantiation.
*/
private function __construct() { }
/*
* Pluralize a word, obeying any stored exceptions.
*
* @param string $word the word to pluralize
*/
public static function pluralize($word) {
foreach(self::$_exceptions as $exception) {
if($exception['singular'] == $word){
return $exception['plural'];
}
}
return parent::pluralize($word);
}
/*
* Add an exception to the rules for inflection.
*
* @param string $singular the singular form of this word
* @param string $plural the plurbal form of this word
*/
public static function addException($singular, $plural) {
self::$_exceptions[] = array('singular' => $singular,
'plural' => $plural);
}
/*
* Forget all stored exceptions.
*/
public static function reset() {
self::$_exceptions = array();
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Logger.php | lib/Phactory/Mongo/Logger.php | <?php
namespace Phactory\Mongo;
class Logger {
const LEVEL_DEBUG = 1;
const LEVEL_WARN = 2;
const LEVEL_ERROR = 4;
const LEVEL_FATAL = 8;
const LEVEL_ALL = 15;
protected static $_level = self::LEVEL_ALL;
protected static $_level_strs = array(self::LEVEL_DEBUG => 'DEBUG',
self::LEVEL_WARN => 'WARN',
self::LEVEL_ERROR => 'ERROR',
self::LEVEL_FATAL => 'FATAL');
public static function setLogLevel($level) {
self::$_level = $level;
}
public static function debug($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_DEBUG, $msg, $backtrace);
}
public static function warn($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_WARN, $msg, $backtrace);
}
public static function error($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_ERROR, $msg, $backtrace);
throw new \Exception();
}
public static function fatal($msg, $backtrace = true) {
self::outputMessage(self::LEVEL_FATAL, $msg, $backtrace);
die;
}
protected static function outputMessage($log_level, $msg, $backtrace) {
if(self::$_level & $log_level) {
print(strftime("%Y-%m-%d %H:%M:%S Phactory ") . self::$_level_strs[$log_level] . ' - ' . $msg . "\n");
if($backtrace) {
debug_print_backtrace();
}
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Association/EmbedsMany.php | lib/Phactory/Mongo/Association/EmbedsMany.php | <?php
namespace Phactory\Mongo\Association;
use Phactory\Mongo\Association;
class EmbedsMany extends Association {
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Mongo/Association/EmbedsOne.php | lib/Phactory/Mongo/Association/EmbedsOne.php | <?php
namespace Phactory\Mongo\Association;
use Phactory\Mongo\Association;
class EmbedsOne extends Association {
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Phactory.php | lib/Phactory/Sql/Phactory.php | <?php
namespace Phactory\Sql;
class Phactory {
/*
* Array of table name => Blueprint
*/
protected $_blueprints = array();
/*
* PDO database connection
*/
protected $_pdo;
/**
* Constructs a Phactory object for testing SQL databases
*
* @param \PDO $pdo A PDO database connection to test with
*/
public function __construct(\PDO $pdo) {
$this->_pdo = $pdo;
}
/*
* Set the PDO object to use for database connection.
*
* @param object $pdo PDO object
*/
public function setConnection($pdo) {
$this->_pdo = $pdo;
}
/*
* Get the PDO database connection object.
*
* @return object PDO
*/
public function getConnection() {
return $this->_pdo;
}
/*
* Define the default values to use when constructing
* a row in the specified table.
*
* @param string $blueprint_name singular name of the table in the database
* @param array $defaults key => value pairs of column => value, or a phactory_blueprint
* @param array $associations array of phactory_associations
*/
public function define($blueprint_name, $defaults = array(), $associations = array()) {
if($defaults instanceof Blueprint) {
$blueprint = $defaults;
} else {
$blueprint = new Blueprint($blueprint_name, $defaults, $associations, $this);
}
$this->_blueprints[$blueprint_name] = $blueprint;
}
/*
* alias for define per @jblotus pull request
* eventually we should just rename the original function
*/
public function defineBlueprint($blueprint_name, $defaults = array(), $associations = array()) {
$this->define($blueprint_name, $defaults, $associations);
}
/*
* Instantiate a row in the specified table, optionally
* overriding some or all of the default values.
* The row is saved to the database, and returned
* as a Row.
*
* @param string $table name of the table
* @param array $overrides key => value pairs of column => value
* @return object Row
*/
public function create($table, $overrides = array()) {
return $this->createWithAssociations($table, array(), $overrides);
}
/*
* Build a Row object, optionally
* overriding some or all of the default values.
* The row is not saved to the database.
*
* @param string $table name of the table
* @param array $overrides key => value pairs of column => value
* @return object Row
*/
public function build($table, $overrides = array()) {
return $this->buildWithAssociations($table, array(), $overrides);
}
/*
* Instantiate a row in the specified table, optionally
* overriding some or all of the default values.
* The row is saved to the database, and returned
* as a Row.
*
* @param string $blueprint_name name of the blueprint to use
* @param array $associations [table name] => [Row]
* @param array $overrides key => value pairs of column => value
* @return object Row
*/
public function createWithAssociations($blueprint_name, $associations = array(), $overrides = array()) {
if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) {
throw new \Exception("No blueprint defined for '$blueprint_name'");
}
return $blueprint->create($overrides, $associations);
}
/*
* Build a Row object, optionally
* overriding some or all of the default values.
* The row is not saved to the database.
*
* @param string $blueprint_name name of the blueprint to use
* @param array $associations [table name] => [Row]
* @param array $overrides key => value pairs of column => value
* @return object Row
*/
public function buildWithAssociations($blueprint_name, $associations = array(), $overrides = array()) {
if(! ($blueprint = $this->_blueprints[$blueprint_name]) ) {
throw new \Exception("No blueprint defined for '$blueprint_name'");
}
foreach($associations as $association) {
if($association instanceof Association\ManyToMany) {
throw new \Exception("ManyToMany associations cannot be used in Phactory::build()");
}
}
return $blueprint->build($overrides, $associations);
}
/*
* Get a row from the database as a Row.
* $byColumn is like array('id' => 123).
*
* @param string $table_name name of the table
* @param array $byColumn
* @return object Row
*/
public function get($table_name, $byColumns) {
$all = $this->getAll($table_name, $byColumns);
return array_shift($all);
}
public function getAll($table_name, $byColumns) {
if(!is_array($byColumns)) {
throw new \Exception("\$byColumns must be an associative array of 'column => value' pairs");
}
$table = new Table($table_name, true, $this);
$equals = array();
$params = array();
foreach($byColumns as $field => $value)
{
$equals[] = $table->quoteIdentifier($field) . ' = ?';
$params[] = $value;
}
$where_sql = implode(' AND ', $equals);
$sql = "SELECT * FROM " . $table->quoteIdentifier($table->getName()) . " WHERE " . $where_sql;
$stmt = $this->_pdo->prepare($sql);
$r = $stmt->execute($params);
if($r === false){
$error = $stmt->errorInfo();
Logger::error('SQL statement failed: '.$sql.' ERROR MESSAGE: '.$error[2].' ERROR CODE: '.$error[1]);
}
$rows = array();
while($result = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$rows[] = new Row($table_name, $result, $this);
}
return $rows;
}
/*
* Delete created Row objects from the database.
*/
public function recall() {
foreach($this->_blueprints as $blueprint) {
$blueprint->recall();
}
}
/*
* Delete created objects from the database, clear defined
* blueprints, and clear stored inflection exceptions.
*/
public function reset() {
$this->recall();
$this->_blueprints = array();
Inflector::reset();
}
public function manyToMany($to_table, $join_table, $from_column = null, $from_join_column = null, $to_join_column = null, $to_column = null) {
$to_table = new Table($to_table, true, $this);
$join_table = new Table($join_table, false, $this);
return new Association\ManyToMany($to_table, $join_table, $from_column, $from_join_column, $to_join_column, $to_column);
}
/*
* Create a many-to-one association object for use in define().
*
* @param string $to_table the table to associate with
* @param string $from_column the fk column on the left table
* @param string $to_column the pk column of the right table, or null to autodetect
*
* @return object Association\ManyToOne
*/
public function manyToOne($to_table, $from_column = null, $to_column = null) {
$to_table = new Table($to_table, true, $this);
return new Association\ManyToOne($to_table, $from_column, $to_column);
}
/*
* Create a one-to-one association object for use in define().
*
* @param string $to_table the table to associate with
* @param string $from_column the fk column on the left table
* @param string $to_column the pk column of the right table, or null to autodetect
*
* @return object Association\OneToOne
*/
public function oneToOne($to_table, $from_column, $to_column = null) {
$to_table = new Table($to_table, true, $this);
return new Association\OneToOne($to_table, $from_column, $to_column);
}
/*
* Specify an exception for table name inflection.
* For example, if your table of fish is called 'fishes',
* call setInflection('fish', 'fishes')
*
* @param string $singular singular form of the word.
* @param string $plural plural form of the word.
*
*/
public function setInflection($singular, $plural){
Inflector::addException($singular, $plural);
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Sequence.php | lib/Phactory/Sql/Sequence.php | <?php
namespace Phactory\Sql;
class Sequence {
protected $_value;
public function __construct($initial_value = 0) {
$this->_value = $initial_value;
}
public function next() {
return $this->_value++;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Table.php | lib/Phactory/Sql/Table.php | <?php
namespace Phactory\Sql;
class Table {
protected $_singular;
protected $_name;
protected $_db_util;
protected $_phactory;
public function __construct($singular_name, $pluralize = true, Phactory $phactory) {
$this->_phactory = $phactory;
$this->_db_util = DbUtilFactory::getDbUtil($phactory);
$this->_singular = $singular_name;
if($pluralize) {
$this->_name = Inflector::pluralize($singular_name);
} else {
$this->_name = $singular_name;
}
}
public function getName() {
return $this->_name;
}
public function getSingularName() {
return $this->_singular;
}
public function getPrimaryKey() {
return $this->_db_util->getPrimaryKey($this->_name);
}
public function hasColumn($column) {
return in_array($column, $this->getColumns());
}
public function getColumns() {
return $this->_db_util->getColumns($this->_name);
}
public function __toString() {
return $this->_name;
}
/**
* Added by Artūrs Gailītis, to support database-specific quote characters
*
* @param string $identifier - table/column name to be quoted in a proper
* way for the database driver, table is using.
* @return string quoted identifier
*/
public function quoteIdentifier($identifier)
{
return $this->_db_util->quoteIdentifier($identifier);
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Row.php | lib/Phactory/Sql/Row.php | <?php
namespace Phactory\Sql;
class Row {
protected $_table;
protected $_storage = array();
protected $_phactory;
public function __construct($table, $data, Phactory $phactory) {
$this->_phactory = $phactory;
if(!$table instanceof Table) {
$table = new Table($table, true, $phactory);
}
$this->_table = $table;
foreach($data as $key => $value) {
$this->_storage[$key] = $value;
}
}
public function getId() {
$pk = $this->_table->getPrimaryKey();
return $this->_storage[$pk];
}
public function save() {
$pdo = $this->_phactory->getConnection();
$sql = "INSERT INTO `{$this->_table}` (";
$data = array();
$params = array();
foreach($this->_storage as $key => $value) {
$index = $this->_table->quoteIdentifier($key);
$data[$index] = ":$key";
$params[":$key"] = $value;
}
$keys = array_keys($data);
$values = array_values($data);
$sql .= join(',', $keys);
$sql .= ") VALUES (";
$sql .= join(',', $values);
$sql .= ")";
$stmt = $pdo->prepare($sql);
$r = $stmt->execute($params);
if($r === false){
$error= $stmt->errorInfo();
Logger::error('SQL statement failed: '.$sql.' ERROR MESSAGE: '.$error[2].' ERROR CODE: '.$error[1]);
}
// only works if table's primary key autoincrements
$id = $pdo->lastInsertId();
if($pk = $this->_table->getPrimaryKey()) {
if($id){
$this->_storage[$pk] = $id;
}else{
// if key doesn't autoincrement, find last inserted row and set the primary key.
$sql = "SELECT * FROM `{$this->_table}` WHERE";
for($i = 0, $size = sizeof($keys); $i < $size; ++$i){
$sql .= " {$keys[$i]} = {$values[$i]} AND";
}
$sql = substr($sql, 0, -4);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
$this->_storage[$pk] = $result[$pk];
}
}
return $r;
}
public function toArray() {
return $copy = $this->_storage;
}
public function __get($key) {
return $this->_storage[$key];
}
public function __set($key, $value) {
$this->_storage[$key] = $value;
}
public function fill() {
$columns = $this->_table->getColumns();
foreach ($columns as $column) {
if ( ! isset($this->_storage[$column]) ) {
$this->_storage[$column] = null;
}
}
return $this;
}
public function __isset($name){
return(isset($this->_storage[$name]));
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Association.php | lib/Phactory/Sql/Association.php | <?php
namespace Phactory\Sql;
class Association {
protected $_to_table;
protected $_fk_column;
public function __construct($to_table, $fk_column) {
$this->_to_table = $to_table;
$this->_fk_column = $fk_column;
}
public function getTable() {
return $this->_to_table;
}
public function getFkColumn() {
return $this->_fk_column;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Blueprint.php | lib/Phactory/Sql/Blueprint.php | <?php
namespace Phactory\Sql;
class Blueprint {
protected $_table;
protected $_defaults;
protected $_associations = array();
protected $_sequence;
protected $_phactory;
public function __construct($name, $defaults, $associations = array(), Phactory $phactory = null) {
if(!($phactory instanceof Phactory)) {
throw new \Exception('$phactory must be an instance of Phactory\Sql\Phactory');
}
$this->_table = new Table($name, true, $phactory);
$this->_defaults = $defaults;
$this->_sequence = new Sequence();
$this->_phactory = $phactory;
foreach($associations as $name => $association) {
$association->setFromTable($this->_table);
$this->addAssociation($name, $association);
}
if(!is_array($associations)) {
throw new \Exception("\$associations must be an array of Association objects");
}
}
public function setDefaults($defaults) {
$this->_defaults = $defaults;
}
public function addDefault($column, $value) {
$this->_defaults[$column] = $value;
}
public function removeDefault($column) {
unset($this->_defaults[$column]);
}
public function setAssociations($associations) {
$this->_associations = $associations;
}
public function addAssociation($name, $association) {
$association->setFromTable($this->_table);
$this->_associations[$name] = $association;
}
public function removeAssociation($name) {
unset($this->_associations[$name]);
}
/*
* Build a Row from this Blueprint. Optionally use an array
* of associated objects to set fk columns.
*
* Note that this function ignores ManyToMany associations, as those
* can't be handled unless the Row is actually saved to the db.
*
* @param array $associated [table name] => [Row]
*/
public function build($overrides = array(), $associated = array()) {
// process one-to-one and many-to-one relations
$assoc_keys = array();
foreach($associated as $name => $row) {
if(!isset($this->_associations[$name])) {
throw new \Exception("No association '$name' defined");
}
$association = $this->_associations[$name];
if(!$association instanceof Association\ManyToMany) {
$fk_column = $association->getFromColumn();
$to_column = $association->getToColumn();
$assoc_keys[$fk_column] = $row->$to_column;
}
}
$data = array_merge($this->_defaults, $assoc_keys);
$this->_evalSequence($data);
$built = new Row($this->_table, $data, $this->_phactory);
if($overrides) {
foreach($overrides as $field => $value) {
$built->$field = $value;
}
}
return $built;
}
/*
* Reify a Blueprint as a Row. Optionally use an array
* of associated objects to set fk columns.
*
* @param array $associated [table name] => [Row]
*/
public function create($overrides = array(), $associated = array()) {
$built = $this->build($overrides, $associated);
// process any many-to-many associations
$many_to_many = array();
foreach($associated as $name => $row) {
$association = $this->_associations[$name];
if($association instanceof Association\ManyToMany) {
if(!is_array($row)) {
$row = array($row);
}
$many_to_many[$name] = array($row, $association);
}
}
$built->save();
if($many_to_many) {
$this->_associateManyToMany($built, $many_to_many);
}
return $built;
}
/*
* Truncate table in the database.
*/
public function recall() {
$db_util = DbUtilFactory::getDbUtil($this->_phactory);
$db_util->disableForeignKeys();
try {
$sql = "DELETE FROM {$this->_table->getName()}";
$this->_phactory->getConnection()->exec($sql);
} catch(Exception $e) { }
foreach($this->_associations as $association) {
if($association instanceof Association\ManyToMany) {
try {
$sql = "DELETE FROM `{$association->getJoinTable()}`";
$this->_phactory->getConnection()->exec($sql);
} catch(Exception $e) { }
}
}
$db_util->enableForeignKeys();
}
protected function _evalSequence(&$data) {
$n = $this->_sequence->next();
foreach($data as &$value) {
if(false !== strpos($value, '$')) {
$value = strtr($value, array('$n' => $n));
}
if(preg_match_all('/#\{(.+)\}/U', $value, $matches)) {
foreach($matches[1] as $match) {
$value = preg_replace('/#\{.+\}/U', eval('return ' . $match . ';'), $value, 1);
}
}
}
}
protected function _associateManyToMany($row, $many_to_many) {
$pdo = $this->_phactory->getConnection();
foreach($many_to_many as $name => $arr) {
list($to_rows, $assoc) = $arr;
foreach($to_rows as $to_row) {
$join_table = $assoc->getJoinTable();
$from_join_column = $assoc->getFromJoinColumn();
$to_join_column = $assoc->getToJoinColumn();
// Quote table names as underlying DB expects it
$sql = "INSERT INTO ".$this->_table->quoteIdentifier($join_table)."
(".$this->_table->quoteIdentifier($from_join_column).", ".$this->_table->quoteIdentifier($to_join_column).")
VALUES
(:from_id, :to_id)";
$stmt = $pdo->prepare($sql);
$r = $stmt->execute(array(':from_id' => $row->getId(), ':to_id' => $to_row->getId()));
if($r === false){
$error= $stmt->errorInfo();
Logger::error('SQL statement failed: '.$sql.' ERROR MESSAGE: '.$error[2].' ERROR CODE: '.$error[1]);
}
}
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/DbUtilFactory.php | lib/Phactory/Sql/DbUtilFactory.php | <?php
namespace Phactory\Sql;
class DbUtilFactory {
private function __construct(){ }
public static function getDbUtil(Phactory $phactory)
{
$db_type = $phactory->getConnection()->getAttribute(\PDO::ATTR_DRIVER_NAME);
switch ($db_type)
{
case 'mysql':
return new DbUtil\MysqlUtil($phactory);
break;
case 'pgsql':
return new DbUtil\PgsqlUtil($phactory);
break;
case 'sqlite':
return new DbUtil\SqliteUtil($phactory);
break;
default:
throw new \Exception("DB type '$db_type' not found");
break;
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Inflector.php | lib/Phactory/Sql/Inflector.php | <?php
namespace Phactory\Sql;
class Inflector extends \Phactory\Inflector {
private static $_exceptions = array();
/*
* Static class forbids instantiation.
*/
private function __construct() { }
/*
* Pluralize a word, obeying any stored exceptions.
*
* @param string $word the word to pluralize
*/
public static function pluralize($word) {
foreach(self::$_exceptions as $exception) {
if($exception['singular'] == $word){
return $exception['plural'];
}
}
return parent::pluralize($word);
}
/*
* Add an exception to the rules for inflection.
*
* @param string $singular the singular form of this word
* @param string $plural the plurbal form of this word
*/
public static function addException($singular, $plural) {
self::$_exceptions[] = array('singular' => $singular,
'plural' => $plural);
}
/*
* Forget all stored exceptions.
*/
public static function reset() {
self::$_exceptions = array();
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Logger.php | lib/Phactory/Sql/Logger.php | <?php
namespace Phactory\Sql;
class Logger {
const LEVEL_DEBUG = 1;
const LEVEL_WARN = 2;
const LEVEL_ERROR = 4;
const LEVEL_FATAL = 8;
const LEVEL_ALL = 15;
protected static $_level = self::LEVEL_ALL;
protected static $_level_strs = array(self::LEVEL_DEBUG => 'DEBUG',
self::LEVEL_WARN => 'WARN',
self::LEVEL_ERROR => 'ERROR',
self::LEVEL_FATAL => 'FATAL');
public static function setLogLevel($level) {
self::$_level = $level;
}
public static function debug($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_DEBUG, $msg, $backtrace);
}
public static function warn($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_WARN, $msg, $backtrace);
}
public static function error($msg, $backtrace = false) {
self::outputMessage(self::LEVEL_ERROR, $msg, $backtrace);
throw new \Exception();
}
public static function fatal($msg, $backtrace = true) {
self::outputMessage(self::LEVEL_FATAL, $msg, $backtrace);
die;
}
protected static function outputMessage($log_level, $msg, $backtrace) {
if(self::$_level & $log_level) {
print(strftime("%Y-%m-%d %H:%M:%S Phactory ") . self::$_level_strs[$log_level] . ' - ' . $msg . "\n");
if($backtrace) {
debug_print_backtrace();
}
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/DbUtil/AbstractDbUtil.php | lib/Phactory/Sql/DbUtil/AbstractDbUtil.php | <?php
namespace Phactory\Sql\DbUtil;
use Phactory\Sql\Phactory;
abstract class AbstractDbUtil
{
protected $_pdo;
/**
* @var string quote character for table and column names. Override in
* DB-specific descendant classes
*/
protected $_quoteChar = '`'; // MySQL and SqlLite uses that
public function __construct(Phactory $phactory) {
$this->_pdo = $phactory->getConnection();
}
abstract public function getPrimaryKey($table);
abstract public function getColumns($table);
// Not available in all RDBMS - default - do nothing
public function disableForeignKeys() {}
public function enableForeignKeys() {}
/**
* @param string $identifier name of table, column, etc
* @return string quoted identifier
*/
public function quoteIdentifier($identifier)
{
$quote = $this->getQuoteChar();
return $quote.$identifier.$quote;
}
public function getQuoteChar()
{
return $this->_quoteChar;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/DbUtil/PgsqlUtil.php | lib/Phactory/Sql/DbUtil/PgsqlUtil.php | <?php
namespace Phactory\Sql\DbUtil;
use Phactory\Sql\Phactory;
class PgsqlUtil extends AbstractDbUtil
{
protected $_quoteChar = '"';
public function getPrimaryKey($table) {
$query = "
SELECT
pg_attribute.attname,
format_type(pg_attribute.atttypid, pg_attribute.atttypmod)
FROM pg_index, pg_class, pg_attribute
WHERE
pg_class.oid = '$table'::regclass AND
indrelid = pg_class.oid AND
pg_attribute.attrelid = pg_class.oid AND
pg_attribute.attnum = any(pg_index.indkey)
AND indisprimary
";
$stmt = $this->_pdo->query($query);
$result = $stmt->fetch();
return $result['attname'];
}
public function getColumns($table) {
$query = "
SELECT column_name
FROM information_schema.columns
WHERE table_name = '$table'
";
$stmt = $this->_pdo->query($query);
$columns = array();
while($row = $stmt->fetch()) {
$columns[] = $row['column_name'];
}
return $columns;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/DbUtil/SqliteUtil.php | lib/Phactory/Sql/DbUtil/SqliteUtil.php | <?php
namespace Phactory\Sql\DbUtil;
use Phactory\Sql\Phactory;
class SqliteUtil extends AbstractDbUtil
{
protected $_quoteChar = '`';
public function getPrimaryKey($table)
{
$stmt = $this->_pdo->prepare("SELECT * FROM sqlite_master WHERE type='table' AND name=:name");
$stmt->execute(array(':name' => $table));
$result = $stmt->fetch();
$sql = $result['sql'];
$matches = array();
preg_match('/(\w+?)\s+\w+?\s+PRIMARY KEY/', $sql, $matches);
if(!isset($matches[1])) {
return null;
}
return $matches[1];
}
public function getColumns($table) {
$stmt = $this->_pdo->query("PRAGMA table_info($table)");
$columns = array();
while($row = $stmt->fetch()) {
$columns[] = $row['name'];
}
return $columns;
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/DbUtil/MysqlUtil.php | lib/Phactory/Sql/DbUtil/MysqlUtil.php | <?php
namespace Phactory\Sql\DbUtil;
use Phactory\Sql\Phactory;
class MysqlUtil extends AbstractDbUtil
{
protected $_quoteChar = '`';
public function getPrimaryKey($table) {
$table = $this->quoteIdentifier($table);
$stmt = $this->_pdo->query("SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'");
$result = $stmt->fetch();
return $result['Column_name'];
}
public function getColumns($table) {
$table = $this->quoteIdentifier($table);
$stmt = $this->_pdo->query("DESCRIBE $table");
$columns = array();
while($row = $stmt->fetch()) {
$columns[] = $row['Field'];
}
return $columns;
}
public function disableForeignKeys() {
$this->_pdo->exec("SET FOREIGN_KEY_CHECKS=0");
}
public function enableForeignKeys() {
$this->_pdo->exec("SET FOREIGN_KEY_CHECKS=1");
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Association/ManyToOne.php | lib/Phactory/Sql/Association/ManyToOne.php | <?php
namespace Phactory\Sql\Association;
class ManyToOne {
protected $_from_table;
protected $_to_table;
protected $_from_column;
protected $_to_column;
public function __construct($to_table, $from_column = null, $to_column = null) {
$this->setToColumn($to_column);
$this->setFromColumn($from_column);
$this->setToTable($to_table);
}
public function getFromTable() {
return $this->_from_table;
}
public function setFromTable($table) {
$this->_from_table = $table;
$this->_guessFromColumn();
}
public function getToTable() {
return $this->_to_table;
}
public function setToTable($table) {
$this->_to_table = $table;
$this->_guessToColumn();
}
public function getFromColumn() {
return $this->_from_column;
}
public function setFromColumn($column) {
$this->_from_column = $column;
}
public function getToColumn() {
return $this->_to_column;
}
public function setToColumn($column) {
$this->_to_column = $column;
}
protected function _guessFromColumn() {
if(null === $this->_from_column) {
$guess = $this->_to_table->getSingularName() . '_id';
if($this->_from_table->hasColumn($guess)) {
$this->setFromColumn($guess);
} else {
throw new \Exception("Unable to guess from_column for association and none specified");
}
}
}
protected function _guessToColumn() {
if(null === $this->_to_column) {
$this->_to_column = $this->_to_table->getPrimaryKey();
if(!$this->_to_column) {
throw new \Exception("Unable to determine primary key for table '{$this->_to_table}' and none specified");
}
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Association/OneToOne.php | lib/Phactory/Sql/Association/OneToOne.php | <?php
namespace Phactory\Sql\Association;
class OneToOne extends ManyToOne { }
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
chriskite/phactory | https://github.com/chriskite/phactory/blob/054cac8f6a5ab6e3da7a5bcead71c7e173c16389/lib/Phactory/Sql/Association/ManyToMany.php | lib/Phactory/Sql/Association/ManyToMany.php | <?php
namespace Phactory\Sql\Association;
class ManyToMany extends ManyToOne {
protected $_join_table;
protected $_from_join_column;
protected $_to_join_column;
public function __construct($to_table, $join_table, $from_column = null, $from_join_column = null, $to_join_column = null, $to_column = null) {
parent::__construct($to_table, $from_column, $to_column);
$this->_join_table = $join_table;
$this->_from_join_column = $from_join_column;
$this->_to_join_column = $to_join_column;
}
public function setFromTable($table) {
$this->_from_table = $table;
$this->_guessFromColumn();
$this->_guessFromJoinColumn();
$this->_guessToJoinColumn();
$this->_guessToColumn();
}
public function getJoinTable() {
return $this->_join_table;
}
public function setJoinTable($table) {
$this->_join_table = $table;
}
public function getFromJoinColumn() {
return $this->_from_join_column;
}
public function setFromJoinColumn($column) {
$this->_from_join_column = $column;
}
public function getToJoinColumn() {
return $this->_to_join_column;
}
public function setToJoinColumn($column) {
$this->_to_join_column = $column;
}
protected function _guessFromColumn() {
if(null == $this->_from_column) {
$guess = $this->_from_table->getPrimaryKey();
$this->setFromColumn($guess);
}
}
protected function _guessFromJoinColumn() {
if(null === $this->_from_join_column) {
$guess = $this->_from_table->getSingularName() . '_id';
if($this->_join_table->hasColumn($guess)) {
$this->setFromJoinColumn($guess);
} else {
throw new \Exception("Unable to guess from_join_column and none specified");
}
}
}
protected function _guessToJoinColumn() {
if(null === $this->_to_join_column) {
$guess = $this->_to_table->getSingularName() . '_id';
if($this->_join_table->hasColumn($guess)) {
$this->setToJoinColumn($guess);
} else {
throw new \Exception("Unable to guess from_join_column and none specified");
}
}
}
protected function _guessToColumn() {
if(null == $this->_to_column) {
$guess = $this->_to_table->getPrimaryKey();
$this->setToColumn($guess);
}
}
}
| php | MIT | 054cac8f6a5ab6e3da7a5bcead71c7e173c16389 | 2026-01-05T04:39:52.269416Z | false |
christiaan/InlineStyle | https://github.com/christiaan/InlineStyle/blob/9c408760465f4e3ef2b5fb08cb6995e3233afa98/InlineStyle/InlineStyle.php | InlineStyle/InlineStyle.php | <?php
namespace InlineStyle;
/*
* InlineStyle MIT License
*
* Copyright (c) 2012 Christiaan Baartse
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use Symfony\Component\CssSelector\Exception\ParseException;
/**
* Parses a html file and applies all embedded and external stylesheets inline
*/
class InlineStyle
{
/**
* @var \DOMDocument the HTML as DOMDocument
*/
private $_dom;
/**
* Prepare all the necessary objects
*
* @param string $html
*/
public function __construct($html = '')
{
if ($html) {
if ($html instanceof \DOMDocument) {
$this->loadDomDocument(clone $html);
} else if (strlen($html) <= PHP_MAXPATHLEN && file_exists($html)) {
$this->loadHTMLFile($html);
} else {
$this->loadHTML($html);
}
}
}
/**
* Load HTML file
*
* @param string $filename
*/
public function loadHTMLFile($filename)
{
$this->loadHTML(file_get_contents($filename));
}
/**
* Load HTML string (UTF-8 encoding assumed)
*
* @param string $html
*/
public function loadHTML($html)
{
$dom = new \DOMDocument();
$dom->formatOutput = true;
// strip illegal XML UTF-8 chars
// remove all control characters except CR, LF and tab
$html = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', '', $html); // 00-09, 11-31, 127
$dom->loadHTML($html);
$this->loadDomDocument($dom);
}
/**
* Load the HTML as a DOMDocument directly
*
* @param \DOMDocument $domDocument
*/
public function loadDomDocument(\DOMDocument $domDocument)
{
$this->_dom = $domDocument;
foreach ($this->_getNodesForCssSelector('[style]') as $node) {
$node->setAttribute(
'inlinestyle-original-style',
$node->getAttribute('style')
);
}
}
/**
* Applies one or more stylesheets to the current document
*
* @param string|string[] $stylesheet
* @return InlineStyle self
*/
public function applyStylesheet($stylesheet)
{
$stylesheet = (array) $stylesheet;
foreach($stylesheet as $ss) {
$parsed = $this->parseStylesheet($ss);
$parsed = $this->sortSelectorsOnSpecificity($parsed);
foreach($parsed as $arr) {
list($selector, $style) = $arr;
$this->applyRule($selector, $style);
}
}
return $this;
}
/**
* @param string $sel Css Selector
* @return array|\DOMNodeList|\DOMElement[]
*/
private function _getNodesForCssSelector($sel)
{
try {
if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
$converter = new \Symfony\Component\CssSelector\CssSelectorConverter(true);
$xpathQuery = $converter->toXPath($sel);
} else {
$xpathQuery = \Symfony\Component\CssSelector\CssSelector::toXPath($sel);
}
return $this->_getDomXpath()->query($xpathQuery);
}
catch(ParseException $e) {
// ignore css rule parse exceptions
}
return array();
}
/**
* Applies a style rule on the document
* @param string $selector
* @param string $style
* @return InlineStyle self
*/
public function applyRule($selector, $style)
{
if($selector) {
$nodes = $this->_getNodesForCssSelector($selector);
$style = $this->_styleToArray($style);
foreach($nodes as $node) {
$current = $node->hasAttribute("style") ?
$this->_styleToArray($node->getAttribute("style")) :
array();
$current = $this->_mergeStyles($current, $style);
$node->setAttribute("style", $this->_arrayToStyle($current));
}
}
return $this;
}
/**
* Returns the DOMDocument as html
*
* @return string the HTML
*/
public function getHTML()
{
$clone = clone $this;
foreach ($clone->_getNodesForCssSelector('[inlinestyle-original-style]') as $node) {
$current = $node->hasAttribute("style") ?
$this->_styleToArray($node->getAttribute("style")) :
array();
$original = $node->hasAttribute("inlinestyle-original-style") ?
$this->_styleToArray($node->getAttribute("inlinestyle-original-style")) :
array();
$current = $clone->_mergeStyles($current, $original);
$node->setAttribute("style", $this->_arrayToStyle($current));
$node->removeAttribute('inlinestyle-original-style');
}
return $clone->_dom->saveHTML();
}
/**
* Recursively extracts the stylesheet nodes from the DOMNode
*
* This cannot be done with XPath or a CSS selector because the order in
* which the elements are found matters
*
* @param \DOMNode $node leave empty to extract from the whole document
* @param string $base The base URI for relative stylesheets
* @param array $devices Considered devices
* @param boolean $remove Should it remove the original stylesheets
* @return array the extracted stylesheets
*/
public function extractStylesheets($node = null, $base = '', $devices = array('all', 'screen', 'handheld'), $remove = true)
{
if(null === $node) {
$node = $this->_dom;
}
$stylesheets = array();
if($node->hasChildNodes()) {
$removeQueue = array();
/** @var $child \DOMElement */
foreach($node->childNodes as $child) {
$nodeName = strtolower($child->nodeName);
if($nodeName === "style" && $this->isForAllowedMediaDevice($child->getAttribute('media'), $devices)) {
$stylesheets[] = $child->nodeValue;
$removeQueue[] = $child;
} else if($nodeName === "link" && strtolower($child->getAttribute('rel')) === 'stylesheet' && $this->isForAllowedMediaDevice($child->getAttribute('media'), $devices)) {
if($child->hasAttribute("href")) {
$href = $child->getAttribute("href");
if($base && false === strpos($href, "://")) {
$href = "{$base}/{$href}";
}
$ext = @file_get_contents($href);
if($ext) {
$removeQueue[] = $child;
$stylesheets[] = $ext;
}
}
} else {
$stylesheets = array_merge($stylesheets,
$this->extractStylesheets($child, $base, $devices, $remove));
}
}
if ($remove) {
foreach ($removeQueue as $child) {
$child->parentNode->removeChild($child);
}
}
}
return $stylesheets;
}
/**
* Extracts the stylesheet nodes nodes specified by the xpath
*
* @param string $xpathQuery xpath query to the desired stylesheet
* @return array the extracted stylesheets
*/
public function extractStylesheetsWithXpath($xpathQuery)
{
$stylesheets = array();
$nodes = $this->_getDomXpath()->query($xpathQuery);
foreach ($nodes as $node)
{
$stylesheets[] = $node->nodeValue;
$node->parentNode->removeChild($node);
}
return $stylesheets;
}
/**
* Parses a stylesheet to selectors and properties
* @param string $stylesheet
* @return array
*/
public function parseStylesheet($stylesheet)
{
$parsed = array();
$stylesheet = $this->_stripStylesheet($stylesheet);
$stylesheet = trim(trim($stylesheet), "}");
foreach(explode("}", $stylesheet) as $rule) {
//Don't parse empty rules
if(!trim($rule))continue;
list($selector, $style) = explode("{", $rule, 2);
foreach (explode(',', $selector) as $sel) {
$parsed[] = array(trim($sel), trim(trim($style), ";"));
}
}
return $parsed;
}
public function sortSelectorsOnSpecificity($parsed)
{
usort($parsed, array($this, 'sortOnSpecificity'));
return $parsed;
}
private function sortOnSpecificity($a, $b)
{
$a = $this->getScoreForSelector($a[0]);
$b = $this->getScoreForSelector($b[0]);
foreach (range(0, 2) as $i) {
if ($a[$i] !== $b[$i]) {
return $a[$i] < $b[$i] ? -1 : 1;
}
}
return -1;
}
public function getScoreForSelector($selector)
{
return array(
preg_match_all('/#\w/i', $selector, $result), // ID's
preg_match_all('/\.\w/i', $selector, $result), // Classes
preg_match_all('/^\w|\ \w|\(\w|\:[^not]/i', $selector, $result) // Tags
);
}
/**
* Parses style properties to a array which can be merged by mergeStyles()
* @param string $style
* @return array
*/
private function _styleToArray($style)
{
$styles = array();
$style = trim(trim($style), ";");
if($style) {
foreach(explode(";", $style) as $props) {
$props = trim(trim($props), ";");
//Don't parse empty props
if(!trim($props))continue;
//Only match valid CSS rules
if (preg_match('#^([-a-z0-9\*]+):(.*)$#i', $props, $matches) && isset($matches[0], $matches[1], $matches[2])) {
list(, $prop, $val) = $matches;
$styles[$prop] = $val;
}
}
}
return $styles;
}
private function _arrayToStyle($array)
{
$st = array();
foreach($array as $prop => $val) {
$st[] = "{$prop}:{$val}";
}
return \implode(';', $st);
}
/**
* Merges two sets of style properties taking !important into account
* @param array $styleA
* @param array $styleB
* @return array
*/
private function _mergeStyles(array $styleA, array $styleB)
{
foreach($styleB as $prop => $val) {
if(!isset($styleA[$prop])
|| substr(str_replace(" ", "", strtolower($styleA[$prop])), -10) !== "!important")
{
$styleA[$prop] = $val;
}
}
return $styleA;
}
private function _stripStylesheet($s)
{
// strip comments
$s = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','', $s);
// strip keyframes rules
$s = preg_replace('/@[-|keyframes].*?\{.*?\}[ \r\n]*\}/s', '', $s);
return $s;
}
private function _getDomXpath()
{
return new \DOMXPath($this->_dom);
}
public function __clone()
{
$this->_dom = clone $this->_dom;
}
private function isForAllowedMediaDevice($mediaAttribute, array $devices)
{
$mediaAttribute = strtolower($mediaAttribute);
$mediaDevices = explode(',', $mediaAttribute);
foreach ($mediaDevices as $device) {
$device = trim($device);
if (!$device || in_array($device, $devices)) {
return true;
}
}
return false;
}
}
| php | MIT | 9c408760465f4e3ef2b5fb08cb6995e3233afa98 | 2026-01-05T04:39:55.087909Z | false |
christiaan/InlineStyle | https://github.com/christiaan/InlineStyle/blob/9c408760465f4e3ef2b5fb08cb6995e3233afa98/InlineStyle/Tests/InlineStyleTest.php | InlineStyle/Tests/InlineStyleTest.php | <?php
namespace InlineStyle\Tests;
/**
* Test class for InlineStyle.
* Generated by PHPUnit on 2010-03-10 at 21:52:44.
*/
use InlineStyle\InlineStyle;
class InlineStyleTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \InlineStyle\InlineStyle
*/
protected $object;
protected $basedir;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->basedir = __DIR__."/testfiles";
$this->object = new InlineStyle($this->basedir."/test.html");
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
unset($this->object);
}
public function testGetHTML()
{
$this->assertEquals(
file_get_contents($this->basedir."/testGetHTML.html"),
$this->object->getHTML());
}
public function testApplyStyleSheet()
{
$this->object->applyStyleSheet("p:not(.p2) { color: red }");
$this->assertEquals(
file_get_contents($this->basedir."/testApplyStylesheet.html"),
$this->object->getHTML());
}
public function testApplyRule()
{
$this->object->applyRule("p:not(.p2)", "color: red");
$this->assertEquals(
file_get_contents($this->basedir."/testApplyStylesheet.html"),
$this->object->getHTML());
}
public function testExtractStylesheets()
{
$stylesheets = $this->object->extractStylesheets(null, $this->basedir);
$this->assertEquals(include $this->basedir."/testExtractStylesheets.php",$stylesheets);
}
public function testApplyExtractedStylesheet()
{
$stylesheets = $this->object->extractStylesheets(null, $this->basedir);
$this->object->applyStylesheet($stylesheets);
$this->assertEquals(
file_get_contents($this->basedir."/testApplyExtractedStylesheet.html"),
$this->object->getHTML());
}
public function testParseStyleSheet()
{
$parsed = $this->object->parseStylesheet("p:not(.p2) { color: red }");
$this->assertEquals(
array(array("p:not(.p2)", "color: red")),
$parsed);
}
public function testParseStyleSheetWithComments()
{
$parsed = $this->object->parseStylesheet("p:not(.p2) { /* blah */ color: red }");
$this->assertEquals(
array(array("p:not(.p2)", "color: red")),
$parsed);
}
public function testIllegalXmlUtf8Chars()
{
// check an exception is not thrown when loading up illegal XML UTF8 chars
new InlineStyle("<html><body>".chr(2).chr(3).chr(4).chr(5)."</body></html>");
}
public function testGetScoreForSelector()
{
$this->assertEquals(
array(1,1,3),
$this->object->getScoreForSelector('ul#nav li.active a'),
'ul#nav li.active a'
);
$this->assertEquals(
array(0,2,3),
$this->object->getScoreForSelector('body.ie7 .col_3 h2 ~ h2'),
'body.ie7 .col_3 h2 ~ h2'
);
$this->assertEquals(
array(1,0,2),
$this->object->getScoreForSelector('#footer *:not(nav) li'),
'#footer *:not(nav) li'
);
$this->assertEquals(
array(0,0,7),
$this->object->getScoreForSelector('ul > li ul li ol li:first-letter'),
'ul > li ul li ol li:first-letter'
);
}
function testSortingParsedStylesheet()
{
$parsed = $this->object->parseStylesheet(<<<CSS
ul#nav li.active a, body.ie7 .col_3 h2 ~ h2 {
color: blue;
}
ul > li ul li ol li:first-letter {
color: red;
}
CSS
);
$this->assertEquals(array (
array (
'ul#nav li.active a',
'color: blue',
),
array (
'body.ie7 .col_3 h2 ~ h2',
'color: blue',
),
array (
'ul > li ul li ol li:first-letter',
'color: red',
),
), $parsed);
$parsed = $this->object->sortSelectorsOnSpecificity($parsed);
$this->assertEquals(array (
array (
'ul > li ul li ol li:first-letter',
'color: red',
),
array (
'body.ie7 .col_3 h2 ~ h2',
'color: blue',
),
array (
'ul#nav li.active a',
'color: blue',
),
), $parsed);
}
function testApplyStylesheetObeysSpecificity()
{
$this->object->applyStylesheet(<<<CSS
p {
color: red;
}
.p2 {
color: blue;
}
p.p2 {
color: green;
}
CSS
);
$this->assertEquals(
file_get_contents($this->basedir."/testApplyStylesheetObeysSpecificity.html"),
$this->object->getHTML());
}
function testDocDocumentDirectly()
{
$dom = new \DOMDocument();
$dom->formatOutput = false;
$dom->loadHTML('<!doctype html><html><body><div></div></body></html>');
$this->object->loadDomDocument($dom);
$this->object->applyRule('div', 'color: red');
$this->assertEquals('<!DOCTYPE html>
<html><body><div style="color: red"></div></body></html>
', $dom->saveHTML());
}
/**
* Regression test for #14 Selectors are sometimes sorted into the wrong cascading order
*/
function testSortingOnSpecifitySameSpecificity()
{
$parsed = $this->object->parseStylesheet(<<<CSS
ul {
color: blue;
}
ul.class {
color: green;
}
ul {
color: red;
}
CSS
);
$parsed = $this->object->sortSelectorsOnSpecificity($parsed);
$this->assertEquals(array(
array(
'ul',
'color: blue'
),
array(
'ul',
'color: red'
),
array(
'ul.class',
'color: green'
),
), $parsed);
}
function testNonWorkingPseudoSelectors()
{
// Regressiontest for #5
$this->object->applyStylesheet(<<<CSS
ul#nav li.active a:link, body.ie7 .col_3:visited h2 ~ h2 {
color: blue;
}
ul > li ul li:active ol li:first-letter {
color: red;
}
CSS
);
}
/**
* Regression tests for #10 _styleToArray crashes when presented with an invalid property name
*/
function testInvalidCssProperties()
{
$this->object->applyStylesheet(<<<CSS
ul {
asohdtoairet;
garbage: )&%)*(%);
}
CSS
);
}
function testRegression24() {
$content = '<p style="text-align:center;">Hello World!</p>';
$htmldoc = new InlineStyle($content);
$htmldoc->applyStylesheet('p{
text-align: left;
}');
$expected = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p style="text-align:center">Hello World!</p></body></html>
HTML;
$this->assertEquals($expected, $htmldoc->getHTML());
$htmldoc->applyStylesheet('p{
text-align: left;
}');
$this->assertEquals($expected, $htmldoc->getHTML());
}
function testMultipleStylesheets28() {
$htmldoc = new InlineStyle(file_get_contents($this->basedir . '/testMultipleStylesheets.html'));
$htmldoc->applyStylesheet($htmldoc->extractStylesheets(null, $this->basedir));
$expected = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><title>Example</title></head>
<body>
<p style='margin:0;padding:0 0 10px 0;background-image: url("someimage.jpg")'>Paragraph</p>
<strong style="font-weight: bold">Strong</strong>
<br>
</body>
</html>
HTML;
$this->assertEquals($expected, $htmldoc->getHTML());
}
function testMediaStylesheets31() {
$htmldoc = new InlineStyle(file_get_contents($this->basedir . '/testMediaStylesheets31.html'));
$htmldoc->applyStylesheet($htmldoc->extractStylesheets(null, $this->basedir));
$expected = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><title>Example</title></head>
<body>
<style type="text/css" media="print">
h1{
display:none;
}
</style>
<h1 style="color:yellow">An example title</h1>
<p style="color:yellow !important;line-height:1.5em">Paragraph 1</p>
</body>
</html>
HTML;
$this->assertEquals($expected, $htmldoc->getHTML());
}
function testLinkedMediaStylesheets31() {
$htmldoc = new InlineStyle(file_get_contents($this->basedir . '/testLinkedMediaStylesheets31.html'));
$htmldoc->applyStylesheet($htmldoc->extractStylesheets(null, $this->basedir));
$expected = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Example</title>
<link rel="stylesheet" href="external.css" media="print">
</head>
<body>
<h1>An example title</h1>
<p>Paragraph <strong style="font-weight: bold">1</strong></p>
</body>
</html>
HTML;
$this->assertEquals($expected, $htmldoc->getHTML());
}
}
| php | MIT | 9c408760465f4e3ef2b5fb08cb6995e3233afa98 | 2026-01-05T04:39:55.087909Z | false |
christiaan/InlineStyle | https://github.com/christiaan/InlineStyle/blob/9c408760465f4e3ef2b5fb08cb6995e3233afa98/InlineStyle/Tests/testfiles/testExtractStylesheets.php | InlineStyle/Tests/testfiles/testExtractStylesheets.php | <?php return array(
'p{
margin:0;
padding:0 0 10px 0;
background-image: url("someimage.jpg");
}
a:hover{
color:Red;
}
p:hover{
color:blue;
}
@-webkit-keyframes test {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}','
h1{
color:yellow
}
p {
color:yellow !important;
}
p {
color:blue
}
'); | php | MIT | 9c408760465f4e3ef2b5fb08cb6995e3233afa98 | 2026-01-05T04:39:55.087909Z | false |
waza-ari/monolog-mysql | https://github.com/waza-ari/monolog-mysql/blob/c0bbb13e916ed56f25b6543715e50b7d4782832d/src/MySQLRecord.php | src/MySQLRecord.php | <?php
declare(strict_types=1);
namespace MySQLHandler;
/**
* Class MySQLRecord
* @package MySQLHandler
*/
class MySQLRecord
{
/**
* the table to store the logs in
*
* @var string
*/
private $table;
/**
* default columns that are stored in db
*
* @var array|string[]
*/
private $defaultColumns;
/**
* additional fields to be stored in the database
*
* For each field $field, an additional context field with the name $field
* is expected along the message, and further the database needs to have these fields
* as the values are stored in the column name $field.
*
* @var array
*/
private $additionalColumns;
/**
* MySQLRecord constructor.
* @param string $table
* @param array $additionalColumns
*/
public function __construct(string $table, array $additionalColumns = [])
{
$this->table = $table;
$this->defaultColumns = [
'id',
'channel',
'level',
'message',
'time',
];
$this->additionalColumns = $additionalColumns;
}
/**
* @param array $content
* @return array
*/
public function filterContent(array $content): array
{
return array_filter($content, function($key) {
return in_array($key, $this->getColumns());
}, ARRAY_FILTER_USE_KEY);
}
/**
* @return string
*/
public function getTable(): string
{
return $this->table;
}
/**
* @return array|string[]
*/
public function getDefaultColumns()
{
return $this->defaultColumns;
}
/**
* @return array
*/
public function getAdditionalColumns(): array
{
return $this->additionalColumns;
}
/**
* @return array
*/
public function getColumns(): array
{
return array_merge($this->defaultColumns, $this->additionalColumns);
}
} | php | MIT | c0bbb13e916ed56f25b6543715e50b7d4782832d | 2026-01-05T04:40:04.829207Z | false |
waza-ari/monolog-mysql | https://github.com/waza-ari/monolog-mysql/blob/c0bbb13e916ed56f25b6543715e50b7d4782832d/src/MySQLHandler.php | src/MySQLHandler.php | <?php
declare(strict_types=1);
namespace MySQLHandler;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use PDO;
use PDOStatement;
/**
* This class is a handler for Monolog, which can be used
* to write records in a MySQL table
*
* Class MySQLHandler
* @package wazaari\MysqlHandler
*/
class MySQLHandler extends AbstractProcessingHandler
{
/**
* defines whether the MySQL connection is been initialized
*
* @var bool
*/
private $initialized;
/**
* pdo object of database connection
*
* @var PDO
*/
protected $pdo;
/**
* statement to insert a new record
*
* @var PDOStatement
*/
private $statement;
/**
* @var MySQLRecord
*/
private $mySQLRecord;
/**
* Constructor of this class, sets the PDO and calls parent constructor
*
* @param PDO $pdo PDO Connector for the database
* @param string $table Table in the database to store the logs in
* @param array $additionalFields Additional Context Parameters to store in database
* @param bool $initialize Defines whether attempts to alter database should be skipped
* @param bool|int $level Debug level which this handler should store
* @param bool $bubble
*/
public function __construct(
PDO $pdo,
string $table,
array $additionalFields = [],
bool $initialize = false,
int $level = Logger::DEBUG,
bool $bubble = true
) {
parent::__construct($level, $bubble);
$this->pdo = $pdo;
$this->initialized = $initialize;
$this->mySQLRecord = new MySQLRecord($table, $additionalFields);
}
/**
* Initializes this handler by creating the table if it not exists
*/
private function initialize(): void
{
$this->pdo->exec("
CREATE TABLE IF NOT EXISTS `{$this->mySQLRecord->getTable()}` (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
channel VARCHAR(255),
level INTEGER,
message LONGTEXT,
time INTEGER UNSIGNED,
INDEX(channel) USING HASH,
INDEX(level) USING HASH,
INDEX(time) USING BTREE
);
");
//Read out actual columns
$actualFields = [];
$rs = $this->pdo->query("SELECT * FROM `{$this->mySQLRecord->getTable()}` LIMIT 0;");
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$actualFields[] = $col['name'];
}
//Calculate changed entries
$removedColumns = array_diff(
$actualFields,
$this->mySQLRecord->getAdditionalColumns(),
$this->mySQLRecord->getDefaultColumns()
);
$addedColumns = array_diff($this->mySQLRecord->getAdditionalColumns(), $actualFields);
//Remove columns
if (! empty($removedColumns)) {
foreach ($removedColumns as $c) {
$this->pdo->exec("ALTER TABLE `{$this->mySQLRecord->getTable()}` DROP `$c`;");
}
}
//Add columns
if (! empty($addedColumns)) {
foreach ($addedColumns as $c) {
$this->pdo->exec(
"ALTER TABLE `{$this->mySQLRecord->getTable()}` ADD `{$c}` TEXT NULL DEFAULT NULL;"
);
}
}
$this->initialized = true;
}
/**
* Prepare the sql statment depending on the fields that should be written to the database
* @param array $content
*/
private function prepareStatement(array $content): void
{
$columns = '';
$fields = '';
foreach (array_keys($content) as $key => $f) {
if ($f == 'id') {
continue;
}
if (empty($columns)) {
$columns .= $f;
$fields .= ":{$f}";
continue;
}
$columns .= ", {$f}";
$fields .= ", :{$f}";
}
$this->statement = $this->pdo->prepare(
"INSERT INTO `{$this->mySQLRecord->getTable()}` ({$columns}) VALUES ({$fields});"
);
}
/**
* Writes the record down to the log of the implementing handler
*
* @param array $record
* @return void
*/
protected function write(array $record): void
{
if (! $this->initialized) {
$this->initialize();
}
/*
* merge $record['context'] and $record['extra'] as additional info of Processors
* getting added to $record['extra']
* @see https://github.com/Seldaek/monolog/blob/master/doc/02-handlers-formatters-processors.md
*/
if (isset($record['extra'])) {
$record['context'] = array_merge($record['context'], $record['extra']);
}
$content = $this->mySQLRecord->filterContent(array_merge([
'channel' => $record['channel'],
'level' => $record['level'],
'message' => $record['message'],
'time' => $record['datetime']->format('U'),
], $record['context']));
$this->prepareStatement($content);
$this->statement->execute($content);
}
}
| php | MIT | c0bbb13e916ed56f25b6543715e50b7d4782832d | 2026-01-05T04:40:04.829207Z | false |
waza-ari/monolog-mysql | https://github.com/waza-ari/monolog-mysql/blob/c0bbb13e916ed56f25b6543715e50b7d4782832d/tests/MySQLRecordTest.php | tests/MySQLRecordTest.php | <?php
declare(strict_types=1);
namespace Tests;
use Faker\Factory;
use Monolog\Logger;
use MySQLHandler\MySQLRecord;
use PHPUnit\Framework\TestCase;
/**
* Class MySQLRecordTest
* @package Tests
*/
class MySQLRecordTest extends TestCase
{
/**
* @test
* @return void
*/
public function get_columns_will_equals_default_columns_and_additional_columns_merge(): void
{
$faker = Factory::create();
$table = strtolower($faker->unique()->word);
$columns = array_pad([], 5, strtolower($faker->unique()->word));
$record = new MySQLRecord($table, $columns);
$this->assertEquals(array_merge([
'id',
'channel',
'level',
'message',
'time',
], $columns), $record->getColumns());
}
/**
* @test
* @return void
*/
public function filter_content_will_equals_argument(): void
{
$faker = Factory::create();
$table = strtolower($faker->unique()->word);
$columns = array_pad([], 5, strtolower($faker->unique()->word));
$record = new MySQLRecord($table, $columns);
$data = array_merge([
'channel' => strtolower($faker->unique()->word),
'level' => $faker->randomElement(Logger::getLevels()),
'message' => $faker->text,
'time' => $faker->dateTime,
], array_fill_keys($columns, $faker->text));
$content = $record->filterContent($data);
$this->assertEquals($data, $content);
}
/**
* @test
* @return void
*/
public function filter_content_will_exclude_out_of_columns(): void
{
$faker = Factory::create();
$table = strtolower($faker->unique()->word);
$columns = array_pad([], 5, strtolower($faker->unique()->word));
$outOfColumns = array_pad([], 5, strtolower($faker->unique()->word));
$record = new MySQLRecord($table, $columns);
$data = array_merge([
'channel' => strtolower($faker->unique()->word),
'level' => $faker->randomElement(Logger::getLevels()),
'message' => $faker->text,
'time' => $faker->dateTime,
], array_fill_keys($outOfColumns, $faker->text));
$content = $record->filterContent($data);
$this->assertNotEquals($data, $content);
$this->assertArrayHasKey('channel', $content);
$this->assertArrayHasKey('level', $content);
$this->assertArrayHasKey('message', $content);
$this->assertArrayHasKey('time', $content);
array_map(function ($key) use ($content) {
$this->assertArrayNotHasKey($key, $content);
}, $outOfColumns);
}
} | php | MIT | c0bbb13e916ed56f25b6543715e50b7d4782832d | 2026-01-05T04:40:04.829207Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/client.php | client.php | <?php
require '/Users/jwage/Sites/doctrine2git/lib/Doctrine/Common/ClassLoader.php';
use Doctrine\REST\Client\Client,
Doctrine\REST\Client\EntityConfiguration,
Doctrine\REST\Client\Manager,
Doctrine\REST\Client\Entity,
Doctrine\Common\ClassLoader;
$classLoader = new ClassLoader('Doctrine\REST', __DIR__ . '/lib');
$classLoader->register();
$client = new Client();
$manager = new Manager($client);
$manager->registerEntity('User');
Entity::setManager($manager);
class User extends Entity
{
public $id;
public $username;
public $password;
public static function configure(EntityConfiguration $entityConfiguration)
{
$entityConfiguration->setUrl('http://localhost/rest/server.php');
$entityConfiguration->setName('user');
}
}
$user = User::find(9);
$user->username = 'teetertertsting';
$user->password = 'w00t';
$user->save();
print_r($user); | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/server.php | server.php | <?php
use Doctrine\REST\Server\Server,
Doctrine\Common\ClassLoader;
require '/Users/jwage/Sites/doctrine2git/lib/Doctrine/Common/ClassLoader.php';
$classLoader = new ClassLoader('Doctrine\REST', __DIR__ . '/lib');
$classLoader->register();
$classLoader = new ClassLoader('Doctrine', '/Users/jwage/Sites/doctrine2git/lib');
$classLoader->register();
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
$config->setProxyDir('/tmp');
$config->setProxyNamespace('Proxies');
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
$connectionOptions = array(
'driver' => 'pdo_mysql',
'dbname' => 'rest_test',
'user' => 'root'
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$parser = new \Doctrine\REST\Server\PHPRequestParser();
$requestData = $parser->getRequestArray();
class TestAction
{
public function executeDBAL()
{
return array('test' => 'test');
}
}
$server = new \Doctrine\REST\Server\Server($em->getConnection(), $requestData);
$server->addEntityAction('user', 'test', 'TestAction');
$server->execute();
$server->getResponse()->send(); | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/tests/Doctrine/Tests/DoctrineTestCase.php | tests/Doctrine/Tests/DoctrineTestCase.php | <?php
namespace Doctrine\Tests;
/**
* Base testcase class for all Doctrine testcases.
*/
abstract class DoctrineTestCase extends \PHPUnit_Framework_TestCase
{
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/tests/Doctrine/Tests/TestInit.php | tests/Doctrine/Tests/TestInit.php | <?php
namespace Doctrine\Tests\REST;
/*
* This file bootstraps the test environment.
*/
error_reporting(E_ALL | E_STRICT);
// register silently failing autoloader
spl_autoload_register(function ($class) {
if (0 === strpos($class, 'Doctrine\Tests\\')) {
$path = __DIR__.'/../../'.strtr($class, '\\', '/').'.php';
if (is_file($path) && is_readable($path)) {
require_once $path;
return true;
}
}
});
require_once realpath(__DIR__ . "/../../../") . "/vendor/autoload.php";
| php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/tests/Doctrine/Tests/REST/ClientTest.php | tests/Doctrine/Tests/REST/ClientTest.php | <?php
namespace Doctrine\Tests\REST;
use Doctrine\REST\Client\Client;
use Doctrine\REST\Client\Entity;
use Doctrine\REST\Client\EntityConfiguration;
use Doctrine\REST\Client\Manager;
use Doctrine\REST\Client\Request;
use Doctrine\Tests\DoctrineTestCase;
class ClientTest extends DoctrineTestCase
{
public function setUp()
{
$this->client = new TestClient();
$manager = new Manager($this->client);
$manager->registerEntity('Doctrine\Tests\REST\ClientArticleTest');
$manager->registerEntity('Doctrine\Tests\REST\Status');
Entity::setManager($manager);
}
public function testGetPath()
{
$this->assertEquals('http://api.people.com/article/1.xml', ClientArticleTest::generateUrl(array('id' => 1)));
$this->assertEquals('http://api.people.com/article/1/test.xml', ClientArticleTest::generateUrl(array('id' => 1, 'action' => 'test')));
$this->assertEquals('http://api.people.com/article.xml', ClientArticleTest::generateUrl());
$this->assertEquals('http://api.people.com/article/test.xml', ClientArticleTest::generateUrl(array('action' => 'test')));
$this->assertEquals('http://api.people.com/article.xml?test=test', ClientArticleTest::generateUrl(array('parameters' => array('test' => 'test'))));
}
public function testInsert()
{
$test = new ClientArticleTest();
$test->setTitle('testing');
$test->save();
$this->assertEquals(1, $test->getId());
$this->assertEquals('http://api.people.com/article.xml', $this->client->last['url']);
$this->assertEquals('PUT', $this->client->last['method']);
}
public function testUpdate()
{
$test = new ClientArticleTest();
$test->setId(1);
$test->setTitle('test');
$test->save();
$this->assertEquals('test', $test->getTitle());
$this->assertEquals('http://api.people.com/article/1.xml', $this->client->last['url']);
$this->assertEquals('POST', $this->client->last['method']);
}
public function testDelete()
{
$test = new ClientArticleTest();
$test->setId(1);
$test->delete();
$this->assertEquals('http://api.people.com/article/1.xml', $this->client->last['url']);
$this->assertEquals('DELETE', $this->client->last['method']);
}
public function testFind()
{
$test = ClientArticleTest::find(1);
$this->assertEquals('test', $test->getTitle());
$this->assertEquals('http://api.people.com/article/1.xml', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testFindWithAction()
{
$test = ClientArticleTest::find(1, 'test');
$this->assertEquals('http://api.people.com/article/1/test.xml', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testFindAll()
{
$test = ClientArticleTest::findAll();
$this->assertEquals(2, count($test));
$one = $test[0];
$two = $test[1];
$this->assertEquals(1, $one->getId());
$this->assertEquals('test1', $one->getTitle());
$this->assertEquals(2, $two->getId());
$this->assertEquals('test2', $two->getTitle());
$this->assertEquals('http://api.people.com/article.xml', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testFindAllWithAction()
{
$test = ClientArticleTest::findAll('test');
$this->assertEquals('http://api.people.com/article/test.xml', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testFindAllWithParameters()
{
$test = ClientArticleTest::findAll(null, array('test' => 'test'));
$this->assertEquals('http://api.people.com/article.xml?test=test', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testExecute()
{
$test = ClientArticleTest::execute(Client::GET, 'test', array('test' => 'test'));
$this->assertEquals('http://api.people.com/article/test.xml?test=test', $this->client->last['url']);
$this->assertEquals('GET', $this->client->last['method']);
}
public function testTwitterStatus()
{
$test = Status::execute(Client::POST, 'update', array('status' => 'updating my status'));
$this->assertEquals('http://twitter.com/statuses/update.xml', $this->client->last['url']);
$this->assertEquals('POST', $this->client->last['method']);
$this->assertEquals(array('status' => 'updating my status'), $this->client->last['parameters']);
$this->assertEquals('username', $this->client->last['username']);
$this->assertEquals('password', $this->client->last['password']);
}
}
class Status extends Entity
{
private $id;
private $status;
private $text;
public static function configure(EntityConfiguration $entityConfiguration)
{
$entityConfiguration->setUrl('http://twitter.com');
$entityConfiguration->setName('statuses');
$entityConfiguration->setUsername('username');
$entityConfiguration->setPassword('password');
}
}
class ClientArticleTest extends Entity
{
private $id;
private $title;
public static function configure(EntityConfiguration $entityConfiguration)
{
$entityConfiguration->setUrl('http://api.people.com');
$entityConfiguration->setName('article');
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class TestClient extends Client
{
public $last;
public function execute(Request $request)
{
$url = $request->getUrl();
$method = $request->getMethod();
$parameters = $request->getParameters();
$username = $request->getUsername();
$password = $request->getPassword();
$this->last = get_defined_vars();
if ($url === 'http://api.people.com/article.xml') {
if ($method === Client::PUT)
{
return array('id' => 1, 'title' => 'test');
} else if ($method === Client::POST) {
return $parameters;
} else if ($method === Client::GET) {
return array(
'article' => array(
array(
'id' => 1,
'title' => 'test1'
),
array(
'id' => 2,
'title' => 'test2'
)
)
);
}
return array();
} else if ($url === 'http://api.people.com/article/1.xml') {
if ($method === Client::DELETE) {
return array('id' => 1, 'title' => 'test');
} else if ($method === Client::GET) {
return array('id' => 1, 'title' => 'test');
}
}
return array();
}
}
| php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/tests/Doctrine/Tests/REST/FunctionalTest.php | tests/Doctrine/Tests/REST/FunctionalTest.php | <?php
namespace Doctrine\Tests\REST;
use Doctrine\ORM\EntityManager;
use Doctrine\REST\Client\Manager;
use Doctrine\REST\Client\Request;
use Doctrine\REST\Client\Entity;
use Doctrine\REST\Client\EntityConfiguration;
use Doctrine\REST\Client\Client;
use Doctrine\REST\Server\Server;
use Doctrine\Tests\DoctrineTestCase;
class FunctionalTest extends DoctrineTestCase
{
private $_manager;
private $_client;
public function setUpRest($type)
{
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
$config->setProxyDir('/tmp');
$config->setProxyNamespace('Proxies');
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
$connectionOptions = array(
'driver' => 'pdo_sqlite',
'memory' => true
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$classes = array($em->getMetadataFactory()->getMetadataFor('Doctrine\Tests\REST\DoctrineUser'));
$schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em);
$schemaTool->dropSchema($classes);
$schemaTool->createSchema($classes);
if ($type === 'orm') {
$this->_client = new TestFunctionalClient('user', $em);
} else {
$this->_client = new TestFunctionalClient('user', $em->getConnection());
}
$this->_manager = new Manager($this->_client);
$this->_manager->registerEntity('Doctrine\Tests\REST\User');
Entity::setManager($this->_manager);
}
public function testOrm()
{
$this->setUpRest('orm');
$this->_testActiveRecordApi();
}
public function testDbal()
{
$this->setUpRest('dbal');
$this->_testActiveRecordApi();
}
private function _testActiveRecordApi()
{
$user1 = new User();
$user1->setUsername('jwage');
$user1->save();
$this->assertEquals(1, $user1->getId());
$user2 = new User();
$user2->setUsername('fabpot');
$user2->save();
$this->assertEquals(2, $user2->getId());
$user3 = new User();
$user3->setUsername('romanb');
$user3->save();
$this->assertEquals(3, $user3->getId());
$user3->setUsername('romanb_new');
$user3->save();
$user3test = User::find($user3->getId());
$this->assertEquals('romanb_new', $user3test->getUsername());
$test = User::findAll();
$this->assertEquals(3, count($test));
$this->assertTrue($user1 === $test[0]);
$this->assertTrue($user2 === $test[1]);
$this->assertTrue($user3 === $test[2]);
$user3->delete();
$test = User::findAll();
$this->assertEquals(2, count($test));
}
}
class TestFunctionalClient extends Client
{
public $name;
public $source;
public $data = array();
public $count = 0;
public function __construct($name, $source)
{
$this->name = $name;
$this->source = $source;
}
public function execServer($request, $requestArray, $parameters = array(), $responseType = 'xml')
{
$requestArray = array_merge($requestArray, (array) $parameters);
$server = new Server($this->source, $requestArray);
if ($this->source instanceof EntityManager) {
$server->setEntityAlias('Doctrine\Tests\REST\DoctrineUser', 'user');
}
$response = $server->getRequestHandler()->execute();
$data = $request->getResponseTransformerImpl()->transform($response->getContent());
return $data;
}
public function execute(Request $request)
{
$url = $request->getUrl();
$method = $request->getMethod();
$parameters = $request->getParameters();
$responseType = $request->getResponseType();
// GET api/user/1.xml (get)
if ($method === 'GET' && preg_match_all('/api\/' . $this->name . '\/([0-9]).xml/', $url, $matches)) {
$id = $matches[1][0];
return $this->execServer($request, array(
'_method' => $method,
'_format' => $responseType,
'_entity' => $this->name,
'_action' => 'get',
'_id' => $id
), $parameters, $responseType);
}
// GET api/user.xml (list)
if ($method === 'GET' && preg_match_all('/api\/' . $this->name . '.xml/', $url, $matches)) {
return $this->execServer($request, array(
'_method' => $method,
'_format' => $responseType,
'_entity' => $this->name,
'_action' => 'list'
), $parameters, $responseType);
}
// PUT api/user.xml (insert)
if ($method === 'PUT' && preg_match_all('/api\/' . $this->name . '.xml/', $url, $matches)) {
return $this->execServer($request, array(
'_method' => $method,
'_format' => $responseType,
'_entity' => $this->name,
'_action' => 'insert'
), $parameters, $responseType);
}
// POST api/user/1.xml (update)
if ($method === 'POST' && preg_match_all('/api\/' . $this->name . '\/([0-9]).xml/', $url, $matches)) {
return $this->execServer($request, array(
'_method' => $method,
'_format' => $responseType,
'_entity' => $this->name,
'_action' => 'update',
'_id' => $parameters['id']
), $parameters, $responseType);
}
// DELETE api/user/1.xml (delete)
if ($method === 'DELETE' && preg_match_all('/api\/' . $this->name . '\/([0-9]).xml/', $url, $matches)) {
return $this->execServer($request, array(
'_method' => $method,
'_format' => $responseType,
'_entity' => $this->name,
'_action' => 'delete',
'_id' => $matches[1][0]
), $parameters, $responseType);
}
}
}
class User extends Entity
{
protected $id;
protected $username;
public static function configure(EntityConfiguration $entityConfiguration)
{
$entityConfiguration->setUrl('api');
$entityConfiguration->setName('user');
}
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
}
/**
* @Entity
* @Table(name="user")
*/
class DoctrineUser
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string", length=255, unique=true)
*/
private $username;
public function setUsername($username)
{
$this->username = $username;
}
}
| php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/tests/Doctrine/Tests/REST/AllTests.php | tests/Doctrine/Tests/REST/AllTests.php | <?php
namespace Doctrine\Tests\REST;
if ( ! defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'AllTests::main');
}
require_once __DIR__ . '/TestInit.php';
class AllTests
{
public static function main()
{
\PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new \PHPUnit_Framework_TestSuite('Doctrine2REST Tests');
$suite->addTestSuite('Doctrine\Tests\REST\ClientTest');
$suite->addTestSuite('Doctrine\Tests\REST\FunctionalTest');
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
AllTests::main();
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/Client.php | lib/Doctrine/REST/Client/Client.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client;
/**
* Basic class for issuing HTTP requests via PHP curl.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Client
{
const POST = 'POST';
const GET = 'GET';
const PUT = 'PUT';
const DELETE = 'DELETE';
public function post(Request $request)
{
$request->setMethod(Client::POST);
return $this->execute($request);
}
public function get(Request $request)
{
$request->setMethod(Client::GET);
return $this->execute($request);
}
public function put(Request $request)
{
$request->setMethod(Client::PUT);
return $this->execute($request);
}
public function delete(Request $request)
{
$request->setMethod(Client::DELETE);
return $this->execute($request);
}
public function execute(Request $request)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request->getUrl());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
$username = $request->getUsername();
$password = $request->getPassword();
if ($username && $password) {
curl_setopt ($ch, CURLOPT_USERPWD, $username . ':' . $password);
}
switch ($request->getMethod()) {
case self::POST:
case self::PUT:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request->getParameters()));
break;
case self::DELETE:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case self::GET:
default:
break;
}
$result = curl_exec($ch);
if ( ! $result) {
$errorNumber = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
throw new \Exception($errorNumber . ': ' . $error);
}
curl_close($ch);
return $request->getResponseTransformerImpl()->transform($result);
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/Entity.php | lib/Doctrine/REST/Client/Entity.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client;
/**
* Abstract entity class for REST entities to extend from to give ActiveRecord
* style interface for working with REST services.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
abstract class Entity
{
protected static $_manager;
public static function setManager(Manager $manager)
{
self::$_manager = $manager;
}
public function toArray()
{
return get_object_vars($this);
}
public function exists()
{
return self::$_manager->entityExists($this);
}
public function getIdentifier()
{
return self::$_manager->getEntityIdentifier($this);
}
public static function generateUrl(array $options = array())
{
$configuration = self::$_manager->getEntityConfiguration(get_called_class());
return $configuration->generateUrl($options);
}
public static function find($id, $action = null)
{
return self::$_manager->execute(
get_called_class(),
self::generateUrl(get_defined_vars()),
Client::GET
);
}
public static function findAll($action = null, $parameters = null)
{
return self::$_manager->execute(
get_called_class(),
self::generateUrl(get_defined_vars()),
Client::GET, $parameters
);
}
public function save($action = null)
{
$parameters = $this->toArray();
$exists = $this->exists();
$method = $exists ? Client::POST : Client::PUT;
$id = $exists ? $this->getIdentifier() : null;
$path = $this->generateUrl(get_defined_vars());
return self::$_manager->execute($this, $path, $method, $parameters, $action);
}
public function delete($action = null)
{
$id = $this->getIdentifier();
return self::$_manager->execute(
$this, $this->generateUrl(get_defined_vars()), Client::DELETE
);
}
public function post($action = null)
{
$id = $this->getIdentifier();
return self::$_manager->execute(
$this, $this->generateUrl(get_defined_vars()),
Client::POST, $this->toArray()
);
}
public function get($action = null)
{
return self::$_manager->execute(
$this, $this->generateUrl(get_defined_vars()),
Client::GET, $this->toArray()
);
}
public function put($action = null)
{
return self::$_manager->execute(
$this, $this->generateUrl(get_defined_vars()),
Client::PUT, $this->toArray()
);
}
public static function execute($method, $action, $parameters = null)
{
return self::$_manager->execute(
get_called_class(),
self::generateUrl(get_defined_vars()),
$method, $parameters
);
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/EntityConfiguration.php | lib/Doctrine/REST/Client/EntityConfiguration.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client;
use Doctrine\REST\Client\URLGenerator\StandardURLGenerator,
Doctrine\REST\Client\ResponseTransformer\StandardResponseTransformer;
/**
* Entity configuration class holds all the configuration information for a PHP5
* object entity that maps to a REST service.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class EntityConfiguration
{
private $_prototype;
private $_reflection;
private $_reflectionProperties = array();
private $_attributes = array(
'class' => null,
'url' => null,
'name' => null,
'username' => null,
'password' => null,
'identifierKey' => 'id',
'responseType' => 'xml',
'urlGeneratorImpl' => null,
'responseTransformerImpl' => null,
);
public function __construct($class)
{
$this->_attributes['class'] = $class;
$this->_attributes['urlGeneratorImpl'] = new StandardURLGenerator($this);
$this->_attributes['responseTransformerImpl'] = new StandardResponseTransformer($this);
$this->_reflection = new \ReflectionClass($class);
foreach ($this->_reflection->getProperties() as $property) {
if ($property->getDeclaringClass()->getName() == $class) {
$property->setAccessible(true);
$this->_reflectionProperties[$property->getName()] = $property;
$this->_properties[] = $property->getName();
}
}
}
public function getReflection()
{
return $this->_reflection;
}
public function getReflectionProperties()
{
return $this->_reflectionProperties;
}
public function getProperties()
{
return $this->_properties;
}
public function setValue($entity, $field, $value)
{
if (isset($this->_reflectionProperties[$field])) {
$this->_reflectionProperties[$field]->setValue($entity, $value);
} else {
$entity->$field = $value;
}
}
public function getValue($entity, $field)
{
return $this->_reflectionProperties[$field]->getValue($entity);
}
public function generateUrl(array $options)
{
return $this->_attributes['urlGeneratorImpl']->generate($options);
}
public function setUrl($url)
{
$this->_attributes['url'] = rtrim($url, '/');
}
public function getUrl()
{
return $this->_attributes['url'];
}
public function setClass($class)
{
$this->_attributes['class'] = $class;
}
public function getClass()
{
return $this->_attributes['class'];
}
public function setName($name)
{
$this->_attributes['name'] = $name;
}
public function getName()
{
return $this->_attributes['name'];
}
public function setUsername($username)
{
$this->_attributes['username'] = $username;
}
public function getUsername()
{
return $this->_attributes['username'];
}
public function setPassword($password)
{
$this->_attributes['password'] = $password;
}
public function getPassword()
{
return $this->_attributes['password'];
}
public function setIdentifierKey($identifierKey)
{
$this->_attributes['identifierKey'] = $identifierKey;
}
public function getIdentifierKey()
{
return $this->_attributes['identifierKey'];
}
public function setResponseType($responseType)
{
$this->_attributes['responseType'] = $responseType;
}
public function getResponseType()
{
return $this->_attributes['responseType'];
}
public function setURLGeneratorImpl($urlGeneratorImpl)
{
$this->_attributes['urlGeneratorImpl'] = $urlGeneratorImpl;
}
public function getURLGeneratorImpl()
{
return $this->_attributes['urlGeneratorImpl'];
}
public function setResponseTransformerImpl($responseHandlerImpl)
{
$this->_attributes['responseTransformerImpl'] = $responseHandlerImpl;
}
public function getResponseTransformerImpl()
{
return $this->_attributes['responseTransformerImpl'];
}
public function newInstance()
{
if ($this->_prototype === null) {
$this->_prototype = unserialize(sprintf(
'O:%d:"%s":0:{}',
strlen($this->_attributes['class']),
$this->_attributes['class']
));
}
return clone $this->_prototype;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/Request.php | lib/Doctrine/REST/Client/Request.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client;
/**
* Class that represents a request to a REST service through the raw HTTP client.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Request
{
private $_url;
private $_method = Client::GET;
private $_parameters = array();
private $_username;
private $_password;
private $_responseType = 'xml';
private $_responseTransformerImpl;
public function setUrl($url)
{
$this->_url = $url;
}
public function getUrl()
{
return $this->_url;
}
public function setMethod($method)
{
$this->_method = $method;
}
public function getMethod()
{
return $this->_method;
}
public function setParameters($parameters)
{
$this->_parameters = $parameters;
}
public function getParameters()
{
return $this->_parameters;
}
public function setResponseType($responseType)
{
$this->_responseType = $responseType;
}
public function getResponseType()
{
return $this->_responseType;
}
public function setUsername($username)
{
$this->_username = $username;
}
public function getUsername()
{
return $this->_username;
}
public function setPassword($password)
{
$this->_password = $password;
}
public function getPassword()
{
return $this->_password;
}
public function setResponseTransformerImpl($responseTransformerImpl)
{
$this->_responseTransformerImpl = $responseTransformerImpl;
}
public function getResponseTransformerImpl()
{
return $this->_responseTransformerImpl;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/Manager.php | lib/Doctrine/REST/Client/Manager.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client;
/**
* Class responsible for managing the entities registered for REST services.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Manager
{
private $_client;
private $_entityConfigurations = array();
private $_identityMap = array();
public function __construct(Client $client)
{
$this->_client = $client;
}
public function registerEntity($entity)
{
$this->_entityConfigurations[$entity] = $entity;
}
public function getEntityConfiguration($entity)
{
if ( ! isset($this->_entityConfigurations[$entity])) {
throw new \InvalidArgumentException(
sprintf('Could not find entity configuration for "%s"', $entity)
);
}
if (is_string($this->_entityConfigurations[$entity])) {
$entityConfiguration = new EntityConfiguration($entity);
call_user_func_array(
array($entity, 'configure'),
array($entityConfiguration)
);
$this->_entityConfigurations[$entity] = $entityConfiguration;
}
return $this->_entityConfigurations[$entity];
}
public function entityExists($entity)
{
return $this->getEntityIdentifier($entity) ? true : false;
}
public function getEntityIdentifier($entity)
{
$configuration = $this->getEntityConfiguration(get_class($entity));
$identifierKey = $configuration->getIdentifierKey();
return $configuration->getValue($entity, $identifierKey);
}
public function execute($entity, $url = null, $method = Client::GET, $parameters = null)
{
if (is_object($entity)) {
$className = get_class($entity);
} else {
$className = $entity;
}
$configuration = $this->getEntityConfiguration($className);
$request = new Request();
$request->setUrl($url);
$request->setMethod($method);
$request->setParameters($parameters);
$request->setUsername($configuration->getUsername());
$request->setPassword($configuration->getPassword());
$request->setResponseType($configuration->getResponseType());
$request->setResponseTransformerImpl($configuration->getResponseTransformerImpl());
$result = $this->_client->execute($request);
if (is_array($result))
{
$name = $configuration->getName();
$identifierKey = $configuration->getIdentifierKey();
$className = $configuration->getClass();
if (isset($result[$name]) && is_array($result[$name]))
{
$collection = array();
foreach ($result[$name] as $data) {
$identifier = $data[$identifierKey];
if (isset($this->_identityMap[$className][$identifier]))
{
$instance = $this->_identityMap[$className][$identifier];
} else {
$instance = $configuration->newInstance();
$this->_identityMap[$className][$identifier] = $instance;
}
$collection[] = $this->_hydrate(
$configuration, $instance, $data
);
}
return $collection;
} else if ($result) {
if (is_object($entity))
{
$instance = $entity;
$this->_hydrate($configuration, $instance, $result);
$identifier = $this->getEntityIdentifier($instance);
$this->_identityMap[$className][$identifier] = $instance;
} else {
$identifier = $result[$identifierKey];
if (isset($this->_identityMap[$className][$identifier]))
{
$instance = $this->_identityMap[$className][$identifier];
} else {
$instance = $configuration->newInstance();
$this->_identityMap[$className][$identifier] = $instance;
}
$this->_hydrate($configuration, $instance, $result);
}
return $instance;
}
} else {
return array();
}
}
private function _hydrate($configuration, $instance, $data)
{
foreach ($data as $key => $value) {
if (is_array($value))
{
$configuration->setValue($instance, $key, (string) $value);
} else {
$configuration->setValue($instance, $key, $value);
}
}
return $instance;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/ResponseTransformer/StandardResponseTransformer.php | lib/Doctrine/REST/Client/ResponseTransformer/StandardResponseTransformer.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client\ResponseTransformer;
/**
* Standard REST request response handler. Converts a standard REST service response
* to an array for easy manipulation. Works for both xml and json response types.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class StandardResponseTransformer extends AbstractResponseTransformer
{
public function transform($data)
{
switch ($this->_entityConfiguration->getResponseType()) {
case 'xml':
return $this->xmlToArray($data);
case 'json':
return $this->jsonToArray($data);
break;
}
}
public function xmlToArray($object, &$array = array())
{
if (is_string($object)) {
$object = new \SimpleXMLElement($object);
}
$children = $object->children();
$executed = false;
foreach ($children as $elementName => $node) {
if (isset($array[$elementName]) && $array[$elementName] !== null) {
if (isset($array[$elementName][0]) && $array[$elementName][0] !== null) {
$i = count($array[$elementName]);
$this->xmlToArray($node, $array[$elementName][$i]);
} else {
$tmp = $array[$elementName];
$array[$elementName] = array();
$array[$elementName][0] = $tmp;
$i = count($array[$elementName]);
$this->xmlToArray($node, $array[$elementName][$i]);
}
} else {
$array[$elementName] = array();
$this->xmlToArray($node, $array[$elementName]);
}
$executed = true;
}
if ( ! $executed && ! $children->getName()) {
$array = (string) $object;
}
return $array;
}
public function jsonToArray($json)
{
return (array) json_decode($json);
}
}
| php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/ResponseTransformer/AbstractResponseTransformer.php | lib/Doctrine/REST/Client/ResponseTransformer/AbstractResponseTransformer.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client\ResponseTransformer;
use Doctrine\REST\Client\EntityConfiguration;
/**
* Abstract REST request response transformer
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
abstract class AbstractResponseTransformer
{
protected $_entityConfiguration;
public function __construct(EntityConfiguration $entityConfiguration)
{
$this->_entityConfiguration = $entityConfiguration;
}
abstract public function transform($data);
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/URLGenerator/ApontadorURLGenerator.php | lib/Doctrine/REST/Client/URLGenerator/ApontadorURLGenerator.php | <?php
namespace Doctrine\REST\Client\URLGenerator;
/**
* Apontador REST request URL generator
*
* @author Alexandre Eher <alexandre@eher.com.br>
*/
class ApontadorURLGenerator extends AbstractURLGenerator
{
public function generate(array $options)
{
$id = isset($options['id']) ? $options['id'] : null;
$action = isset($options['action']) ? $options['action'] : null;
$parameters = isset($options['parameters']) ? $options['parameters'] : array();
$parameters['type'] = $this->_entityConfiguration->getResponseType();
if ($id)
{
if ($action !== null)
{
$path = sprintf('/%s/%s', $id, $action);
} else {
$path = sprintf('/%s', $id);
}
} else {
if ($action !== null)
{
$path = sprintf('/%s', $action);
} else {
$path = '';
}
}
$url = $this->_entityConfiguration->getUrl() . '/' . $this->_entityConfiguration->getName() . $path;
if (is_array($parameters) && $parameters) {
foreach ($this->_entityConfiguration->getProperties() as $field) {
unset($parameters[$field]);
}
if ($parameters) {
$url .= '?' . http_build_query($parameters);
}
}
return $url;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/URLGenerator/AbstractURLGenerator.php | lib/Doctrine/REST/Client/URLGenerator/AbstractURLGenerator.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client\URLGenerator;
use Doctrine\REST\Client\EntityConfiguration;
/**
* Abstract URL generator for REST services
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
abstract class AbstractURLGenerator
{
protected $_entityConfiguration;
public function __construct(EntityConfiguration $entityConfiguration)
{
$this->_entityConfiguration = $entityConfiguration;
}
abstract public function generate(array $options);
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Client/URLGenerator/StandardURLGenerator.php | lib/Doctrine/REST/Client/URLGenerator/StandardURLGenerator.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Client\URLGenerator;
/**
* Standard REST request URL generator
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class StandardURLGenerator extends AbstractURLGenerator
{
public function generate(array $options)
{
$id = isset($options['id']) ? $options['id'] : null;
$action = isset($options['action']) ? $options['action'] : null;
$parameters = isset($options['parameters']) ? $options['parameters'] : array();
if ($id)
{
if ($action !== null)
{
$path = sprintf('/%s/%s.' . $this->_entityConfiguration->getResponseType(), $id, $action);
} else {
$path = sprintf('/%s.' . $this->_entityConfiguration->getResponseType(), $id);
}
} else {
if ($action !== null)
{
$path = sprintf('/%s.' . $this->_entityConfiguration->getResponseType(), $action);
} else {
$path = '.' . $this->_entityConfiguration->getResponseType();
}
}
$url = $this->_entityConfiguration->getUrl() . '/' . $this->_entityConfiguration->getName() . $path;
if (is_array($parameters) && $parameters) {
foreach ($this->_entityConfiguration->getProperties() as $field) {
unset($parameters[$field]);
}
if ($parameters) {
$url .= '?' . http_build_query($parameters);
}
}
return $url;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Request.php | lib/Doctrine/REST/Server/Request.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server;
/**
* Class that represents a REST server request.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Request implements \ArrayAccess
{
private $_data;
public function __construct(array $request)
{
$this->_data = $request;
$this->_data['_format'] = isset($this->_data['_format']) ? $this->_data['_format'] : 'json';
}
public function getData()
{
return $this->_data;
}
public function offsetSet($key, $value)
{
$this->_data[$key] = $value;
}
public function offsetGet($key)
{
return isset($this->_data[$key]) ? $this->_data[$key] : null;
}
public function offsetUnset($key)
{
unset($this->_data[$key]);
}
public function offsetExists($key)
{
return isset($this->_data[$key]);
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/RequestHandler.php | lib/Doctrine/REST/Server/RequestHandler.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server;
use Doctrine\ORM\EntityManager,
Doctrine\DBAL\Connection;
/**
* Class responsible for transforming a REST server request to a response.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class RequestHandler
{
private $_source;
private $_request;
private $_response;
private $_username;
private $_password;
private $_credentialsCallback;
private $_entities = array();
private $_actions = array(
'delete' => 'Doctrine\\REST\\Server\\Action\\DeleteAction',
'get' => 'Doctrine\\REST\\Server\\Action\\GetAction',
'insert' => 'Doctrine\\REST\\Server\\Action\\InsertAction',
'update' => 'Doctrine\\REST\\Server\\Action\\UpdateAction',
'list' => 'Doctrine\\REST\\Server\\Action\\ListAction'
);
public function __construct($source, Request $request, Response $response)
{
$this->_source = $source;
$this->_request = $request;
$this->_response = $response;
$this->_response->setRequestHandler($this);
$this->_credentialsCallback = array($this, 'checkCredentials');
}
public function configureEntity($entity, $configuration)
{
$this->_entities[$entity] = $configuration;
}
public function setEntityAlias($entity, $alias)
{
$this->_entities[$entity]['alias'] = $alias;
}
public function addEntityAction($entity, $action, $className)
{
$this->_entities[$entity]['actions'][$action] = $className;
}
public function setEntityIdentifierKey($entity, $identifierKey)
{
$this->_entities[$entity]['identifierKey'] = $identifierKey;
}
public function getEntityIdentifierKey($entity)
{
return isset($this->_entities[$entity]['identifierKey']) ? $this->_entities[$entity]['identifierKey'] : 'id';
}
public function resolveEntityAlias($alias)
{
foreach ($this->_entities as $entity => $configuration) {
if (isset($configuration['alias']) && $configuration['alias'] === $alias) {
return $entity;
}
}
return $alias;
}
public function setCredentialsCallback($callback)
{
$this->_credentialsCallback = $callback;
}
public function registerAction($action, $className)
{
$this->_actions[$action] = $className;
}
public function isSecure()
{
return ($this->_username && $this->_password) ? true : false;
}
public function checkCredentials($username, $password)
{
if ( ! $this->isSecure()) {
return true;
}
if ($this->_username == $username && $this->_password == $password) {
return true;
} else {
return false;
}
}
public function hasValidCredentials()
{
$args = array($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
return call_user_func_array($this->_credentialsCallback, $args);
}
public function getUsername()
{
return $this->_username;
}
public function setUsername($username)
{
$this->_username = $username;
}
public function getPassword()
{
return $this->_password;
}
public function setPassword($password)
{
$this->_password = $password;
}
public function getActions()
{
return $this->_actions;
}
public function getSource()
{
return $this->_source;
}
public function getRequest()
{
return $this->_request;
}
public function getResponse()
{
return $this->_response;
}
public function getEntity()
{
return $this->resolveEntityAlias($this->_request['_entity']);
}
public function execute()
{
try {
$entity = $this->getEntity();
$actionInstance = $this->getAction($entity, $this->_request['_action']);
if (method_exists($actionInstance, 'execute')) {
$result = $actionInstance->execute();
} else {
if ($this->_source instanceof EntityManager) {
$result = $actionInstance->executeORM();
} else {
$result = $actionInstance->executeDBAL();
}
}
$this->_response->setResponseData(
$this->_transformResultForResponse($result)
);
} catch (\Exception $e) {
$this->_response->setError($this->_getExceptionErrorMessage($e));
}
return $this->_response;
}
public function getAction($entity, $actionName)
{
if (isset($this->_actions[$actionName])) {
if ( ! is_object($this->_actions[$actionName])) {
$actionClassName = $this->_actions[$actionName];
$this->_actions[$actionName] = new $actionClassName($this);
}
return $this->_actions[$actionName];
}
if (isset($this->_entities[$entity]['actions'][$actionName])) {
if ( ! is_object($this->_entities[$entity]['actions'][$actionName])) {
$actionClassName = $this->_entities[$entity]['actions'][$actionName];
$this->_entities[$entity]['actions'][$actionName] = new $actionClassName($this);
}
return $this->_entities[$entity]['actions'][$actionName];
}
}
private function _getExceptionErrorMessage(\Exception $e)
{
$message = $e->getMessage();
if ($e instanceof \PDOException) {
$message = preg_replace("/SQLSTATE\[.*\]: (.*)/", "$1", $message);
}
return $message;
}
private function _transformResultForResponse($result, $array = null)
{
if ( ! $array) {
$array = array();
}
if (is_object($result)) {
$entityName = get_class($result);
if ($this->_source instanceof EntityManager) {
$class = $this->_source->getMetadataFactory()->getMetadataFor($entityName);
foreach ($class->fieldMappings as $fieldMapping) {
$array[$fieldMapping['fieldName']] = $class->getReflectionProperty($fieldMapping['fieldName'])->getValue($result);
}
} else {
$vars = get_object_vars($result);
foreach ($vars as $key => $value) {
$array[$key] = $value;
}
}
} else if (is_array($result)) {
foreach ($result as $key => $value) {
if (is_object($value) || is_array($value)) {
if (is_object($value)) {
$key = $this->_request['_entity'] . $key;
}
$array[$key] = $this->_transformResultForResponse($value, isset($array[$key]) ? $array[$key] : array());
} else {
$array[$key] = $value;
}
}
} else if (is_string($result)) {
$array = $result;
}
return $array;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Response.php | lib/Doctrine/REST/Server/Response.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server;
/**
* Class that represents a REST server response.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Response
{
private $_requestHandler;
private $_request;
private $_responseData;
public function __construct(Request $request)
{
$this->_request = $request;
}
public function setRequestHandler(RequestHandler $requestHandler)
{
$this->_requestHandler = $requestHandler;
}
public function setError($error)
{
$this->_responseData = array();
$this->_responseData['error'] = $error;
}
public function setResponseData($responseData)
{
$this->_responseData = $responseData;
}
public function send()
{
$this->_sendHeaders();
echo $this->getContent();
}
public function getContent()
{
$data = $this->_responseData;
switch ($this->_request['_format']) {
case 'php':
return serialize($data);
break;
case 'json':
return json_encode($data);
break;
case 'xml':
default:
return $this->_arrayToXml($data, $this->_request['_entity']);
}
}
private function _sendHeaders()
{
if ($this->_requestHandler->getUsername()) {
if ( ! isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="Doctrine REST API"');
header('HTTP/1.0 401 Unauthorized');
} else {
if ( ! $this->_requestHandler->hasValidCredentials()) {
$this->setError('Invalid credentials specified.');
}
}
}
switch ($this->_request['_format']) {
case 'php':
header('Content-type: text/html;');
break;
case 'json':
header('Content-type: text/json;');
header('Content-Disposition: attachment; filename="' . $this->_request['_action'] . '.json"');
break;
case 'xml':
default:
header('Content-type: application/xml;');
}
}
private function _arrayToXml($array, $rootNodeName = 'doctrine', $xml = null, $charset = null)
{
if ($xml === null) {
$xml = new \SimpleXmlElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><$rootNodeName/>");
}
foreach($array as $key => $value) {
if (is_numeric($key)) {
$key = $rootNodeName . $key;
}
$key = preg_replace('/[^A-Za-z_]/i', '', $key);
if (is_array($value) && ! empty($value)) {
$node = $xml->addChild($key);
$this->_arrayToXml($value, $rootNodeName, $node, $charset);
} else if ($value) {
$charset = $charset ? $charset : 'utf-8';
if (strcasecmp($charset, 'utf-8') !== 0 && strcasecmp($charset, 'utf8') !== 0) {
$value = iconv($charset, 'UTF-8', $value);
}
$value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
$xml->addChild($key, $value);
}
}
return $this->_formatXml($xml);
}
private function _formatXml($simpleXml)
{
$xml = $simpleXml->asXml();
// add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
$xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml);
// now indent the tags
$token = strtok($xml, "\n");
$result = ''; // holds formatted version as it is built
$pad = 0; // initial indent
$matches = array(); // returns from preg_matches()
// test for the various tag states
while ($token !== false) {
// 1. open and closing tags on same line - no change
if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) {
$indent = 0;
// 2. closing tag - outdent now
} else if (preg_match('/^<\/\w/', $token, $matches)) {
$pad = $pad - 4;
// 3. opening tag - don't pad this one, only subsequent tags
} elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) {
$indent = 4;
// 4. no indentation needed
} else {
$indent = 0;
}
// pad the line with the required number of leading spaces
$line = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);
$result .= $line . "\n"; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
}
return $result;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Server.php | lib/Doctrine/REST/Server/Server.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server;
use Doctrine\ORM\EntityManager,
Doctrine\ORM\Connection;
/**
* Simple REST server facade.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Server
{
private $_requestHandler;
private $_request;
private $_response;
public function __construct($source, array $requestData = array())
{
$this->_request = new Request($requestData);
$this->_response = new Response($this->_request);
$this->_requestHandler = new RequestHandler($source, $this->_request, $this->_response);
}
public function execute()
{
$this->_requestHandler->execute();
return $this->_requestHandler->getResponse()->getContent();
}
public function setEntityIdentifierKey($entity, $identifierKey)
{
$this->_requestHandler->setEntityIdentifierKey($entity, $identifierKey);
}
public function setEntityAlias($entity, $alias)
{
$this->_requestHandler->setEntityAlias($entity, $alias);
}
public function registerAction($action, $className)
{
$this->_requestHandler->registerAction($action, $className);
}
public function addEntityAction($entity, $action, $className)
{
$this->_requestHandler->addEntityAction($entity, $action, $className);
}
public function setUsername($username)
{
$this->_requestHandler->setUsername($username);
}
public function setPassword($password)
{
$this->_requestHandler->setPassword($password);
}
public function getResponse()
{
return $this->_response;
}
public function getRequest()
{
return $this->_request;
}
public function getRequestHandler()
{
return $this->_requestHandler;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/PHPRequestParser.php | lib/Doctrine/REST/Server/PHPRequestParser.php | <?php
namespace Doctrine\REST\Server;
class PHPRequestParser
{
public function getRequestArray()
{
$path = $_SERVER['PATH_INFO'];
$path = ltrim($path, '/');
$e = explode('/', $path);
$count = count($e);
$end = end($e);
$e2 = explode('.', $end);
$e[count($e) - 1] = $e2[0];
$format = isset($e2[1]) ? $e2[1] : 'xml';
$entity = $e[0];
$id = isset($e[1]) ? $e[1] : null;
$action = isset($e[2]) ? $e[2] : null;
$method = isset($_REQUEST['_method']) ? $_REQUEST['_method'] : $_SERVER['REQUEST_METHOD'];
$method = strtoupper($method);
if ($count === 1) {
if ($method === 'POST' || $method === 'PUT') {
$action = 'insert';
} else if ($method === 'GET') {
$action = 'list';
}
} else if ($count === 2) {
if ($method === 'POST' || $method === 'PUT') {
$action = 'update';
} else if ($method === 'GET') {
$action = 'get';
} else if ($method === 'DELETE') {
$action = 'delete';
}
} else if ($count === 3) {
$action = $action;
}
$data = array_merge(array(
'_entity' => $entity,
'_id' => $id,
'_action' => $action,
'_format' => $format
), $_REQUEST);
return $data;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/AbstractAction.php | lib/Doctrine/REST/Server/Action/AbstractAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
use Doctrine\REST\Server\RequestHandler,
Doctrine\ORM\EntityManager;
/**
* Abstract server action class for REST server actions to extend from.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
abstract class AbstractAction
{
protected $_requestHandler;
protected $_source;
protected $_request;
public function __construct(RequestHandler $requestHandler)
{
$this->_requestHandler = $requestHandler;
$this->_source = $requestHandler->getSource();
$this->_request = $requestHandler->getRequest();
}
public function executeORM()
{
}
public function executeDBAL()
{
}
protected function _getEntity()
{
return $this->_requestHandler->getEntity();
}
protected function _getEntityIdentifierKey()
{
return $this->_requestHandler->getEntityIdentifierKey($this->_getEntity());
}
protected function _setQueryFirstAndMax($q)
{
if ( ! isset($this->_request['_page']) && ! isset($this->_request['_first']) && ! isset($this->_request['_max'])) {
$this->_request['_page'] = '1';
}
$maxPerPage = isset($this->_request['_max_per_page']) ? $this->_request['_max_per_page'] : 20;
if (isset($this->_request['_page'])) {
$page = $this->_request['_page'];
$first = ($page - 1) * $maxPerPage;
} else {
if (isset($this->_request['_first'])) {
$first = $this->_request['_first'];
} else {
$first = 0;
}
if (isset($this->_request['_max'])) {
$maxPerPage = $this->_request['_max'];
}
}
if ($this->_source instanceof EntityManager) {
$q->setFirstResult($first);
$q->setMaxResults($maxPerPage);
} else {
$platform = $this->_source->getDatabasePlatform();
return $platform->modifyLimitQuery($q, $maxPerPage, $first);
}
}
protected function _findEntityById()
{
if ($this->_source instanceof EntityManager) {
$entity = $this->_getEntity();
$id = $this->_request['_id'];
$qb = $this->_source->createQueryBuilder()
->select('a')
->from($entity, 'a')
->where('a.id = ?1')
->setParameter('1', $id);
$query = $qb->getQuery();
return $query->getSingleResult();
} else {
$entity = $this->_getEntity();
$identifierKey = $this->_getEntityIdentifierKey($entity);
$query = sprintf('SELECT * FROM %s WHERE %s = ?', $entity, $identifierKey);
return $this->_source->fetchAssoc($query, array($this->_request['_id']));
}
}
protected function _updateEntityInstance($entity)
{
$data = $this->_gatherData($this->_request->getData());
foreach ($data as $key => $value) {
$setter = 'set' . ucfirst($key);
if (is_callable(array($entity, $setter))) {
$entity->$setter($value);
}
}
return $entity;
}
protected function _gatherData()
{
$data = array();
foreach ($this->_request->getData() as $key => $value) {
if ($key[0] == '_') {
continue;
}
$data[$key] = $value;
}
return $data;
}
}
| php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/GetAction.php | lib/Doctrine/REST/Server/Action/GetAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
/**
* REST server get action.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class GetAction extends AbstractAction
{
public function execute()
{
$entity = $this->_findEntityById();
if ( ! $entity) {
throw new \InvalidArgumentException(sprintf('Could not find the "%s" with an id of "%s"', $this->_request['_entity'], implode(', ', (array) $this->_request['_id'])));
}
return $entity;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/UpdateAction.php | lib/Doctrine/REST/Server/Action/UpdateAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
/**
* REST server update action.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class UpdateAction extends AbstractAction
{
public function executeORM()
{
if ($entity = $this->_findEntityById()) {
$this->_updateEntityInstance($entity);
$this->_source->flush();
}
return $entity;
}
public function executeDBAL()
{
$entity = $this->_getEntity();
$identifierKey = $this->_getEntityIdentifierKey($entity);
$data = $this->_gatherData();
$this->_source->update($entity, $data, array(
$identifierKey => $this->_request['_id']
));
return $this->_findEntityById();
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/ListAction.php | lib/Doctrine/REST/Server/Action/ListAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
/**
* REST server list action.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class ListAction extends AbstractAction
{
public function executeORM()
{
$entity = $this->_getEntity();
$qb = $this->_source->createQueryBuilder()
->select('a')
->from($entity, 'a');
$data = $this->_gatherData();
foreach ($data as $key => $value) {
$qb->andWhere("a.$key = :$key");
$qb->setParameter($key, $value);
}
$query = $qb->getQuery();
$this->_setQueryFirstAndMax($query);
$results = $query->execute();
return $results;
}
public function executeDBAL()
{
$entity = $this->_getEntity();
$params = array();
$query = sprintf('SELECT * FROM %s', $entity);
if ($data = $this->_gatherData()) {
$query .= ' WHERE ';
foreach ($data as $key => $value) {
$query .= $key . ' = ? AND ';
$params[] = $value;
}
$query = substr($query, 0, strlen($query) - 5);
}
$query = $this->_setQueryFirstAndMax($query);
$results = $this->_source->fetchAll($query, $params);
return $results;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/InsertAction.php | lib/Doctrine/REST/Server/Action/InsertAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
/**
* REST server insert action.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class InsertAction extends AbstractAction
{
public function executeORM()
{
$entity = $this->_getEntity();
$instance = new $entity();
$this->_updateEntityInstance($instance);
$this->_source->persist($instance);
$this->_source->flush();
return $instance;
}
public function executeDBAL()
{
$entity = $this->_getEntity();
$identifierKey = $this->_getEntityIdentifierKey();
$data = $this->_gatherData();
unset($data['id']);
$this->_source->insert($entity, $data);
$data = array_merge(
array($identifierKey => $this->_source->lastInsertId()),
$data
);
return $data;
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
doctrine/rest | https://github.com/doctrine/rest/blob/a0e2e42bdce3834e01d102784e5b399929d0c1fc/lib/Doctrine/REST/Server/Action/DeleteAction.php | lib/Doctrine/REST/Server/Action/DeleteAction.php | <?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\REST\Server\Action;
/**
* REST server delete action.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @version $Revision$
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class DeleteAction extends AbstractAction
{
public function executeORM()
{
if ($entity = $this->_findEntityById()) {
$this->_source->remove($entity);
$this->_source->flush();
return $entity;
}
}
public function executeDBAL()
{
if ($entity = $this->_findEntityById()) {
$this->_source->delete($this->_getEntity(), array(
$this->_getEntityIdentifierKey() => $this->_request['_id']
));
return $entity;
}
}
} | php | MIT | a0e2e42bdce3834e01d102784e5b399929d0c1fc | 2026-01-05T04:40:12.562751Z | false |
staabm/side-effects-detector | https://github.com/staabm/side-effects-detector/blob/5ac07cdea5aad2a8fbc2ecc29fda11981d365112/tests/SideEffectsDetectorTest.php | tests/SideEffectsDetectorTest.php | <?php
namespace staabm\SideEffectsDetector\Tests;
use PHPUnit\Framework\TestCase;
use staabm\SideEffectsDetector\SideEffect;
use staabm\SideEffectsDetector\SideEffectsDetector;
class SideEffectsDetectorTest extends TestCase {
/**
* @dataProvider dataHasSideEffects
*/
public function testHasSideEffects(string $code, array $expected): void {
$detector = new SideEffectsDetector();
self::assertSame($expected, $detector->getSideEffects($code));
}
static public function dataHasSideEffects():iterable
{
yield ['<?php function abc() {}', [SideEffect::SCOPE_POLLUTION]];
if (PHP_VERSION_ID < 80000) {
// PHP7.x misses accurate reflection information
yield ['<?php gc_enable();', [SideEffect::MAYBE]];
yield ['<?php gc_enabled();', []];
yield ['<?php gc_disable();', [SideEffect::MAYBE]];
yield ["<?php if (file_exists(__DIR__. '/sess_' .session_id())) unlink(__DIR__. '/sess_' .session_id());", [SideEffect::MAYBE, SideEffect::INPUT_OUTPUT]];
} else {
yield ['<?php gc_enable();', [SideEffect::UNKNOWN_CLASS]];
yield ['<?php gc_enabled();', []];
yield ['<?php gc_disable();', [SideEffect::UNKNOWN_CLASS]];
yield ["<?php if (file_exists(__DIR__. '/sess_' .session_id())) unlink(__DIR__. '/sess_' .session_id());", [SideEffect::INPUT_OUTPUT]];
}
yield ['<?php $_GET["A"] = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $_POST["A"] = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $_COOKIE["A"] = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $_REQUEST["A"] = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $this->x = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php MyClass::$x = 1;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $this->doFoo();', [SideEffect::MAYBE]];
yield ['<?php MyClass::doFooBar();', [SideEffect::MAYBE]];
yield ['<?php putenv("MY_X=1");', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $x = getenv("MY_X");', []];
yield ['<?php ini_set("memory_limit", "1024M");', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php $x = ini_get("memory_limit");', []];
yield ['<?php echo "Hello World";', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php print("Hello World");', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php printf("Hello %s", "World");', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php vprintf("Hello %s", ["World"]);', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php trigger_error("error $i");', [SideEffect::UNKNOWN_CLASS]];
yield ['<?php fopen("file.txt");', [SideEffect::INPUT_OUTPUT]];
yield ['<?php version_compare(PHP_VERSION, "8.0", ">=") or die("skip because attributes are only available since PHP 8.0");', [SideEffect::PROCESS_EXIT]];
yield ['<?php version_compare(PHP_VERSION, "8.0", ">=") or echo("skip because attributes are only available since PHP 8.0");', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php die(0);', [SideEffect::PROCESS_EXIT]];
yield ['<?php exit(0);', [SideEffect::PROCESS_EXIT]];
yield ['<?php eval($x);', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php global $x; $x = [];', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php goto somewhere;', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php include "some-file.php";', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php include_once "some-file.php";', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php require "some-file.php";', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php require_once "some-file.php";', [SideEffect::SCOPE_POLLUTION]];
// constructor might have side-effects
yield ['<?php throw new RuntimeException("foo");', [SideEffect::SCOPE_POLLUTION, SideEffect::MAYBE]];
yield ['<?php unknownFunction($x);', [SideEffect::MAYBE]];
yield ['<?php echo unknownFunction($x);', [SideEffect::STANDARD_OUTPUT, SideEffect::MAYBE]];
yield ['<?php unset($x);', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php (unset)$x;', [SideEffect::SCOPE_POLLUTION]];
// constructor might have side-effects
yield ['<?php new SomeClass();', [SideEffect::SCOPE_POLLUTION, SideEffect::MAYBE]];
yield ['<?php function abc() {}', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php class abc {}', [SideEffect::SCOPE_POLLUTION]];
yield ['<?php (function (){})();', []];
yield ['<?php (function(){})();', []];
yield ['<?php (function(){echo "hi";})();', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php (function (){echo "hi";})();', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php if (getenv("SKIP_SLOW_TESTS")) echo("skip slow test");', [SideEffect::STANDARD_OUTPUT]];
yield ["<?php if (setlocale(LC_ALL, 'invalid') === 'invalid') { echo 'skip setlocale() is broken /w musl'; }", [SideEffect::SCOPE_POLLUTION, SideEffect::STANDARD_OUTPUT]];
yield ["<?php if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { echo 'skip this test on windows'; }", [SideEffect::STANDARD_OUTPUT]];
yield ['<?php if (PHP_INT_SIZE != 8) echo "skip this test is for 64bit platform only";', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php if (PHP_OS_FAMILY !== "Windows") echo "skip for Windows only";', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php if (PHP_ZTS) echo "skip hard_timeout works only on no-zts builds";', [SideEffect::STANDARD_OUTPUT]];
yield ['<?php if (getenv("SKIP_SLOW_TESTS")) echo "skip slow test"; if (PHP_OS_FAMILY !== "Windows") echo "skip Windows only test";', [SideEffect::STANDARD_OUTPUT]];
yield ["<?php if (class_exists('autoload_root', false)) echo 'skip Autoload test classes exist already';", [SideEffect::SCOPE_POLLUTION, SideEffect::STANDARD_OUTPUT]];
yield ["<?php if (strtolower(php_uname('s')) == 'darwin') { print 'skip ok to fail on MacOS X';}", [SideEffect::STANDARD_OUTPUT]];
yield ["<?php if declare(strict_types=1); if (1 == 2) { exit(1); }", [SideEffect::PROCESS_EXIT]];
yield ['<?php include "some-file.php"; echo "hello world"; exit(1);',
[SideEffect::SCOPE_POLLUTION, SideEffect::STANDARD_OUTPUT, SideEffect::PROCESS_EXIT],
];
}
} | php | MIT | 5ac07cdea5aad2a8fbc2ecc29fda11981d365112 | 2026-01-05T04:40:26.384644Z | false |
staabm/side-effects-detector | https://github.com/staabm/side-effects-detector/blob/5ac07cdea5aad2a8fbc2ecc29fda11981d365112/tests/bootstrap.php | tests/bootstrap.php | <?php
require_once __DIR__ . '/../vendor/autoload.php';
| php | MIT | 5ac07cdea5aad2a8fbc2ecc29fda11981d365112 | 2026-01-05T04:40:26.384644Z | false |
staabm/side-effects-detector | https://github.com/staabm/side-effects-detector/blob/5ac07cdea5aad2a8fbc2ecc29fda11981d365112/lib/functionMetadata.php | lib/functionMetadata.php | <?php declare(strict_types = 1);
/**
* Intially copied from PHPStan, but modified with some additional info about often used functions/methods, which PHPStan gets information about from other sources.
*
* https://github.com/phpstan/phpstan-src/blob/2.0.x/resources/functionMap.php
*/
return [
// added data
'ini_set' => ['hasSideEffects' => true],
'trigger_error' => ['hasSideEffects' => true],
'putenv' => ['hasSideEffects' => true],
'version_compare' => ['hasSideEffects' => false],
// Intially copied from PHPStan
'BackedEnum::from' => ['hasSideEffects' => false],
'BackedEnum::tryFrom' => ['hasSideEffects' => false],
'CURLFile::getFilename' => ['hasSideEffects' => false],
'CURLFile::getMimeType' => ['hasSideEffects' => false],
'CURLFile::getPostFilename' => ['hasSideEffects' => false],
'Cassandra\\Exception\\AlreadyExistsException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\AuthenticationException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ConfigurationException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\DivideByZeroException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\DomainException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ExecutionException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\InvalidArgumentException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\InvalidQueryException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\InvalidSyntaxException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\IsBootstrappingException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\LogicException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\OverloadedException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ProtocolException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\RangeException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ReadTimeoutException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\RuntimeException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ServerException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\TimeoutException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\TruncateException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\UnauthorizedException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\UnavailableException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\UnpreparedException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\ValidationException::__construct' => ['hasSideEffects' => false],
'Cassandra\\Exception\\WriteTimeoutException::__construct' => ['hasSideEffects' => false],
'Closure::bind' => ['hasSideEffects' => false],
'Closure::bindTo' => ['hasSideEffects' => false],
'Collator::__construct' => ['hasSideEffects' => false],
'Collator::compare' => ['hasSideEffects' => false],
'Collator::getAttribute' => ['hasSideEffects' => false],
'Collator::getErrorCode' => ['hasSideEffects' => false],
'Collator::getErrorMessage' => ['hasSideEffects' => false],
'Collator::getLocale' => ['hasSideEffects' => false],
'Collator::getSortKey' => ['hasSideEffects' => false],
'Collator::getStrength' => ['hasSideEffects' => false],
'DateTime::add' => ['hasSideEffects' => true],
'DateTime::createFromFormat' => ['hasSideEffects' => false],
'DateTime::createFromImmutable' => ['hasSideEffects' => false],
'DateTime::diff' => ['hasSideEffects' => false],
'DateTime::format' => ['hasSideEffects' => false],
'DateTime::getLastErrors' => ['hasSideEffects' => false],
'DateTime::getOffset' => ['hasSideEffects' => false],
'DateTime::getTimestamp' => ['hasSideEffects' => false],
'DateTime::getTimezone' => ['hasSideEffects' => false],
'DateTime::modify' => ['hasSideEffects' => true],
'DateTime::setDate' => ['hasSideEffects' => true],
'DateTime::setISODate' => ['hasSideEffects' => true],
'DateTime::setTime' => ['hasSideEffects' => true],
'DateTime::setTimestamp' => ['hasSideEffects' => true],
'DateTime::setTimezone' => ['hasSideEffects' => true],
'DateTime::sub' => ['hasSideEffects' => true],
'DateTimeImmutable::add' => ['hasSideEffects' => false],
'DateTimeImmutable::createFromFormat' => ['hasSideEffects' => false],
'DateTimeImmutable::createFromMutable' => ['hasSideEffects' => false],
'DateTimeImmutable::diff' => ['hasSideEffects' => false],
'DateTimeImmutable::format' => ['hasSideEffects' => false],
'DateTimeImmutable::getLastErrors' => ['hasSideEffects' => false],
'DateTimeImmutable::getOffset' => ['hasSideEffects' => false],
'DateTimeImmutable::getTimestamp' => ['hasSideEffects' => false],
'DateTimeImmutable::getTimezone' => ['hasSideEffects' => false],
'DateTimeImmutable::modify' => ['hasSideEffects' => false],
'DateTimeImmutable::setDate' => ['hasSideEffects' => false],
'DateTimeImmutable::setISODate' => ['hasSideEffects' => false],
'DateTimeImmutable::setTime' => ['hasSideEffects' => false],
'DateTimeImmutable::setTimestamp' => ['hasSideEffects' => false],
'DateTimeImmutable::setTimezone' => ['hasSideEffects' => false],
'DateTimeImmutable::sub' => ['hasSideEffects' => false],
'Error::__construct' => ['hasSideEffects' => false],
'ErrorException::__construct' => ['hasSideEffects' => false],
'Event::__construct' => ['hasSideEffects' => false],
'EventBase::getFeatures' => ['hasSideEffects' => false],
'EventBase::getMethod' => ['hasSideEffects' => false],
'EventBase::getTimeOfDayCached' => ['hasSideEffects' => false],
'EventBase::gotExit' => ['hasSideEffects' => false],
'EventBase::gotStop' => ['hasSideEffects' => false],
'EventBuffer::__construct' => ['hasSideEffects' => false],
'EventBufferEvent::__construct' => ['hasSideEffects' => false],
'EventBufferEvent::getDnsErrorString' => ['hasSideEffects' => false],
'EventBufferEvent::getEnabled' => ['hasSideEffects' => false],
'EventBufferEvent::getInput' => ['hasSideEffects' => false],
'EventBufferEvent::getOutput' => ['hasSideEffects' => false],
'EventConfig::__construct' => ['hasSideEffects' => false],
'EventDnsBase::__construct' => ['hasSideEffects' => false],
'EventHttpConnection::__construct' => ['hasSideEffects' => false],
'EventHttpRequest::__construct' => ['hasSideEffects' => false],
'EventHttpRequest::getCommand' => ['hasSideEffects' => false],
'EventHttpRequest::getConnection' => ['hasSideEffects' => false],
'EventHttpRequest::getHost' => ['hasSideEffects' => false],
'EventHttpRequest::getInputBuffer' => ['hasSideEffects' => false],
'EventHttpRequest::getInputHeaders' => ['hasSideEffects' => false],
'EventHttpRequest::getOutputBuffer' => ['hasSideEffects' => false],
'EventHttpRequest::getOutputHeaders' => ['hasSideEffects' => false],
'EventHttpRequest::getResponseCode' => ['hasSideEffects' => false],
'EventHttpRequest::getUri' => ['hasSideEffects' => false],
'EventSslContext::__construct' => ['hasSideEffects' => false],
'Exception::__construct' => ['hasSideEffects' => false],
'Exception::getCode' => ['hasSideEffects' => false],
'Exception::getFile' => ['hasSideEffects' => false],
'Exception::getLine' => ['hasSideEffects' => false],
'Exception::getMessage' => ['hasSideEffects' => false],
'Exception::getPrevious' => ['hasSideEffects' => false],
'Exception::getTrace' => ['hasSideEffects' => false],
'Exception::getTraceAsString' => ['hasSideEffects' => false],
'Gmagick::getcopyright' => ['hasSideEffects' => false],
'Gmagick::getfilename' => ['hasSideEffects' => false],
'Gmagick::getimagebackgroundcolor' => ['hasSideEffects' => false],
'Gmagick::getimageblueprimary' => ['hasSideEffects' => false],
'Gmagick::getimagebordercolor' => ['hasSideEffects' => false],
'Gmagick::getimagechanneldepth' => ['hasSideEffects' => false],
'Gmagick::getimagecolors' => ['hasSideEffects' => false],
'Gmagick::getimagecolorspace' => ['hasSideEffects' => false],
'Gmagick::getimagecompose' => ['hasSideEffects' => false],
'Gmagick::getimagedelay' => ['hasSideEffects' => false],
'Gmagick::getimagedepth' => ['hasSideEffects' => false],
'Gmagick::getimagedispose' => ['hasSideEffects' => false],
'Gmagick::getimageextrema' => ['hasSideEffects' => false],
'Gmagick::getimagefilename' => ['hasSideEffects' => false],
'Gmagick::getimageformat' => ['hasSideEffects' => false],
'Gmagick::getimagegamma' => ['hasSideEffects' => false],
'Gmagick::getimagegreenprimary' => ['hasSideEffects' => false],
'Gmagick::getimageheight' => ['hasSideEffects' => false],
'Gmagick::getimagehistogram' => ['hasSideEffects' => false],
'Gmagick::getimageindex' => ['hasSideEffects' => false],
'Gmagick::getimageinterlacescheme' => ['hasSideEffects' => false],
'Gmagick::getimageiterations' => ['hasSideEffects' => false],
'Gmagick::getimagematte' => ['hasSideEffects' => false],
'Gmagick::getimagemattecolor' => ['hasSideEffects' => false],
'Gmagick::getimageprofile' => ['hasSideEffects' => false],
'Gmagick::getimageredprimary' => ['hasSideEffects' => false],
'Gmagick::getimagerenderingintent' => ['hasSideEffects' => false],
'Gmagick::getimageresolution' => ['hasSideEffects' => false],
'Gmagick::getimagescene' => ['hasSideEffects' => false],
'Gmagick::getimagesignature' => ['hasSideEffects' => false],
'Gmagick::getimagetype' => ['hasSideEffects' => false],
'Gmagick::getimageunits' => ['hasSideEffects' => false],
'Gmagick::getimagewhitepoint' => ['hasSideEffects' => false],
'Gmagick::getimagewidth' => ['hasSideEffects' => false],
'Gmagick::getpackagename' => ['hasSideEffects' => false],
'Gmagick::getquantumdepth' => ['hasSideEffects' => false],
'Gmagick::getreleasedate' => ['hasSideEffects' => false],
'Gmagick::getsamplingfactors' => ['hasSideEffects' => false],
'Gmagick::getsize' => ['hasSideEffects' => false],
'Gmagick::getversion' => ['hasSideEffects' => false],
'GmagickDraw::getfillcolor' => ['hasSideEffects' => false],
'GmagickDraw::getfillopacity' => ['hasSideEffects' => false],
'GmagickDraw::getfont' => ['hasSideEffects' => false],
'GmagickDraw::getfontsize' => ['hasSideEffects' => false],
'GmagickDraw::getfontstyle' => ['hasSideEffects' => false],
'GmagickDraw::getfontweight' => ['hasSideEffects' => false],
'GmagickDraw::getstrokecolor' => ['hasSideEffects' => false],
'GmagickDraw::getstrokeopacity' => ['hasSideEffects' => false],
'GmagickDraw::getstrokewidth' => ['hasSideEffects' => false],
'GmagickDraw::gettextdecoration' => ['hasSideEffects' => false],
'GmagickDraw::gettextencoding' => ['hasSideEffects' => false],
'GmagickPixel::getcolor' => ['hasSideEffects' => false],
'GmagickPixel::getcolorcount' => ['hasSideEffects' => false],
'GmagickPixel::getcolorvalue' => ['hasSideEffects' => false],
'HttpMessage::getBody' => ['hasSideEffects' => false],
'HttpMessage::getHeader' => ['hasSideEffects' => false],
'HttpMessage::getHeaders' => ['hasSideEffects' => false],
'HttpMessage::getHttpVersion' => ['hasSideEffects' => false],
'HttpMessage::getInfo' => ['hasSideEffects' => false],
'HttpMessage::getParentMessage' => ['hasSideEffects' => false],
'HttpMessage::getRequestMethod' => ['hasSideEffects' => false],
'HttpMessage::getRequestUrl' => ['hasSideEffects' => false],
'HttpMessage::getResponseCode' => ['hasSideEffects' => false],
'HttpMessage::getResponseStatus' => ['hasSideEffects' => false],
'HttpMessage::getType' => ['hasSideEffects' => false],
'HttpQueryString::get' => ['hasSideEffects' => false],
'HttpQueryString::getArray' => ['hasSideEffects' => false],
'HttpQueryString::getBool' => ['hasSideEffects' => false],
'HttpQueryString::getFloat' => ['hasSideEffects' => false],
'HttpQueryString::getInt' => ['hasSideEffects' => false],
'HttpQueryString::getObject' => ['hasSideEffects' => false],
'HttpQueryString::getString' => ['hasSideEffects' => false],
'HttpRequest::getBody' => ['hasSideEffects' => false],
'HttpRequest::getContentType' => ['hasSideEffects' => false],
'HttpRequest::getCookies' => ['hasSideEffects' => false],
'HttpRequest::getHeaders' => ['hasSideEffects' => false],
'HttpRequest::getHistory' => ['hasSideEffects' => false],
'HttpRequest::getMethod' => ['hasSideEffects' => false],
'HttpRequest::getOptions' => ['hasSideEffects' => false],
'HttpRequest::getPostFields' => ['hasSideEffects' => false],
'HttpRequest::getPostFiles' => ['hasSideEffects' => false],
'HttpRequest::getPutData' => ['hasSideEffects' => false],
'HttpRequest::getPutFile' => ['hasSideEffects' => false],
'HttpRequest::getQueryData' => ['hasSideEffects' => false],
'HttpRequest::getRawPostData' => ['hasSideEffects' => false],
'HttpRequest::getRawRequestMessage' => ['hasSideEffects' => false],
'HttpRequest::getRawResponseMessage' => ['hasSideEffects' => false],
'HttpRequest::getRequestMessage' => ['hasSideEffects' => false],
'HttpRequest::getResponseBody' => ['hasSideEffects' => false],
'HttpRequest::getResponseCode' => ['hasSideEffects' => false],
'HttpRequest::getResponseCookies' => ['hasSideEffects' => false],
'HttpRequest::getResponseData' => ['hasSideEffects' => false],
'HttpRequest::getResponseHeader' => ['hasSideEffects' => false],
'HttpRequest::getResponseInfo' => ['hasSideEffects' => false],
'HttpRequest::getResponseMessage' => ['hasSideEffects' => false],
'HttpRequest::getResponseStatus' => ['hasSideEffects' => false],
'HttpRequest::getSslOptions' => ['hasSideEffects' => false],
'HttpRequest::getUrl' => ['hasSideEffects' => false],
'HttpRequestPool::getAttachedRequests' => ['hasSideEffects' => false],
'HttpRequestPool::getFinishedRequests' => ['hasSideEffects' => false],
'Imagick::getColorspace' => ['hasSideEffects' => false],
'Imagick::getCompression' => ['hasSideEffects' => false],
'Imagick::getCompressionQuality' => ['hasSideEffects' => false],
'Imagick::getConfigureOptions' => ['hasSideEffects' => false],
'Imagick::getFeatures' => ['hasSideEffects' => false],
'Imagick::getFilename' => ['hasSideEffects' => false],
'Imagick::getFont' => ['hasSideEffects' => false],
'Imagick::getFormat' => ['hasSideEffects' => false],
'Imagick::getGravity' => ['hasSideEffects' => false],
'Imagick::getHDRIEnabled' => ['hasSideEffects' => false],
'Imagick::getImage' => ['hasSideEffects' => false],
'Imagick::getImageAlphaChannel' => ['hasSideEffects' => false],
'Imagick::getImageArtifact' => ['hasSideEffects' => false],
'Imagick::getImageAttribute' => ['hasSideEffects' => false],
'Imagick::getImageBackgroundColor' => ['hasSideEffects' => false],
'Imagick::getImageBlob' => ['hasSideEffects' => false],
'Imagick::getImageBluePrimary' => ['hasSideEffects' => false],
'Imagick::getImageBorderColor' => ['hasSideEffects' => false],
'Imagick::getImageChannelDepth' => ['hasSideEffects' => false],
'Imagick::getImageChannelDistortion' => ['hasSideEffects' => false],
'Imagick::getImageChannelDistortions' => ['hasSideEffects' => false],
'Imagick::getImageChannelExtrema' => ['hasSideEffects' => false],
'Imagick::getImageChannelKurtosis' => ['hasSideEffects' => false],
'Imagick::getImageChannelMean' => ['hasSideEffects' => false],
'Imagick::getImageChannelRange' => ['hasSideEffects' => false],
'Imagick::getImageChannelStatistics' => ['hasSideEffects' => false],
'Imagick::getImageClipMask' => ['hasSideEffects' => false],
'Imagick::getImageColormapColor' => ['hasSideEffects' => false],
'Imagick::getImageColors' => ['hasSideEffects' => false],
'Imagick::getImageColorspace' => ['hasSideEffects' => false],
'Imagick::getImageCompose' => ['hasSideEffects' => false],
'Imagick::getImageCompression' => ['hasSideEffects' => false],
'Imagick::getImageCompressionQuality' => ['hasSideEffects' => false],
'Imagick::getImageDelay' => ['hasSideEffects' => false],
'Imagick::getImageDepth' => ['hasSideEffects' => false],
'Imagick::getImageDispose' => ['hasSideEffects' => false],
'Imagick::getImageDistortion' => ['hasSideEffects' => false],
'Imagick::getImageExtrema' => ['hasSideEffects' => false],
'Imagick::getImageFilename' => ['hasSideEffects' => false],
'Imagick::getImageFormat' => ['hasSideEffects' => false],
'Imagick::getImageGamma' => ['hasSideEffects' => false],
'Imagick::getImageGeometry' => ['hasSideEffects' => false],
'Imagick::getImageGravity' => ['hasSideEffects' => false],
'Imagick::getImageGreenPrimary' => ['hasSideEffects' => false],
'Imagick::getImageHeight' => ['hasSideEffects' => false],
'Imagick::getImageHistogram' => ['hasSideEffects' => false],
'Imagick::getImageIndex' => ['hasSideEffects' => false],
'Imagick::getImageInterlaceScheme' => ['hasSideEffects' => false],
'Imagick::getImageInterpolateMethod' => ['hasSideEffects' => false],
'Imagick::getImageIterations' => ['hasSideEffects' => false],
'Imagick::getImageLength' => ['hasSideEffects' => false],
'Imagick::getImageMatte' => ['hasSideEffects' => false],
'Imagick::getImageMatteColor' => ['hasSideEffects' => false],
'Imagick::getImageMimeType' => ['hasSideEffects' => false],
'Imagick::getImageOrientation' => ['hasSideEffects' => false],
'Imagick::getImagePage' => ['hasSideEffects' => false],
'Imagick::getImagePixelColor' => ['hasSideEffects' => false],
'Imagick::getImageProfile' => ['hasSideEffects' => false],
'Imagick::getImageProfiles' => ['hasSideEffects' => false],
'Imagick::getImageProperties' => ['hasSideEffects' => false],
'Imagick::getImageProperty' => ['hasSideEffects' => false],
'Imagick::getImageRedPrimary' => ['hasSideEffects' => false],
'Imagick::getImageRegion' => ['hasSideEffects' => false],
'Imagick::getImageRenderingIntent' => ['hasSideEffects' => false],
'Imagick::getImageResolution' => ['hasSideEffects' => false],
'Imagick::getImageScene' => ['hasSideEffects' => false],
'Imagick::getImageSignature' => ['hasSideEffects' => false],
'Imagick::getImageSize' => ['hasSideEffects' => false],
'Imagick::getImageTicksPerSecond' => ['hasSideEffects' => false],
'Imagick::getImageTotalInkDensity' => ['hasSideEffects' => false],
'Imagick::getImageType' => ['hasSideEffects' => false],
'Imagick::getImageUnits' => ['hasSideEffects' => false],
'Imagick::getImageVirtualPixelMethod' => ['hasSideEffects' => false],
'Imagick::getImageWhitePoint' => ['hasSideEffects' => false],
'Imagick::getImageWidth' => ['hasSideEffects' => false],
'Imagick::getImagesBlob' => ['hasSideEffects' => false],
'Imagick::getInterlaceScheme' => ['hasSideEffects' => false],
'Imagick::getIteratorIndex' => ['hasSideEffects' => false],
'Imagick::getNumberImages' => ['hasSideEffects' => false],
'Imagick::getOption' => ['hasSideEffects' => false],
'Imagick::getPage' => ['hasSideEffects' => false],
'Imagick::getPixelIterator' => ['hasSideEffects' => false],
'Imagick::getPixelRegionIterator' => ['hasSideEffects' => false],
'Imagick::getPointSize' => ['hasSideEffects' => false],
'Imagick::getSamplingFactors' => ['hasSideEffects' => false],
'Imagick::getSize' => ['hasSideEffects' => false],
'Imagick::getSizeOffset' => ['hasSideEffects' => false],
'ImagickDraw::getBorderColor' => ['hasSideEffects' => false],
'ImagickDraw::getClipPath' => ['hasSideEffects' => false],
'ImagickDraw::getClipRule' => ['hasSideEffects' => false],
'ImagickDraw::getClipUnits' => ['hasSideEffects' => false],
'ImagickDraw::getDensity' => ['hasSideEffects' => false],
'ImagickDraw::getFillColor' => ['hasSideEffects' => false],
'ImagickDraw::getFillOpacity' => ['hasSideEffects' => false],
'ImagickDraw::getFillRule' => ['hasSideEffects' => false],
'ImagickDraw::getFont' => ['hasSideEffects' => false],
'ImagickDraw::getFontFamily' => ['hasSideEffects' => false],
'ImagickDraw::getFontResolution' => ['hasSideEffects' => false],
'ImagickDraw::getFontSize' => ['hasSideEffects' => false],
'ImagickDraw::getFontStretch' => ['hasSideEffects' => false],
'ImagickDraw::getFontStyle' => ['hasSideEffects' => false],
'ImagickDraw::getFontWeight' => ['hasSideEffects' => false],
'ImagickDraw::getGravity' => ['hasSideEffects' => false],
'ImagickDraw::getOpacity' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeAntialias' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeColor' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeDashArray' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeDashOffset' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeLineCap' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeLineJoin' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeMiterLimit' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeOpacity' => ['hasSideEffects' => false],
'ImagickDraw::getStrokeWidth' => ['hasSideEffects' => false],
'ImagickDraw::getTextAlignment' => ['hasSideEffects' => false],
'ImagickDraw::getTextAntialias' => ['hasSideEffects' => false],
'ImagickDraw::getTextDecoration' => ['hasSideEffects' => false],
'ImagickDraw::getTextDirection' => ['hasSideEffects' => false],
'ImagickDraw::getTextEncoding' => ['hasSideEffects' => false],
'ImagickDraw::getTextInterLineSpacing' => ['hasSideEffects' => false],
'ImagickDraw::getTextInterWordSpacing' => ['hasSideEffects' => false],
'ImagickDraw::getTextKerning' => ['hasSideEffects' => false],
'ImagickDraw::getTextUnderColor' => ['hasSideEffects' => false],
'ImagickDraw::getVectorGraphics' => ['hasSideEffects' => false],
'ImagickKernel::getMatrix' => ['hasSideEffects' => false],
'ImagickPixel::getColor' => ['hasSideEffects' => false],
'ImagickPixel::getColorAsString' => ['hasSideEffects' => false],
'ImagickPixel::getColorCount' => ['hasSideEffects' => false],
'ImagickPixel::getColorQuantum' => ['hasSideEffects' => false],
'ImagickPixel::getColorValue' => ['hasSideEffects' => false],
'ImagickPixel::getColorValueQuantum' => ['hasSideEffects' => false],
'ImagickPixel::getHSL' => ['hasSideEffects' => false],
'ImagickPixel::getIndex' => ['hasSideEffects' => false],
'ImagickPixelIterator::getCurrentIteratorRow' => ['hasSideEffects' => false],
'ImagickPixelIterator::getIteratorRow' => ['hasSideEffects' => false],
'ImagickPixelIterator::getNextIteratorRow' => ['hasSideEffects' => false],
'ImagickPixelIterator::getPreviousIteratorRow' => ['hasSideEffects' => false],
'IntBackedEnum::from' => ['hasSideEffects' => false],
'IntBackedEnum::tryFrom' => ['hasSideEffects' => false],
'IntlBreakIterator::current' => ['hasSideEffects' => false],
'IntlBreakIterator::getErrorCode' => ['hasSideEffects' => false],
'IntlBreakIterator::getErrorMessage' => ['hasSideEffects' => false],
'IntlBreakIterator::getIterator' => ['hasSideEffects' => false],
'IntlBreakIterator::getLocale' => ['hasSideEffects' => false],
'IntlBreakIterator::getPartsIterator' => ['hasSideEffects' => false],
'IntlBreakIterator::getText' => ['hasSideEffects' => false],
'IntlBreakIterator::isBoundary' => ['hasSideEffects' => false],
'IntlCalendar::after' => ['hasSideEffects' => false],
'IntlCalendar::before' => ['hasSideEffects' => false],
'IntlCalendar::equals' => ['hasSideEffects' => false],
'IntlCalendar::fieldDifference' => ['hasSideEffects' => false],
'IntlCalendar::get' => ['hasSideEffects' => false],
'IntlCalendar::getActualMaximum' => ['hasSideEffects' => false],
'IntlCalendar::getActualMinimum' => ['hasSideEffects' => false],
'IntlCalendar::getDayOfWeekType' => ['hasSideEffects' => false],
'IntlCalendar::getErrorCode' => ['hasSideEffects' => false],
'IntlCalendar::getErrorMessage' => ['hasSideEffects' => false],
'IntlCalendar::getFirstDayOfWeek' => ['hasSideEffects' => false],
'IntlCalendar::getGreatestMinimum' => ['hasSideEffects' => false],
'IntlCalendar::getLeastMaximum' => ['hasSideEffects' => false],
'IntlCalendar::getLocale' => ['hasSideEffects' => false],
'IntlCalendar::getMaximum' => ['hasSideEffects' => false],
'IntlCalendar::getMinimalDaysInFirstWeek' => ['hasSideEffects' => false],
'IntlCalendar::getMinimum' => ['hasSideEffects' => false],
'IntlCalendar::getRepeatedWallTimeOption' => ['hasSideEffects' => false],
'IntlCalendar::getSkippedWallTimeOption' => ['hasSideEffects' => false],
'IntlCalendar::getTime' => ['hasSideEffects' => false],
'IntlCalendar::getTimeZone' => ['hasSideEffects' => false],
'IntlCalendar::getType' => ['hasSideEffects' => false],
'IntlCalendar::getWeekendTransition' => ['hasSideEffects' => false],
'IntlCalendar::inDaylightTime' => ['hasSideEffects' => false],
'IntlCalendar::isEquivalentTo' => ['hasSideEffects' => false],
'IntlCalendar::isLenient' => ['hasSideEffects' => false],
'IntlCalendar::isWeekend' => ['hasSideEffects' => false],
'IntlCalendar::toDateTime' => ['hasSideEffects' => false],
'IntlChar::hasBinaryProperty' => ['hasSideEffects' => false],
'IntlCodePointBreakIterator::getLastCodePoint' => ['hasSideEffects' => false],
'IntlDateFormatter::__construct' => ['hasSideEffects' => false],
'IntlDateFormatter::getCalendar' => ['hasSideEffects' => false],
'IntlDateFormatter::getCalendarObject' => ['hasSideEffects' => false],
'IntlDateFormatter::getDateType' => ['hasSideEffects' => false],
'IntlDateFormatter::getErrorCode' => ['hasSideEffects' => false],
'IntlDateFormatter::getErrorMessage' => ['hasSideEffects' => false],
'IntlDateFormatter::getLocale' => ['hasSideEffects' => false],
'IntlDateFormatter::getPattern' => ['hasSideEffects' => false],
'IntlDateFormatter::getTimeType' => ['hasSideEffects' => false],
'IntlDateFormatter::getTimeZone' => ['hasSideEffects' => false],
'IntlDateFormatter::getTimeZoneId' => ['hasSideEffects' => false],
'IntlDateFormatter::isLenient' => ['hasSideEffects' => false],
'IntlGregorianCalendar::getGregorianChange' => ['hasSideEffects' => false],
'IntlGregorianCalendar::isLeapYear' => ['hasSideEffects' => false],
'IntlPartsIterator::getBreakIterator' => ['hasSideEffects' => false],
'IntlRuleBasedBreakIterator::__construct' => ['hasSideEffects' => false],
'IntlRuleBasedBreakIterator::getBinaryRules' => ['hasSideEffects' => false],
'IntlRuleBasedBreakIterator::getRuleStatus' => ['hasSideEffects' => false],
'IntlRuleBasedBreakIterator::getRuleStatusVec' => ['hasSideEffects' => false],
'IntlRuleBasedBreakIterator::getRules' => ['hasSideEffects' => false],
'IntlTimeZone::getDSTSavings' => ['hasSideEffects' => false],
'IntlTimeZone::getDisplayName' => ['hasSideEffects' => false],
'IntlTimeZone::getErrorCode' => ['hasSideEffects' => false],
'IntlTimeZone::getErrorMessage' => ['hasSideEffects' => false],
'IntlTimeZone::getID' => ['hasSideEffects' => false],
'IntlTimeZone::getRawOffset' => ['hasSideEffects' => false],
'IntlTimeZone::hasSameRules' => ['hasSideEffects' => false],
'IntlTimeZone::toDateTimeZone' => ['hasSideEffects' => false],
'JsonIncrementalParser::__construct' => ['hasSideEffects' => false],
'JsonIncrementalParser::get' => ['hasSideEffects' => false],
'JsonIncrementalParser::getError' => ['hasSideEffects' => false],
'MemcachedException::__construct' => ['hasSideEffects' => false],
'MessageFormatter::__construct' => ['hasSideEffects' => false],
'MessageFormatter::format' => ['hasSideEffects' => false],
'MessageFormatter::getErrorCode' => ['hasSideEffects' => false],
'MessageFormatter::getErrorMessage' => ['hasSideEffects' => false],
'MessageFormatter::getLocale' => ['hasSideEffects' => false],
'MessageFormatter::getPattern' => ['hasSideEffects' => false],
'MessageFormatter::parse' => ['hasSideEffects' => false],
'NumberFormatter::__construct' => ['hasSideEffects' => false],
'NumberFormatter::format' => ['hasSideEffects' => false],
'NumberFormatter::formatCurrency' => ['hasSideEffects' => false],
'NumberFormatter::getAttribute' => ['hasSideEffects' => false],
'NumberFormatter::getErrorCode' => ['hasSideEffects' => false],
'NumberFormatter::getErrorMessage' => ['hasSideEffects' => false],
'NumberFormatter::getLocale' => ['hasSideEffects' => false],
'NumberFormatter::getPattern' => ['hasSideEffects' => false],
'NumberFormatter::getSymbol' => ['hasSideEffects' => false],
'NumberFormatter::getTextAttribute' => ['hasSideEffects' => false],
'ReflectionAttribute::getArguments' => ['hasSideEffects' => false],
'ReflectionAttribute::getName' => ['hasSideEffects' => false],
'ReflectionAttribute::getTarget' => ['hasSideEffects' => false],
'ReflectionAttribute::isRepeated' => ['hasSideEffects' => false],
'ReflectionClass::getAttributes' => ['hasSideEffects' => false],
'ReflectionClass::getConstant' => ['hasSideEffects' => false],
'ReflectionClass::getConstants' => ['hasSideEffects' => false],
'ReflectionClass::getConstructor' => ['hasSideEffects' => false],
'ReflectionClass::getDefaultProperties' => ['hasSideEffects' => false],
'ReflectionClass::getDocComment' => ['hasSideEffects' => false],
'ReflectionClass::getEndLine' => ['hasSideEffects' => false],
'ReflectionClass::getExtension' => ['hasSideEffects' => false],
'ReflectionClass::getExtensionName' => ['hasSideEffects' => false],
'ReflectionClass::getFileName' => ['hasSideEffects' => false],
'ReflectionClass::getInterfaceNames' => ['hasSideEffects' => false],
'ReflectionClass::getInterfaces' => ['hasSideEffects' => false],
'ReflectionClass::getMethod' => ['hasSideEffects' => false],
'ReflectionClass::getMethods' => ['hasSideEffects' => false],
'ReflectionClass::getModifiers' => ['hasSideEffects' => false],
'ReflectionClass::getName' => ['hasSideEffects' => false],
'ReflectionClass::getNamespaceName' => ['hasSideEffects' => false],
'ReflectionClass::getParentClass' => ['hasSideEffects' => false],
'ReflectionClass::getProperties' => ['hasSideEffects' => false],
'ReflectionClass::getProperty' => ['hasSideEffects' => false],
'ReflectionClass::getReflectionConstant' => ['hasSideEffects' => false],
'ReflectionClass::getReflectionConstants' => ['hasSideEffects' => false],
'ReflectionClass::getShortName' => ['hasSideEffects' => false],
'ReflectionClass::getStartLine' => ['hasSideEffects' => false],
'ReflectionClass::getStaticProperties' => ['hasSideEffects' => false],
'ReflectionClass::getStaticPropertyValue' => ['hasSideEffects' => false],
'ReflectionClass::getTraitAliases' => ['hasSideEffects' => false],
'ReflectionClass::getTraitNames' => ['hasSideEffects' => false],
'ReflectionClass::getTraits' => ['hasSideEffects' => false],
'ReflectionClass::isAbstract' => ['hasSideEffects' => false],
'ReflectionClass::isAnonymous' => ['hasSideEffects' => false],
'ReflectionClass::isCloneable' => ['hasSideEffects' => false],
'ReflectionClass::isFinal' => ['hasSideEffects' => false],
'ReflectionClass::isInstance' => ['hasSideEffects' => false],
'ReflectionClass::isInstantiable' => ['hasSideEffects' => false],
'ReflectionClass::isInterface' => ['hasSideEffects' => false],
'ReflectionClass::isInternal' => ['hasSideEffects' => false],
'ReflectionClass::isIterable' => ['hasSideEffects' => false],
'ReflectionClass::isIterateable' => ['hasSideEffects' => false],
'ReflectionClass::isReadOnly' => ['hasSideEffects' => false],
'ReflectionClass::isSubclassOf' => ['hasSideEffects' => false],
'ReflectionClass::isTrait' => ['hasSideEffects' => false],
'ReflectionClass::isUserDefined' => ['hasSideEffects' => false],
'ReflectionClassConstant::getAttributes' => ['hasSideEffects' => false],
'ReflectionClassConstant::getDeclaringClass' => ['hasSideEffects' => false],
'ReflectionClassConstant::getDocComment' => ['hasSideEffects' => false],
'ReflectionClassConstant::getModifiers' => ['hasSideEffects' => false],
'ReflectionClassConstant::getName' => ['hasSideEffects' => false],
'ReflectionClassConstant::getValue' => ['hasSideEffects' => false],
'ReflectionClassConstant::isPrivate' => ['hasSideEffects' => false],
'ReflectionClassConstant::isProtected' => ['hasSideEffects' => false],
'ReflectionClassConstant::isPublic' => ['hasSideEffects' => false],
'ReflectionEnumBackedCase::getBackingValue' => ['hasSideEffects' => false],
'ReflectionEnumUnitCase::getEnum' => ['hasSideEffects' => false],
'ReflectionEnumUnitCase::getValue' => ['hasSideEffects' => false],
'ReflectionExtension::getClassNames' => ['hasSideEffects' => false],
'ReflectionExtension::getClasses' => ['hasSideEffects' => false],
'ReflectionExtension::getConstants' => ['hasSideEffects' => false],
'ReflectionExtension::getDependencies' => ['hasSideEffects' => false],
'ReflectionExtension::getFunctions' => ['hasSideEffects' => false],
'ReflectionExtension::getINIEntries' => ['hasSideEffects' => false],
'ReflectionExtension::getName' => ['hasSideEffects' => false],
'ReflectionExtension::getVersion' => ['hasSideEffects' => false],
'ReflectionExtension::isPersistent' => ['hasSideEffects' => false],
'ReflectionExtension::isTemporary' => ['hasSideEffects' => false],
| php | MIT | 5ac07cdea5aad2a8fbc2ecc29fda11981d365112 | 2026-01-05T04:40:26.384644Z | true |
staabm/side-effects-detector | https://github.com/staabm/side-effects-detector/blob/5ac07cdea5aad2a8fbc2ecc29fda11981d365112/lib/SideEffectsDetector.php | lib/SideEffectsDetector.php | <?php
namespace staabm\SideEffectsDetector;
final class SideEffectsDetector {
/**
* @var array<int>
*/
private array $scopePollutingTokens = [
T_CLASS,
T_FUNCTION,
T_NEW,
T_EVAL,
T_GLOBAL,
T_GOTO,
T_HALT_COMPILER,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
T_THROW,
T_UNSET,
T_UNSET_CAST
];
private const PROCESS_EXIT_TOKENS = [
T_EXIT
];
private const OUTPUT_TOKENS = [
T_PRINT,
T_ECHO,
T_INLINE_HTML
];
private const SCOPE_POLLUTING_FUNCTIONS = [
'putenv',
'setlocale',
'class_exists',
'ini_set',
];
private const STANDARD_OUTPUT_FUNCTIONS = [
'printf',
'vprintf'
];
private const INPUT_OUTPUT_FUNCTIONS = [
'fopen',
'file_get_contents',
'file_put_contents',
'fwrite',
'fputs',
'fread',
'unlink'
];
/**
* @var array<string, array{'hasSideEffects': bool}>
*/
private array $functionMetadata;
public function __construct() {
$functionMeta = require __DIR__ . '/functionMetadata.php';
if (!is_array($functionMeta)) {
throw new \RuntimeException('Invalid function metadata');
}
$this->functionMetadata = $functionMeta;
if (defined('T_ENUM')) {
$this->scopePollutingTokens[] = T_ENUM;
}
}
/**
* @api
*
* @return array<SideEffect::*>
*/
public function getSideEffects(string $code): array {
$tokens = token_get_all($code);
$sideEffects = [];
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (!is_array($token)) {
continue;
}
if ($this->isAnonymousFunction($tokens, $i)) {
continue;
}
if (in_array($token[0], self::OUTPUT_TOKENS, true)) {
$sideEffects[] = SideEffect::STANDARD_OUTPUT;
continue;
}
if (in_array($token[0], self::PROCESS_EXIT_TOKENS, true)) {
$sideEffects[] = SideEffect::PROCESS_EXIT;
continue;
}
if (in_array($token[0], $this->scopePollutingTokens, true)) {
$sideEffects[] = SideEffect::SCOPE_POLLUTION;
$i++;
if (in_array($token[0], [T_FUNCTION, T_CLASS], true)) {
$this->consumeWhitespaces($tokens, $i);
}
// consume function/class-name
if (
!array_key_exists($i, $tokens)
|| !is_array($tokens[$i])
|| $tokens[$i][0] !== T_STRING
) {
continue;
}
$i++;
continue;
}
$functionCall = $this->getFunctionCall($tokens, $i);
if ($functionCall !== null) {
$callSideEffect = $this->getFunctionCallSideEffect($functionCall);
if ($callSideEffect !== null) {
$sideEffects[] = $callSideEffect;
}
continue;
}
$methodCall = $this->getMethodCall($tokens, $i);
if ($methodCall !== null) {
$sideEffects[] = SideEffect::MAYBE;
continue;
}
$propertyAccess = $this->getPropertyAccess($tokens, $i);
if ($propertyAccess !== null) {
$sideEffects[] = SideEffect::SCOPE_POLLUTION;
continue;
}
if ($this->isNonLocalVariable($tokens, $i)) {
$sideEffects[] = SideEffect::SCOPE_POLLUTION;
continue;
}
}
return array_values(array_unique($sideEffects));
}
/**
* @return SideEffect::*|null
*/
private function getFunctionCallSideEffect(string $functionName): ?string { // @phpstan-ignore return.unusedType
if (in_array($functionName, self::STANDARD_OUTPUT_FUNCTIONS, true)) {
return SideEffect::STANDARD_OUTPUT;
}
if (in_array($functionName, self::INPUT_OUTPUT_FUNCTIONS, true)) {
return SideEffect::INPUT_OUTPUT;
}
if (in_array($functionName, self::SCOPE_POLLUTING_FUNCTIONS, true)) {
return SideEffect::SCOPE_POLLUTION;
}
if (array_key_exists($functionName, $this->functionMetadata)) {
if ($this->functionMetadata[$functionName]['hasSideEffects'] === true) {
return SideEffect::UNKNOWN_CLASS;
}
} else {
try {
$reflectionFunction = new \ReflectionFunction($functionName);
$returnType = $reflectionFunction->getReturnType();
if ($returnType === null) {
return SideEffect::MAYBE; // no reflection information -> we don't know
}
if ((string)$returnType === 'void') {
return SideEffect::UNKNOWN_CLASS; // functions with void return type must have side-effects
}
} catch (\ReflectionException $e) {
return SideEffect::MAYBE; // function does not exist -> we don't know
}
}
return null;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function getFunctionCall(array $tokens, int $index): ?string {
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| $tokens[$index][0] !== T_STRING
) {
return null;
}
$functionName = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
array_key_exists($index, $tokens)
&& $tokens[$index] === '('
) {
return $functionName;
}
return null;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function getMethodCall(array $tokens, int $index): ?string {
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_VARIABLE, T_STRING], true)
) {
return null;
}
$callee = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_OBJECT_OPERATOR , T_DOUBLE_COLON ], true)
) {
return null;
}
$operator = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_STRING], true)
) {
return null;
}
$method = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
array_key_exists($index, $tokens)
&& $tokens[$index] !== '('
) {
return null;
}
return $callee . $operator . $method;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function getPropertyAccess(array $tokens, int $index): ?string {
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_VARIABLE, T_STRING], true)
) {
return null;
}
$objectOrClass = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_OBJECT_OPERATOR , T_DOUBLE_COLON ], true)
) {
return null;
}
$operator = $tokens[$index][1];
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| !in_array($tokens[$index][0], [T_STRING, T_VARIABLE], true)
) {
return null;
}
$propName = $tokens[$index][1];
return $objectOrClass . $operator . $propName;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function isAnonymousFunction(array $tokens, int $index): bool
{
if (
!array_key_exists($index, $tokens)
|| !is_array($tokens[$index])
|| $tokens[$index][0] !== T_FUNCTION
) {
return false;
}
$index++;
$this->consumeWhitespaces($tokens, $index);
if (
array_key_exists($index, $tokens)
&& $tokens[$index] === '('
) {
return true;
}
return false;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function isNonLocalVariable(array $tokens, int $index): bool
{
if (
array_key_exists($index, $tokens)
&& is_array($tokens[$index])
&& $tokens[$index][0] === T_VARIABLE
) {
if (
in_array(
$tokens[$index][1],
[
'$this',
'$GLOBALS', '$_SERVER', '$_GET', '$_POST', '$_FILES', '$_COOKIE', '$_SESSION', '$_REQUEST', '$_ENV',
],
true)
) {
return true;
}
}
return false;
}
/**
* @param array<int, array{0:int,1:string,2:int}|string|int> $tokens
*/
private function consumeWhitespaces(array $tokens, int &$index): void {
while (
array_key_exists($index, $tokens)
&& is_array($tokens[$index])
&& $tokens[$index][0] === T_WHITESPACE
) {
$index++;
}
}
}
| php | MIT | 5ac07cdea5aad2a8fbc2ecc29fda11981d365112 | 2026-01-05T04:40:26.384644Z | false |
staabm/side-effects-detector | https://github.com/staabm/side-effects-detector/blob/5ac07cdea5aad2a8fbc2ecc29fda11981d365112/lib/SideEffect.php | lib/SideEffect.php | <?php
namespace staabm\SideEffectsDetector;
/**
* @api
*/
final class SideEffect {
/**
* die, exit, throw.
*/
const PROCESS_EXIT = 'process_exit';
/**
* class definition, func definition, include, require, global var, unset, goto
*/
const SCOPE_POLLUTION = 'scope_pollution';
/**
* fwrite, unlink...
*/
const INPUT_OUTPUT = 'input_output';
/**
* echo, print.
*/
const STANDARD_OUTPUT = 'standard_output';
/**
* code for sure has side-effects, we don't have enough information to classify it.
*/
const UNKNOWN_CLASS = 'unknown_class';
/**
* code might have side-effects, but we can't tell for sure.
*/
const MAYBE = 'maybe_has_side_effects';
private function __construct() {
// nothing todo
}
} | php | MIT | 5ac07cdea5aad2a8fbc2ecc29fda11981d365112 | 2026-01-05T04:40:26.384644Z | false |
BenSampo/laravel-embed | https://github.com/BenSampo/laravel-embed/blob/6692360e65a2f024900a56a564ca23da6ef3d145/src/EmbedServiceProvider.php | src/EmbedServiceProvider.php | <?php
namespace BenSampo\Embed;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use BenSampo\Embed\ViewComponents\EmbedViewComponent;
use BenSampo\Embed\ViewComponents\StylesViewComponent;
use BenSampo\Embed\ViewComponents\ResponsiveWrapperViewComponent;
class EmbedServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Blade::component('embed', EmbedViewComponent::class);
Blade::component('embed-responsive-wrapper', ResponsiveWrapperViewComponent::class);
Blade::component('embed-styles', StylesViewComponent::class);
$this->loadViewsFrom(__DIR__.'/../resources/views', 'embed');
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/embed'),
]);
}
}
| php | MIT | 6692360e65a2f024900a56a564ca23da6ef3d145 | 2026-01-05T04:40:24.357530Z | false |
BenSampo/laravel-embed | https://github.com/BenSampo/laravel-embed/blob/6692360e65a2f024900a56a564ca23da6ef3d145/src/ServiceContract.php | src/ServiceContract.php | <?php
namespace BenSampo\Embed;
use Illuminate\Contracts\View\View;
use BenSampo\Embed\ValueObjects\Ratio;
use BenSampo\Embed\ValueObjects\Url;
interface ServiceContract
{
public static function detect(Url $url): bool;
public function view(): View;
public function cacheAndRender(): string;
public function setAspectRatio(?Ratio $aspectRatio): ServiceContract;
public function setLabel(?string $label): ServiceContract;
} | php | MIT | 6692360e65a2f024900a56a564ca23da6ef3d145 | 2026-01-05T04:40:24.357530Z | false |
BenSampo/laravel-embed | https://github.com/BenSampo/laravel-embed/blob/6692360e65a2f024900a56a564ca23da6ef3d145/src/ServiceFactory.php | src/ServiceFactory.php | <?php
namespace BenSampo\Embed;
use BenSampo\Embed\ValueObjects\Url;
use Symfony\Component\Finder\Finder;
use BenSampo\Embed\Services\Fallback;
use Illuminate\Support\Facades\Cache;
use BenSampo\Embed\Tests\Fakes\ServiceFactoryFake;
use BenSampo\Embed\Exceptions\ServiceNotFoundException;
class ServiceFactory
{
protected $serviceClassesPath = __DIR__ . '/Services';
protected $serviceClassesNamespace = "BenSampo\Embed\Services\\";
public static function getByUrl(Url $url): ServiceContract
{
$factory = self::resolve();
$cacheKey = 'larevel-embed-service::' . $url;
if (Cache::has($cacheKey)) {
$serviceClass = Cache::get($cacheKey);
return new $serviceClass($url);
}
foreach ($factory->serviceClasses() as $serviceClass) {
if ($serviceClass::detect($url)) {
Cache::forever($cacheKey, $serviceClass);
return new $serviceClass($url);
};
}
throw new ServiceNotFoundException($url);
}
public static function getFallback(Url $url): ServiceContract
{
return new Fallback($url);
}
public static function fake(): void
{
app()->instance(ServiceFactory::class, new ServiceFactoryFake);
}
public function serviceClasses(): array
{
$directoryIterator = (new Finder)
->files()
->in($this->serviceClassesPath)
->name('*.php')
->getIterator();
$serviceClasses = [];
foreach ($directoryIterator as $file) {
$serviceClasses[] = $this->serviceClassesNamespace . $file->getFilenameWithoutExtension();
}
return $serviceClasses;
}
protected static function resolve(): self
{
return resolve(self::class);
}
} | php | MIT | 6692360e65a2f024900a56a564ca23da6ef3d145 | 2026-01-05T04:40:24.357530Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.