repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
bobthecow/psysh | src/ParserFactory.php | ParserFactory.createParser | public function createParser($kind = null)
{
if ($this->hasKindsSupport()) {
$originalFactory = new OriginalParserFactory();
$kind = $kind ?: $this->getDefaultKind();
if (!\in_array($kind, static::getPossibleKinds())) {
throw new \InvalidArgumentException('Unknown parser kind');
}
$parser = $originalFactory->create(\constant('PhpParser\ParserFactory::' . $kind));
} else {
if ($kind !== null) {
throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');
}
$parser = new Parser(new Lexer());
}
return $parser;
} | php | public function createParser($kind = null)
{
if ($this->hasKindsSupport()) {
$originalFactory = new OriginalParserFactory();
$kind = $kind ?: $this->getDefaultKind();
if (!\in_array($kind, static::getPossibleKinds())) {
throw new \InvalidArgumentException('Unknown parser kind');
}
$parser = $originalFactory->create(\constant('PhpParser\ParserFactory::' . $kind));
} else {
if ($kind !== null) {
throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');
}
$parser = new Parser(new Lexer());
}
return $parser;
} | [
"public",
"function",
"createParser",
"(",
"$",
"kind",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasKindsSupport",
"(",
")",
")",
"{",
"$",
"originalFactory",
"=",
"new",
"OriginalParserFactory",
"(",
")",
";",
"$",
"kind",
"=",
"$",
"kind",
"?",
":",
"$",
"this",
"->",
"getDefaultKind",
"(",
")",
";",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"kind",
",",
"static",
"::",
"getPossibleKinds",
"(",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unknown parser kind'",
")",
";",
"}",
"$",
"parser",
"=",
"$",
"originalFactory",
"->",
"create",
"(",
"\\",
"constant",
"(",
"'PhpParser\\ParserFactory::'",
".",
"$",
"kind",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"kind",
"!==",
"null",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Install PHP Parser v2.x to specify parser kind'",
")",
";",
"}",
"$",
"parser",
"=",
"new",
"Parser",
"(",
"new",
"Lexer",
"(",
")",
")",
";",
"}",
"return",
"$",
"parser",
";",
"}"
] | New parser instance with given kind.
@param string|null $kind One of class constants (only for PHP parser 2.0 and above)
@return Parser | [
"New",
"parser",
"instance",
"with",
"given",
"kind",
"."
] | 9aaf29575bb8293206bb0420c1e1c87ff2ffa94e | https://github.com/bobthecow/psysh/blob/9aaf29575bb8293206bb0420c1e1c87ff2ffa94e/src/ParserFactory.php#L69-L90 | train |
jeremykenedy/laravel-logger | src/app/Http/Middleware/LogActivity.php | LogActivity.shouldLog | protected function shouldLog($request)
{
foreach (config('LaravelLogger.loggerMiddlewareExcept', []) as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->is($except)) {
return false;
}
}
return true;
} | php | protected function shouldLog($request)
{
foreach (config('LaravelLogger.loggerMiddlewareExcept', []) as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->is($except)) {
return false;
}
}
return true;
} | [
"protected",
"function",
"shouldLog",
"(",
"$",
"request",
")",
"{",
"foreach",
"(",
"config",
"(",
"'LaravelLogger.loggerMiddlewareExcept'",
",",
"[",
"]",
")",
"as",
"$",
"except",
")",
"{",
"if",
"(",
"$",
"except",
"!==",
"'/'",
")",
"{",
"$",
"except",
"=",
"trim",
"(",
"$",
"except",
",",
"'/'",
")",
";",
"}",
"if",
"(",
"$",
"request",
"->",
"is",
"(",
"$",
"except",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Determine if the request has a URI that should log.
@param \Illuminate\Http\Request $request
@return bool | [
"Determine",
"if",
"the",
"request",
"has",
"a",
"URI",
"that",
"should",
"log",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Middleware/LogActivity.php#L37-L50 | train |
jeremykenedy/laravel-logger | src/LaravelLoggerServiceProvider.php | LaravelLoggerServiceProvider.registerEventListeners | private function registerEventListeners()
{
$listeners = $this->getListeners();
foreach ($listeners as $listenerKey => $listenerValues) {
foreach ($listenerValues as $listenerValue) {
\Event::listen($listenerKey,
$listenerValue
);
}
}
} | php | private function registerEventListeners()
{
$listeners = $this->getListeners();
foreach ($listeners as $listenerKey => $listenerValues) {
foreach ($listenerValues as $listenerValue) {
\Event::listen($listenerKey,
$listenerValue
);
}
}
} | [
"private",
"function",
"registerEventListeners",
"(",
")",
"{",
"$",
"listeners",
"=",
"$",
"this",
"->",
"getListeners",
"(",
")",
";",
"foreach",
"(",
"$",
"listeners",
"as",
"$",
"listenerKey",
"=>",
"$",
"listenerValues",
")",
"{",
"foreach",
"(",
"$",
"listenerValues",
"as",
"$",
"listenerValue",
")",
"{",
"\\",
"Event",
"::",
"listen",
"(",
"$",
"listenerKey",
",",
"$",
"listenerValue",
")",
";",
"}",
"}",
"}"
] | Register the list of listeners and events.
@return void | [
"Register",
"the",
"list",
"of",
"listeners",
"and",
"events",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/LaravelLoggerServiceProvider.php#L100-L110 | train |
jeremykenedy/laravel-logger | src/LaravelLoggerServiceProvider.php | LaravelLoggerServiceProvider.publishFiles | private function publishFiles()
{
$publishTag = 'LaravelLogger';
$this->publishes([
__DIR__.'/config/laravel-logger.php' => base_path('config/laravel-logger.php'),
], $publishTag);
$this->publishes([
__DIR__.'/resources/views' => base_path('resources/views/vendor/'.$publishTag),
], $publishTag);
$this->publishes([
__DIR__.'/resources/lang' => base_path('resources/lang/vendor/'.$publishTag),
], $publishTag);
} | php | private function publishFiles()
{
$publishTag = 'LaravelLogger';
$this->publishes([
__DIR__.'/config/laravel-logger.php' => base_path('config/laravel-logger.php'),
], $publishTag);
$this->publishes([
__DIR__.'/resources/views' => base_path('resources/views/vendor/'.$publishTag),
], $publishTag);
$this->publishes([
__DIR__.'/resources/lang' => base_path('resources/lang/vendor/'.$publishTag),
], $publishTag);
} | [
"private",
"function",
"publishFiles",
"(",
")",
"{",
"$",
"publishTag",
"=",
"'LaravelLogger'",
";",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/config/laravel-logger.php'",
"=>",
"base_path",
"(",
"'config/laravel-logger.php'",
")",
",",
"]",
",",
"$",
"publishTag",
")",
";",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/resources/views'",
"=>",
"base_path",
"(",
"'resources/views/vendor/'",
".",
"$",
"publishTag",
")",
",",
"]",
",",
"$",
"publishTag",
")",
";",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/resources/lang'",
"=>",
"base_path",
"(",
"'resources/lang/vendor/'",
".",
"$",
"publishTag",
")",
",",
"]",
",",
"$",
"publishTag",
")",
";",
"}"
] | Publish files for Laravel Logger.
@return void | [
"Publish",
"files",
"for",
"Laravel",
"Logger",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/LaravelLoggerServiceProvider.php#L117-L132 | train |
jeremykenedy/laravel-logger | src/app/Http/Controllers/LaravelLoggerController.php | LaravelLoggerController.mapAdditionalDetails | private function mapAdditionalDetails($collectionItems)
{
$collectionItems->map(function ($collectionItem) {
$eventTime = Carbon::parse($collectionItem->updated_at);
$collectionItem['timePassed'] = $eventTime->diffForHumans();
$collectionItem['userAgentDetails'] = UserAgentDetails::details($collectionItem->useragent);
$collectionItem['langDetails'] = UserAgentDetails::localeLang($collectionItem->locale);
$collectionItem['userDetails'] = config('LaravelLogger.defaultUserModel')::find($collectionItem->userId);
return $collectionItem;
});
return $collectionItems;
} | php | private function mapAdditionalDetails($collectionItems)
{
$collectionItems->map(function ($collectionItem) {
$eventTime = Carbon::parse($collectionItem->updated_at);
$collectionItem['timePassed'] = $eventTime->diffForHumans();
$collectionItem['userAgentDetails'] = UserAgentDetails::details($collectionItem->useragent);
$collectionItem['langDetails'] = UserAgentDetails::localeLang($collectionItem->locale);
$collectionItem['userDetails'] = config('LaravelLogger.defaultUserModel')::find($collectionItem->userId);
return $collectionItem;
});
return $collectionItems;
} | [
"private",
"function",
"mapAdditionalDetails",
"(",
"$",
"collectionItems",
")",
"{",
"$",
"collectionItems",
"->",
"map",
"(",
"function",
"(",
"$",
"collectionItem",
")",
"{",
"$",
"eventTime",
"=",
"Carbon",
"::",
"parse",
"(",
"$",
"collectionItem",
"->",
"updated_at",
")",
";",
"$",
"collectionItem",
"[",
"'timePassed'",
"]",
"=",
"$",
"eventTime",
"->",
"diffForHumans",
"(",
")",
";",
"$",
"collectionItem",
"[",
"'userAgentDetails'",
"]",
"=",
"UserAgentDetails",
"::",
"details",
"(",
"$",
"collectionItem",
"->",
"useragent",
")",
";",
"$",
"collectionItem",
"[",
"'langDetails'",
"]",
"=",
"UserAgentDetails",
"::",
"localeLang",
"(",
"$",
"collectionItem",
"->",
"locale",
")",
";",
"$",
"collectionItem",
"[",
"'userDetails'",
"]",
"=",
"config",
"(",
"'LaravelLogger.defaultUserModel'",
")",
"::",
"find",
"(",
"$",
"collectionItem",
"->",
"userId",
")",
";",
"return",
"$",
"collectionItem",
";",
"}",
")",
";",
"return",
"$",
"collectionItems",
";",
"}"
] | Add additional details to a collections.
@param collection $collectionItems
@return collection | [
"Add",
"additional",
"details",
"to",
"a",
"collections",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L46-L59 | train |
jeremykenedy/laravel-logger | src/app/Http/Controllers/LaravelLoggerController.php | LaravelLoggerController.showAccessLogEntry | public function showAccessLogEntry(Request $request, $id)
{
$activity = Activity::findOrFail($id);
$userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId);
$userAgentDetails = UserAgentDetails::details($activity->useragent);
$ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress);
$langDetails = UserAgentDetails::localeLang($activity->locale);
$eventTime = Carbon::parse($activity->created_at);
$timePassed = $eventTime->diffForHumans();
if (config('LaravelLogger.loggerPaginationEnabled')) {
$userActivities = Activity::where('userId', $activity->userId)
->orderBy('created_at', 'desc')
->paginate(config('LaravelLogger.loggerPaginationPerPage'));
$totalUserActivities = $userActivities->total();
} else {
$userActivities = Activity::where('userId', $activity->userId)
->orderBy('created_at', 'desc')
->get();
$totalUserActivities = $userActivities->count();
}
self::mapAdditionalDetails($userActivities);
$data = [
'activity' => $activity,
'userDetails' => $userDetails,
'ipAddressDetails' => $ipAddressDetails,
'timePassed' => $timePassed,
'userAgentDetails' => $userAgentDetails,
'langDetails' => $langDetails,
'userActivities' => $userActivities,
'totalUserActivities' => $totalUserActivities,
'isClearedEntry' => false,
];
return View('LaravelLogger::logger.activity-log-item', $data);
} | php | public function showAccessLogEntry(Request $request, $id)
{
$activity = Activity::findOrFail($id);
$userDetails = config('LaravelLogger.defaultUserModel')::find($activity->userId);
$userAgentDetails = UserAgentDetails::details($activity->useragent);
$ipAddressDetails = IpAddressDetails::checkIP($activity->ipAddress);
$langDetails = UserAgentDetails::localeLang($activity->locale);
$eventTime = Carbon::parse($activity->created_at);
$timePassed = $eventTime->diffForHumans();
if (config('LaravelLogger.loggerPaginationEnabled')) {
$userActivities = Activity::where('userId', $activity->userId)
->orderBy('created_at', 'desc')
->paginate(config('LaravelLogger.loggerPaginationPerPage'));
$totalUserActivities = $userActivities->total();
} else {
$userActivities = Activity::where('userId', $activity->userId)
->orderBy('created_at', 'desc')
->get();
$totalUserActivities = $userActivities->count();
}
self::mapAdditionalDetails($userActivities);
$data = [
'activity' => $activity,
'userDetails' => $userDetails,
'ipAddressDetails' => $ipAddressDetails,
'timePassed' => $timePassed,
'userAgentDetails' => $userAgentDetails,
'langDetails' => $langDetails,
'userActivities' => $userActivities,
'totalUserActivities' => $totalUserActivities,
'isClearedEntry' => false,
];
return View('LaravelLogger::logger.activity-log-item', $data);
} | [
"public",
"function",
"showAccessLogEntry",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"$",
"activity",
"=",
"Activity",
"::",
"findOrFail",
"(",
"$",
"id",
")",
";",
"$",
"userDetails",
"=",
"config",
"(",
"'LaravelLogger.defaultUserModel'",
")",
"::",
"find",
"(",
"$",
"activity",
"->",
"userId",
")",
";",
"$",
"userAgentDetails",
"=",
"UserAgentDetails",
"::",
"details",
"(",
"$",
"activity",
"->",
"useragent",
")",
";",
"$",
"ipAddressDetails",
"=",
"IpAddressDetails",
"::",
"checkIP",
"(",
"$",
"activity",
"->",
"ipAddress",
")",
";",
"$",
"langDetails",
"=",
"UserAgentDetails",
"::",
"localeLang",
"(",
"$",
"activity",
"->",
"locale",
")",
";",
"$",
"eventTime",
"=",
"Carbon",
"::",
"parse",
"(",
"$",
"activity",
"->",
"created_at",
")",
";",
"$",
"timePassed",
"=",
"$",
"eventTime",
"->",
"diffForHumans",
"(",
")",
";",
"if",
"(",
"config",
"(",
"'LaravelLogger.loggerPaginationEnabled'",
")",
")",
"{",
"$",
"userActivities",
"=",
"Activity",
"::",
"where",
"(",
"'userId'",
",",
"$",
"activity",
"->",
"userId",
")",
"->",
"orderBy",
"(",
"'created_at'",
",",
"'desc'",
")",
"->",
"paginate",
"(",
"config",
"(",
"'LaravelLogger.loggerPaginationPerPage'",
")",
")",
";",
"$",
"totalUserActivities",
"=",
"$",
"userActivities",
"->",
"total",
"(",
")",
";",
"}",
"else",
"{",
"$",
"userActivities",
"=",
"Activity",
"::",
"where",
"(",
"'userId'",
",",
"$",
"activity",
"->",
"userId",
")",
"->",
"orderBy",
"(",
"'created_at'",
",",
"'desc'",
")",
"->",
"get",
"(",
")",
";",
"$",
"totalUserActivities",
"=",
"$",
"userActivities",
"->",
"count",
"(",
")",
";",
"}",
"self",
"::",
"mapAdditionalDetails",
"(",
"$",
"userActivities",
")",
";",
"$",
"data",
"=",
"[",
"'activity'",
"=>",
"$",
"activity",
",",
"'userDetails'",
"=>",
"$",
"userDetails",
",",
"'ipAddressDetails'",
"=>",
"$",
"ipAddressDetails",
",",
"'timePassed'",
"=>",
"$",
"timePassed",
",",
"'userAgentDetails'",
"=>",
"$",
"userAgentDetails",
",",
"'langDetails'",
"=>",
"$",
"langDetails",
",",
"'userActivities'",
"=>",
"$",
"userActivities",
",",
"'totalUserActivities'",
"=>",
"$",
"totalUserActivities",
",",
"'isClearedEntry'",
"=>",
"false",
",",
"]",
";",
"return",
"View",
"(",
"'LaravelLogger::logger.activity-log-item'",
",",
"$",
"data",
")",
";",
"}"
] | Show an individual activity log entry.
@param Request $request
@param int $id
@return \Illuminate\Http\Response | [
"Show",
"an",
"individual",
"activity",
"log",
"entry",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L94-L132 | train |
jeremykenedy/laravel-logger | src/app/Http/Controllers/LaravelLoggerController.php | LaravelLoggerController.showClearedActivityLog | public function showClearedActivityLog()
{
if (config('LaravelLogger.loggerPaginationEnabled')) {
$activities = Activity::onlyTrashed()
->orderBy('created_at', 'desc')
->paginate(config('LaravelLogger.loggerPaginationPerPage'));
$totalActivities = $activities->total();
} else {
$activities = Activity::onlyTrashed()
->orderBy('created_at', 'desc')
->get();
$totalActivities = $activities->count();
}
self::mapAdditionalDetails($activities);
$data = [
'activities' => $activities,
'totalActivities' => $totalActivities,
];
return View('LaravelLogger::logger.activity-log-cleared', $data);
} | php | public function showClearedActivityLog()
{
if (config('LaravelLogger.loggerPaginationEnabled')) {
$activities = Activity::onlyTrashed()
->orderBy('created_at', 'desc')
->paginate(config('LaravelLogger.loggerPaginationPerPage'));
$totalActivities = $activities->total();
} else {
$activities = Activity::onlyTrashed()
->orderBy('created_at', 'desc')
->get();
$totalActivities = $activities->count();
}
self::mapAdditionalDetails($activities);
$data = [
'activities' => $activities,
'totalActivities' => $totalActivities,
];
return View('LaravelLogger::logger.activity-log-cleared', $data);
} | [
"public",
"function",
"showClearedActivityLog",
"(",
")",
"{",
"if",
"(",
"config",
"(",
"'LaravelLogger.loggerPaginationEnabled'",
")",
")",
"{",
"$",
"activities",
"=",
"Activity",
"::",
"onlyTrashed",
"(",
")",
"->",
"orderBy",
"(",
"'created_at'",
",",
"'desc'",
")",
"->",
"paginate",
"(",
"config",
"(",
"'LaravelLogger.loggerPaginationPerPage'",
")",
")",
";",
"$",
"totalActivities",
"=",
"$",
"activities",
"->",
"total",
"(",
")",
";",
"}",
"else",
"{",
"$",
"activities",
"=",
"Activity",
"::",
"onlyTrashed",
"(",
")",
"->",
"orderBy",
"(",
"'created_at'",
",",
"'desc'",
")",
"->",
"get",
"(",
")",
";",
"$",
"totalActivities",
"=",
"$",
"activities",
"->",
"count",
"(",
")",
";",
"}",
"self",
"::",
"mapAdditionalDetails",
"(",
"$",
"activities",
")",
";",
"$",
"data",
"=",
"[",
"'activities'",
"=>",
"$",
"activities",
",",
"'totalActivities'",
"=>",
"$",
"totalActivities",
",",
"]",
";",
"return",
"View",
"(",
"'LaravelLogger::logger.activity-log-cleared'",
",",
"$",
"data",
")",
";",
"}"
] | Show the cleared activity log - softdeleted records.
@return \Illuminate\Http\Response | [
"Show",
"the",
"cleared",
"activity",
"log",
"-",
"softdeleted",
"records",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L156-L178 | train |
jeremykenedy/laravel-logger | src/app/Http/Controllers/LaravelLoggerController.php | LaravelLoggerController.destroyActivityLog | public function destroyActivityLog(Request $request)
{
$activities = Activity::onlyTrashed()->get();
foreach ($activities as $activity) {
$activity->forceDelete();
}
return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly'));
} | php | public function destroyActivityLog(Request $request)
{
$activities = Activity::onlyTrashed()->get();
foreach ($activities as $activity) {
$activity->forceDelete();
}
return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly'));
} | [
"public",
"function",
"destroyActivityLog",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"activities",
"=",
"Activity",
"::",
"onlyTrashed",
"(",
")",
"->",
"get",
"(",
")",
";",
"foreach",
"(",
"$",
"activities",
"as",
"$",
"activity",
")",
"{",
"$",
"activity",
"->",
"forceDelete",
"(",
")",
";",
"}",
"return",
"redirect",
"(",
"'activity'",
")",
"->",
"with",
"(",
"'success'",
",",
"trans",
"(",
"'LaravelLogger::laravel-logger.messages.logDestroyedSuccessfuly'",
")",
")",
";",
"}"
] | Destroy the specified resource from storage.
@param Request $request
@return \Illuminate\Http\Response | [
"Destroy",
"the",
"specified",
"resource",
"from",
"storage",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L236-L244 | train |
jeremykenedy/laravel-logger | src/app/Http/Controllers/LaravelLoggerController.php | LaravelLoggerController.restoreClearedActivityLog | public function restoreClearedActivityLog(Request $request)
{
$activities = Activity::onlyTrashed()->get();
foreach ($activities as $activity) {
$activity->restore();
}
return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly'));
} | php | public function restoreClearedActivityLog(Request $request)
{
$activities = Activity::onlyTrashed()->get();
foreach ($activities as $activity) {
$activity->restore();
}
return redirect('activity')->with('success', trans('LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly'));
} | [
"public",
"function",
"restoreClearedActivityLog",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"activities",
"=",
"Activity",
"::",
"onlyTrashed",
"(",
")",
"->",
"get",
"(",
")",
";",
"foreach",
"(",
"$",
"activities",
"as",
"$",
"activity",
")",
"{",
"$",
"activity",
"->",
"restore",
"(",
")",
";",
"}",
"return",
"redirect",
"(",
"'activity'",
")",
"->",
"with",
"(",
"'success'",
",",
"trans",
"(",
"'LaravelLogger::laravel-logger.messages.logRestoredSuccessfuly'",
")",
")",
";",
"}"
] | Restore the specified resource from soft deleted storage.
@param Request $request
@return \Illuminate\Http\Response | [
"Restore",
"the",
"specified",
"resource",
"from",
"soft",
"deleted",
"storage",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Controllers/LaravelLoggerController.php#L253-L261 | train |
jeremykenedy/laravel-logger | src/app/Http/Traits/UserAgentDetails.php | UserAgentDetails.details | public static function details($ua)
{
$ua = is_null($ua) ? $_SERVER['HTTP_USER_AGENT'] : $ua;
// Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..)
$platforms = 'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux';
// All browsers except MSIE/Trident and..
// NOT for browsers that use this syntax: Version/0.xx Browsername
$browsers = 'Firefox|Chrome|Opera';
// Specifically for browsers that use this syntax: Version/0.xx Browername
$browsers_v = 'Safari|Mobile'; // Mobile is mentioned in Android and BlackBerry UA's
// Fill in your most common engines..
$engines = 'Gecko|Trident|Webkit|Presto';
// Regex the crap out of the user agent, making multiple selections and..
$regex_pat = "/((Mozilla)\/[\d\.]+|(Opera)\/[\d\.]+)\s\(.*?((MSIE)\s([\d\.]+).*?(Windows)|({$platforms})).*?\s.*?({$engines})[\/\s]+[\d\.]+(\;\srv\:([\d\.]+)|.*?).*?(Version[\/\s]([\d\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\/\s]+([\d\.]+))|$).*/i";
// .. placing them in this order, delimited by |
$replace_pat = '$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}';
// Run the preg_replace .. and explode on |
$ua_array = explode('|', preg_replace($regex_pat, $replace_pat, $ua, PREG_PATTERN_ORDER));
if (count($ua_array) > 1) {
$return['platform'] = $ua_array[0]; // Windows / iPad / MacOS / BlackBerry
$return['type'] = $ua_array[1]; // Mozilla / Opera etc.
$return['renderer'] = $ua_array[2]; // WebKit / Presto / Trident / Gecko etc.
$return['browser'] = $ua_array[3]; // Chrome / Safari / MSIE / Firefox
/*
Not necessary but this will filter out Chromes ridiculously long version
numbers 31.0.1234.122 becomes 31.0, while a "normal" 3 digit version number
like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is.
*/
if (preg_match("/^[\d]+\.[\d]+(?:\.[\d]{0,2}$)?/", $ua_array[4], $matches)) {
$return['version'] = $matches[0];
} else {
$return['version'] = $ua_array[4];
}
} else {
return false;
}
// Replace some browsernames e.g. MSIE -> Internet Explorer
switch (strtolower($return['browser'])) {
case 'msie':
case 'trident':
$return['browser'] = 'Internet Explorer';
break;
case '': // IE 11 is a steamy turd (thanks Microsoft...)
if (strtolower($return['renderer']) == 'trident') {
$return['browser'] = 'Internet Explorer';
}
break;
}
switch (strtolower($return['platform'])) {
case 'android': // These browsers claim to be Safari but are BB Mobile
case 'blackberry': // and Android Mobile
if ($return['browser'] == 'Safari' || $return['browser'] == 'Mobile' || $return['browser'] == '') {
$return['browser'] = "{$return['platform']} mobile";
}
break;
}
return $return;
} | php | public static function details($ua)
{
$ua = is_null($ua) ? $_SERVER['HTTP_USER_AGENT'] : $ua;
// Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..)
$platforms = 'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux';
// All browsers except MSIE/Trident and..
// NOT for browsers that use this syntax: Version/0.xx Browsername
$browsers = 'Firefox|Chrome|Opera';
// Specifically for browsers that use this syntax: Version/0.xx Browername
$browsers_v = 'Safari|Mobile'; // Mobile is mentioned in Android and BlackBerry UA's
// Fill in your most common engines..
$engines = 'Gecko|Trident|Webkit|Presto';
// Regex the crap out of the user agent, making multiple selections and..
$regex_pat = "/((Mozilla)\/[\d\.]+|(Opera)\/[\d\.]+)\s\(.*?((MSIE)\s([\d\.]+).*?(Windows)|({$platforms})).*?\s.*?({$engines})[\/\s]+[\d\.]+(\;\srv\:([\d\.]+)|.*?).*?(Version[\/\s]([\d\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\/\s]+([\d\.]+))|$).*/i";
// .. placing them in this order, delimited by |
$replace_pat = '$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}';
// Run the preg_replace .. and explode on |
$ua_array = explode('|', preg_replace($regex_pat, $replace_pat, $ua, PREG_PATTERN_ORDER));
if (count($ua_array) > 1) {
$return['platform'] = $ua_array[0]; // Windows / iPad / MacOS / BlackBerry
$return['type'] = $ua_array[1]; // Mozilla / Opera etc.
$return['renderer'] = $ua_array[2]; // WebKit / Presto / Trident / Gecko etc.
$return['browser'] = $ua_array[3]; // Chrome / Safari / MSIE / Firefox
/*
Not necessary but this will filter out Chromes ridiculously long version
numbers 31.0.1234.122 becomes 31.0, while a "normal" 3 digit version number
like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is.
*/
if (preg_match("/^[\d]+\.[\d]+(?:\.[\d]{0,2}$)?/", $ua_array[4], $matches)) {
$return['version'] = $matches[0];
} else {
$return['version'] = $ua_array[4];
}
} else {
return false;
}
// Replace some browsernames e.g. MSIE -> Internet Explorer
switch (strtolower($return['browser'])) {
case 'msie':
case 'trident':
$return['browser'] = 'Internet Explorer';
break;
case '': // IE 11 is a steamy turd (thanks Microsoft...)
if (strtolower($return['renderer']) == 'trident') {
$return['browser'] = 'Internet Explorer';
}
break;
}
switch (strtolower($return['platform'])) {
case 'android': // These browsers claim to be Safari but are BB Mobile
case 'blackberry': // and Android Mobile
if ($return['browser'] == 'Safari' || $return['browser'] == 'Mobile' || $return['browser'] == '') {
$return['browser'] = "{$return['platform']} mobile";
}
break;
}
return $return;
} | [
"public",
"static",
"function",
"details",
"(",
"$",
"ua",
")",
"{",
"$",
"ua",
"=",
"is_null",
"(",
"$",
"ua",
")",
"?",
"$",
"_SERVER",
"[",
"'HTTP_USER_AGENT'",
"]",
":",
"$",
"ua",
";",
"// Enumerate all common platforms, this is usually placed in braces (order is important! First come first serve..)",
"$",
"platforms",
"=",
"'Windows|iPad|iPhone|Macintosh|Android|BlackBerry|Unix|Linux'",
";",
"// All browsers except MSIE/Trident and..",
"// NOT for browsers that use this syntax: Version/0.xx Browsername",
"$",
"browsers",
"=",
"'Firefox|Chrome|Opera'",
";",
"// Specifically for browsers that use this syntax: Version/0.xx Browername",
"$",
"browsers_v",
"=",
"'Safari|Mobile'",
";",
"// Mobile is mentioned in Android and BlackBerry UA's",
"// Fill in your most common engines..",
"$",
"engines",
"=",
"'Gecko|Trident|Webkit|Presto'",
";",
"// Regex the crap out of the user agent, making multiple selections and..",
"$",
"regex_pat",
"=",
"\"/((Mozilla)\\/[\\d\\.]+|(Opera)\\/[\\d\\.]+)\\s\\(.*?((MSIE)\\s([\\d\\.]+).*?(Windows)|({$platforms})).*?\\s.*?({$engines})[\\/\\s]+[\\d\\.]+(\\;\\srv\\:([\\d\\.]+)|.*?).*?(Version[\\/\\s]([\\d\\.]+)(.*?({$browsers_v})|$)|(({$browsers})[\\/\\s]+([\\d\\.]+))|$).*/i\"",
";",
"// .. placing them in this order, delimited by |",
"$",
"replace_pat",
"=",
"'$7$8|$2$3|$9|${17}${15}$5$3|${18}${13}$6${11}'",
";",
"// Run the preg_replace .. and explode on |",
"$",
"ua_array",
"=",
"explode",
"(",
"'|'",
",",
"preg_replace",
"(",
"$",
"regex_pat",
",",
"$",
"replace_pat",
",",
"$",
"ua",
",",
"PREG_PATTERN_ORDER",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"ua_array",
")",
">",
"1",
")",
"{",
"$",
"return",
"[",
"'platform'",
"]",
"=",
"$",
"ua_array",
"[",
"0",
"]",
";",
"// Windows / iPad / MacOS / BlackBerry",
"$",
"return",
"[",
"'type'",
"]",
"=",
"$",
"ua_array",
"[",
"1",
"]",
";",
"// Mozilla / Opera etc.",
"$",
"return",
"[",
"'renderer'",
"]",
"=",
"$",
"ua_array",
"[",
"2",
"]",
";",
"// WebKit / Presto / Trident / Gecko etc.",
"$",
"return",
"[",
"'browser'",
"]",
"=",
"$",
"ua_array",
"[",
"3",
"]",
";",
"// Chrome / Safari / MSIE / Firefox",
"/*\n Not necessary but this will filter out Chromes ridiculously long version\n numbers 31.0.1234.122 becomes 31.0, while a \"normal\" 3 digit version number\n like 10.2.1 would stay 10.2.1, 11.0 stays 11.0. Non-match stays what it is.\n */",
"if",
"(",
"preg_match",
"(",
"\"/^[\\d]+\\.[\\d]+(?:\\.[\\d]{0,2}$)?/\"",
",",
"$",
"ua_array",
"[",
"4",
"]",
",",
"$",
"matches",
")",
")",
"{",
"$",
"return",
"[",
"'version'",
"]",
"=",
"$",
"matches",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"$",
"return",
"[",
"'version'",
"]",
"=",
"$",
"ua_array",
"[",
"4",
"]",
";",
"}",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"// Replace some browsernames e.g. MSIE -> Internet Explorer",
"switch",
"(",
"strtolower",
"(",
"$",
"return",
"[",
"'browser'",
"]",
")",
")",
"{",
"case",
"'msie'",
":",
"case",
"'trident'",
":",
"$",
"return",
"[",
"'browser'",
"]",
"=",
"'Internet Explorer'",
";",
"break",
";",
"case",
"''",
":",
"// IE 11 is a steamy turd (thanks Microsoft...)",
"if",
"(",
"strtolower",
"(",
"$",
"return",
"[",
"'renderer'",
"]",
")",
"==",
"'trident'",
")",
"{",
"$",
"return",
"[",
"'browser'",
"]",
"=",
"'Internet Explorer'",
";",
"}",
"break",
";",
"}",
"switch",
"(",
"strtolower",
"(",
"$",
"return",
"[",
"'platform'",
"]",
")",
")",
"{",
"case",
"'android'",
":",
"// These browsers claim to be Safari but are BB Mobile",
"case",
"'blackberry'",
":",
"// and Android Mobile",
"if",
"(",
"$",
"return",
"[",
"'browser'",
"]",
"==",
"'Safari'",
"||",
"$",
"return",
"[",
"'browser'",
"]",
"==",
"'Mobile'",
"||",
"$",
"return",
"[",
"'browser'",
"]",
"==",
"''",
")",
"{",
"$",
"return",
"[",
"'browser'",
"]",
"=",
"\"{$return['platform']} mobile\"",
";",
"}",
"break",
";",
"}",
"return",
"$",
"return",
";",
"}"
] | Get the user's agents details.
@param $ua
@return array | [
"Get",
"the",
"user",
"s",
"agents",
"details",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/UserAgentDetails.php#L14-L82 | train |
jeremykenedy/laravel-logger | src/app/Http/Traits/ActivityLogger.php | ActivityLogger.activity | public static function activity($description = null)
{
$userType = trans('LaravelLogger::laravel-logger.userTypes.guest');
$userId = null;
if (\Auth::check()) {
$userType = trans('LaravelLogger::laravel-logger.userTypes.registered');
$userId = \Request::user()->id;
}
if (Crawler::isCrawler()) {
$userType = trans('LaravelLogger::laravel-logger.userTypes.crawler');
$description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.\Request::fullUrl();
}
if (!$description) {
switch (strtolower(\Request::method())) {
case 'post':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.created');
break;
case 'patch':
case 'put':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.edited');
break;
case 'delete':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted');
break;
case 'get':
default:
$verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed');
break;
}
$description = $verb.' '.\Request::path();
}
$data = [
'description' => $description,
'userType' => $userType,
'userId' => $userId,
'route' => \Request::fullUrl(),
'ipAddress' => \Request::ip(),
'userAgent' => \Request::header('user-agent'),
'locale' => \Request::header('accept-language'),
'referer' => \Request::header('referer'),
'methodType' => \Request::method(),
];
// Validation Instance
$validator = Validator::make($data, Activity::Rules([]));
if ($validator->fails()) {
$errors = self::prepareErrorMessage($validator->errors(), $data);
if (config('LaravelLogger.logDBActivityLogFailuresToFile')) {
Log::error('Failed to record activity event. Failed Validation: '.$errors);
}
} else {
self::storeActivity($data);
}
} | php | public static function activity($description = null)
{
$userType = trans('LaravelLogger::laravel-logger.userTypes.guest');
$userId = null;
if (\Auth::check()) {
$userType = trans('LaravelLogger::laravel-logger.userTypes.registered');
$userId = \Request::user()->id;
}
if (Crawler::isCrawler()) {
$userType = trans('LaravelLogger::laravel-logger.userTypes.crawler');
$description = $userType.' '.trans('LaravelLogger::laravel-logger.verbTypes.crawled').' '.\Request::fullUrl();
}
if (!$description) {
switch (strtolower(\Request::method())) {
case 'post':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.created');
break;
case 'patch':
case 'put':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.edited');
break;
case 'delete':
$verb = trans('LaravelLogger::laravel-logger.verbTypes.deleted');
break;
case 'get':
default:
$verb = trans('LaravelLogger::laravel-logger.verbTypes.viewed');
break;
}
$description = $verb.' '.\Request::path();
}
$data = [
'description' => $description,
'userType' => $userType,
'userId' => $userId,
'route' => \Request::fullUrl(),
'ipAddress' => \Request::ip(),
'userAgent' => \Request::header('user-agent'),
'locale' => \Request::header('accept-language'),
'referer' => \Request::header('referer'),
'methodType' => \Request::method(),
];
// Validation Instance
$validator = Validator::make($data, Activity::Rules([]));
if ($validator->fails()) {
$errors = self::prepareErrorMessage($validator->errors(), $data);
if (config('LaravelLogger.logDBActivityLogFailuresToFile')) {
Log::error('Failed to record activity event. Failed Validation: '.$errors);
}
} else {
self::storeActivity($data);
}
} | [
"public",
"static",
"function",
"activity",
"(",
"$",
"description",
"=",
"null",
")",
"{",
"$",
"userType",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.userTypes.guest'",
")",
";",
"$",
"userId",
"=",
"null",
";",
"if",
"(",
"\\",
"Auth",
"::",
"check",
"(",
")",
")",
"{",
"$",
"userType",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.userTypes.registered'",
")",
";",
"$",
"userId",
"=",
"\\",
"Request",
"::",
"user",
"(",
")",
"->",
"id",
";",
"}",
"if",
"(",
"Crawler",
"::",
"isCrawler",
"(",
")",
")",
"{",
"$",
"userType",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.userTypes.crawler'",
")",
";",
"$",
"description",
"=",
"$",
"userType",
".",
"' '",
".",
"trans",
"(",
"'LaravelLogger::laravel-logger.verbTypes.crawled'",
")",
".",
"' '",
".",
"\\",
"Request",
"::",
"fullUrl",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"description",
")",
"{",
"switch",
"(",
"strtolower",
"(",
"\\",
"Request",
"::",
"method",
"(",
")",
")",
")",
"{",
"case",
"'post'",
":",
"$",
"verb",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.verbTypes.created'",
")",
";",
"break",
";",
"case",
"'patch'",
":",
"case",
"'put'",
":",
"$",
"verb",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.verbTypes.edited'",
")",
";",
"break",
";",
"case",
"'delete'",
":",
"$",
"verb",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.verbTypes.deleted'",
")",
";",
"break",
";",
"case",
"'get'",
":",
"default",
":",
"$",
"verb",
"=",
"trans",
"(",
"'LaravelLogger::laravel-logger.verbTypes.viewed'",
")",
";",
"break",
";",
"}",
"$",
"description",
"=",
"$",
"verb",
".",
"' '",
".",
"\\",
"Request",
"::",
"path",
"(",
")",
";",
"}",
"$",
"data",
"=",
"[",
"'description'",
"=>",
"$",
"description",
",",
"'userType'",
"=>",
"$",
"userType",
",",
"'userId'",
"=>",
"$",
"userId",
",",
"'route'",
"=>",
"\\",
"Request",
"::",
"fullUrl",
"(",
")",
",",
"'ipAddress'",
"=>",
"\\",
"Request",
"::",
"ip",
"(",
")",
",",
"'userAgent'",
"=>",
"\\",
"Request",
"::",
"header",
"(",
"'user-agent'",
")",
",",
"'locale'",
"=>",
"\\",
"Request",
"::",
"header",
"(",
"'accept-language'",
")",
",",
"'referer'",
"=>",
"\\",
"Request",
"::",
"header",
"(",
"'referer'",
")",
",",
"'methodType'",
"=>",
"\\",
"Request",
"::",
"method",
"(",
")",
",",
"]",
";",
"// Validation Instance",
"$",
"validator",
"=",
"Validator",
"::",
"make",
"(",
"$",
"data",
",",
"Activity",
"::",
"Rules",
"(",
"[",
"]",
")",
")",
";",
"if",
"(",
"$",
"validator",
"->",
"fails",
"(",
")",
")",
"{",
"$",
"errors",
"=",
"self",
"::",
"prepareErrorMessage",
"(",
"$",
"validator",
"->",
"errors",
"(",
")",
",",
"$",
"data",
")",
";",
"if",
"(",
"config",
"(",
"'LaravelLogger.logDBActivityLogFailuresToFile'",
")",
")",
"{",
"Log",
"::",
"error",
"(",
"'Failed to record activity event. Failed Validation: '",
".",
"$",
"errors",
")",
";",
"}",
"}",
"else",
"{",
"self",
"::",
"storeActivity",
"(",
"$",
"data",
")",
";",
"}",
"}"
] | Laravel Logger Log Activity.
@param string $description
@return void | [
"Laravel",
"Logger",
"Log",
"Activity",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/ActivityLogger.php#L19-L80 | train |
jeremykenedy/laravel-logger | src/app/Http/Traits/ActivityLogger.php | ActivityLogger.storeActivity | private static function storeActivity($data)
{
Activity::create([
'description' => $data['description'],
'userType' => $data['userType'],
'userId' => $data['userId'],
'route' => $data['route'],
'ipAddress' => $data['ipAddress'],
'userAgent' => $data['userAgent'],
'locale' => $data['locale'],
'referer' => $data['referer'],
'methodType' => $data['methodType'],
]);
} | php | private static function storeActivity($data)
{
Activity::create([
'description' => $data['description'],
'userType' => $data['userType'],
'userId' => $data['userId'],
'route' => $data['route'],
'ipAddress' => $data['ipAddress'],
'userAgent' => $data['userAgent'],
'locale' => $data['locale'],
'referer' => $data['referer'],
'methodType' => $data['methodType'],
]);
} | [
"private",
"static",
"function",
"storeActivity",
"(",
"$",
"data",
")",
"{",
"Activity",
"::",
"create",
"(",
"[",
"'description'",
"=>",
"$",
"data",
"[",
"'description'",
"]",
",",
"'userType'",
"=>",
"$",
"data",
"[",
"'userType'",
"]",
",",
"'userId'",
"=>",
"$",
"data",
"[",
"'userId'",
"]",
",",
"'route'",
"=>",
"$",
"data",
"[",
"'route'",
"]",
",",
"'ipAddress'",
"=>",
"$",
"data",
"[",
"'ipAddress'",
"]",
",",
"'userAgent'",
"=>",
"$",
"data",
"[",
"'userAgent'",
"]",
",",
"'locale'",
"=>",
"$",
"data",
"[",
"'locale'",
"]",
",",
"'referer'",
"=>",
"$",
"data",
"[",
"'referer'",
"]",
",",
"'methodType'",
"=>",
"$",
"data",
"[",
"'methodType'",
"]",
",",
"]",
")",
";",
"}"
] | Store activity entry to database.
@param array $data
@return void | [
"Store",
"activity",
"entry",
"to",
"database",
"."
] | 16f0cbbe281544598e10e807703ff2e60d998772 | https://github.com/jeremykenedy/laravel-logger/blob/16f0cbbe281544598e10e807703ff2e60d998772/src/app/Http/Traits/ActivityLogger.php#L89-L102 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.withRules | public function withRules(array $rules): self
{
$new = clone $this;
/* Clear the stack */
unset($new->rules);
$new->rules = new \SplStack;
/* Add the rules */
foreach ($rules as $callable) {
$new = $new->addRule($callable);
}
return $new;
} | php | public function withRules(array $rules): self
{
$new = clone $this;
/* Clear the stack */
unset($new->rules);
$new->rules = new \SplStack;
/* Add the rules */
foreach ($rules as $callable) {
$new = $new->addRule($callable);
}
return $new;
} | [
"public",
"function",
"withRules",
"(",
"array",
"$",
"rules",
")",
":",
"self",
"{",
"$",
"new",
"=",
"clone",
"$",
"this",
";",
"/* Clear the stack */",
"unset",
"(",
"$",
"new",
"->",
"rules",
")",
";",
"$",
"new",
"->",
"rules",
"=",
"new",
"\\",
"SplStack",
";",
"/* Add the rules */",
"foreach",
"(",
"$",
"rules",
"as",
"$",
"callable",
")",
"{",
"$",
"new",
"=",
"$",
"new",
"->",
"addRule",
"(",
"$",
"callable",
")",
";",
"}",
"return",
"$",
"new",
";",
"}"
] | Set all rules in the stack. | [
"Set",
"all",
"rules",
"in",
"the",
"stack",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L182-L193 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.shouldAuthenticate | private function shouldAuthenticate(ServerRequestInterface $request): bool
{
/* If any of the rules in stack return false will not authenticate */
foreach ($this->rules as $callable) {
if (false === $callable($request)) {
return false;
}
}
return true;
} | php | private function shouldAuthenticate(ServerRequestInterface $request): bool
{
/* If any of the rules in stack return false will not authenticate */
foreach ($this->rules as $callable) {
if (false === $callable($request)) {
return false;
}
}
return true;
} | [
"private",
"function",
"shouldAuthenticate",
"(",
"ServerRequestInterface",
"$",
"request",
")",
":",
"bool",
"{",
"/* If any of the rules in stack return false will not authenticate */",
"foreach",
"(",
"$",
"this",
"->",
"rules",
"as",
"$",
"callable",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"callable",
"(",
"$",
"request",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Check if middleware should authenticate. | [
"Check",
"if",
"middleware",
"should",
"authenticate",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L209-L218 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.fetchToken | private function fetchToken(ServerRequestInterface $request): string
{
/* Check for token in header. */
$header = $request->getHeaderLine($this->options["header"]);
if (false === empty($header)) {
if (preg_match($this->options["regexp"], $header, $matches)) {
$this->log(LogLevel::DEBUG, "Using token from request header");
return $matches[1];
}
}
/* Token not found in header try a cookie. */
$cookieParams = $request->getCookieParams();
if (isset($cookieParams[$this->options["cookie"]])) {
$this->log(LogLevel::DEBUG, "Using token from cookie");
return $cookieParams[$this->options["cookie"]];
};
/* If everything fails log and throw. */
$this->log(LogLevel::WARNING, "Token not found");
throw new RuntimeException("Token not found.");
} | php | private function fetchToken(ServerRequestInterface $request): string
{
/* Check for token in header. */
$header = $request->getHeaderLine($this->options["header"]);
if (false === empty($header)) {
if (preg_match($this->options["regexp"], $header, $matches)) {
$this->log(LogLevel::DEBUG, "Using token from request header");
return $matches[1];
}
}
/* Token not found in header try a cookie. */
$cookieParams = $request->getCookieParams();
if (isset($cookieParams[$this->options["cookie"]])) {
$this->log(LogLevel::DEBUG, "Using token from cookie");
return $cookieParams[$this->options["cookie"]];
};
/* If everything fails log and throw. */
$this->log(LogLevel::WARNING, "Token not found");
throw new RuntimeException("Token not found.");
} | [
"private",
"function",
"fetchToken",
"(",
"ServerRequestInterface",
"$",
"request",
")",
":",
"string",
"{",
"/* Check for token in header. */",
"$",
"header",
"=",
"$",
"request",
"->",
"getHeaderLine",
"(",
"$",
"this",
"->",
"options",
"[",
"\"header\"",
"]",
")",
";",
"if",
"(",
"false",
"===",
"empty",
"(",
"$",
"header",
")",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"this",
"->",
"options",
"[",
"\"regexp\"",
"]",
",",
"$",
"header",
",",
"$",
"matches",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"DEBUG",
",",
"\"Using token from request header\"",
")",
";",
"return",
"$",
"matches",
"[",
"1",
"]",
";",
"}",
"}",
"/* Token not found in header try a cookie. */",
"$",
"cookieParams",
"=",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"cookieParams",
"[",
"$",
"this",
"->",
"options",
"[",
"\"cookie\"",
"]",
"]",
")",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"DEBUG",
",",
"\"Using token from cookie\"",
")",
";",
"return",
"$",
"cookieParams",
"[",
"$",
"this",
"->",
"options",
"[",
"\"cookie\"",
"]",
"]",
";",
"}",
";",
"/* If everything fails log and throw. */",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"WARNING",
",",
"\"Token not found\"",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"\"Token not found.\"",
")",
";",
"}"
] | Fetch the access token. | [
"Fetch",
"the",
"access",
"token",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L237-L260 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.decodeToken | private function decodeToken(string $token): array
{
try {
$decoded = JWT::decode(
$token,
$this->options["secret"],
(array) $this->options["algorithm"]
);
return (array) $decoded;
} catch (Exception $exception) {
$this->log(LogLevel::WARNING, $exception->getMessage(), [$token]);
throw $exception;
}
} | php | private function decodeToken(string $token): array
{
try {
$decoded = JWT::decode(
$token,
$this->options["secret"],
(array) $this->options["algorithm"]
);
return (array) $decoded;
} catch (Exception $exception) {
$this->log(LogLevel::WARNING, $exception->getMessage(), [$token]);
throw $exception;
}
} | [
"private",
"function",
"decodeToken",
"(",
"string",
"$",
"token",
")",
":",
"array",
"{",
"try",
"{",
"$",
"decoded",
"=",
"JWT",
"::",
"decode",
"(",
"$",
"token",
",",
"$",
"this",
"->",
"options",
"[",
"\"secret\"",
"]",
",",
"(",
"array",
")",
"$",
"this",
"->",
"options",
"[",
"\"algorithm\"",
"]",
")",
";",
"return",
"(",
"array",
")",
"$",
"decoded",
";",
"}",
"catch",
"(",
"Exception",
"$",
"exception",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"WARNING",
",",
"$",
"exception",
"->",
"getMessage",
"(",
")",
",",
"[",
"$",
"token",
"]",
")",
";",
"throw",
"$",
"exception",
";",
"}",
"}"
] | Decode the token. | [
"Decode",
"the",
"token",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L265-L278 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.secret | private function secret($secret): void
{
if (false === is_array($secret) && false === is_string($secret)) {
throw new InvalidArgumentException(
'Secret must be either a string or an array of "kid" => "secret" pairs'
);
}
$this->options["secret"] = $secret;
} | php | private function secret($secret): void
{
if (false === is_array($secret) && false === is_string($secret)) {
throw new InvalidArgumentException(
'Secret must be either a string or an array of "kid" => "secret" pairs'
);
}
$this->options["secret"] = $secret;
} | [
"private",
"function",
"secret",
"(",
"$",
"secret",
")",
":",
"void",
"{",
"if",
"(",
"false",
"===",
"is_array",
"(",
"$",
"secret",
")",
"&&",
"false",
"===",
"is_string",
"(",
"$",
"secret",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Secret must be either a string or an array of \"kid\" => \"secret\" pairs'",
")",
";",
"}",
"$",
"this",
"->",
"options",
"[",
"\"secret\"",
"]",
"=",
"$",
"secret",
";",
"}"
] | Set the secret key. | [
"Set",
"the",
"secret",
"key",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L343-L351 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.error | private function error(callable $error): void
{
if ($error instanceof Closure) {
$this->options["error"] = $error->bindTo($this);
} else {
$this->options["error"] = $error;
}
} | php | private function error(callable $error): void
{
if ($error instanceof Closure) {
$this->options["error"] = $error->bindTo($this);
} else {
$this->options["error"] = $error;
}
} | [
"private",
"function",
"error",
"(",
"callable",
"$",
"error",
")",
":",
"void",
"{",
"if",
"(",
"$",
"error",
"instanceof",
"Closure",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"\"error\"",
"]",
"=",
"$",
"error",
"->",
"bindTo",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"options",
"[",
"\"error\"",
"]",
"=",
"$",
"error",
";",
"}",
"}"
] | Set the error handler. | [
"Set",
"the",
"error",
"handler",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L356-L363 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.before | private function before(callable $before): void
{
if ($before instanceof Closure) {
$this->options["before"] = $before->bindTo($this);
} else {
$this->options["before"] = $before;
}
} | php | private function before(callable $before): void
{
if ($before instanceof Closure) {
$this->options["before"] = $before->bindTo($this);
} else {
$this->options["before"] = $before;
}
} | [
"private",
"function",
"before",
"(",
"callable",
"$",
"before",
")",
":",
"void",
"{",
"if",
"(",
"$",
"before",
"instanceof",
"Closure",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"\"before\"",
"]",
"=",
"$",
"before",
"->",
"bindTo",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"options",
"[",
"\"before\"",
"]",
"=",
"$",
"before",
";",
"}",
"}"
] | Set the before handler. | [
"Set",
"the",
"before",
"handler",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L419-L426 | train |
tuupola/slim-jwt-auth | src/JwtAuthentication.php | JwtAuthentication.after | private function after(callable $after): void
{
if ($after instanceof Closure) {
$this->options["after"] = $after->bindTo($this);
} else {
$this->options["after"] = $after;
}
} | php | private function after(callable $after): void
{
if ($after instanceof Closure) {
$this->options["after"] = $after->bindTo($this);
} else {
$this->options["after"] = $after;
}
} | [
"private",
"function",
"after",
"(",
"callable",
"$",
"after",
")",
":",
"void",
"{",
"if",
"(",
"$",
"after",
"instanceof",
"Closure",
")",
"{",
"$",
"this",
"->",
"options",
"[",
"\"after\"",
"]",
"=",
"$",
"after",
"->",
"bindTo",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"options",
"[",
"\"after\"",
"]",
"=",
"$",
"after",
";",
"}",
"}"
] | Set the after handler. | [
"Set",
"the",
"after",
"handler",
"."
] | 70416d5d32fd584a335fe1ce882a65af2eea2592 | https://github.com/tuupola/slim-jwt-auth/blob/70416d5d32fd584a335fe1ce882a65af2eea2592/src/JwtAuthentication.php#L431-L438 | train |
Imangazaliev/DiDOM | src/DiDom/Errors.php | Errors.restore | public static function restore($clear = true)
{
if ($clear) {
libxml_clear_errors();
}
libxml_use_internal_errors(self::$internalErrors);
libxml_disable_entity_loader(self::$disableEntities);
} | php | public static function restore($clear = true)
{
if ($clear) {
libxml_clear_errors();
}
libxml_use_internal_errors(self::$internalErrors);
libxml_disable_entity_loader(self::$disableEntities);
} | [
"public",
"static",
"function",
"restore",
"(",
"$",
"clear",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"clear",
")",
"{",
"libxml_clear_errors",
"(",
")",
";",
"}",
"libxml_use_internal_errors",
"(",
"self",
"::",
"$",
"internalErrors",
")",
";",
"libxml_disable_entity_loader",
"(",
"self",
"::",
"$",
"disableEntities",
")",
";",
"}"
] | Restore error reporting.
@param bool $clear | [
"Restore",
"error",
"reporting",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Errors.php#L31-L39 | train |
Imangazaliev/DiDOM | src/DiDom/StyleAttribute.php | StyleAttribute.parseStyleAttribute | protected function parseStyleAttribute()
{
if (!$this->element->hasAttribute('style')) {
// possible if style attribute has been removed
if ($this->styleString !== '') {
$this->styleString = '';
$this->properties = [];
}
return;
}
// if style attribute is not changed
if ($this->element->getAttribute('style') === $this->styleString) {
return;
}
// save style attribute as is (without trimming)
$this->styleString = $this->element->getAttribute('style');
$styleString = trim($this->styleString, ' ;');
if ($styleString === '') {
$this->properties = [];
return;
}
$properties = explode(';', $styleString);
foreach ($properties as $property) {
list($name, $value) = explode(':', $property);
$name = trim($name);
$value = trim($value);
$this->properties[$name] = $value;
}
} | php | protected function parseStyleAttribute()
{
if (!$this->element->hasAttribute('style')) {
// possible if style attribute has been removed
if ($this->styleString !== '') {
$this->styleString = '';
$this->properties = [];
}
return;
}
// if style attribute is not changed
if ($this->element->getAttribute('style') === $this->styleString) {
return;
}
// save style attribute as is (without trimming)
$this->styleString = $this->element->getAttribute('style');
$styleString = trim($this->styleString, ' ;');
if ($styleString === '') {
$this->properties = [];
return;
}
$properties = explode(';', $styleString);
foreach ($properties as $property) {
list($name, $value) = explode(':', $property);
$name = trim($name);
$value = trim($value);
$this->properties[$name] = $value;
}
} | [
"protected",
"function",
"parseStyleAttribute",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"element",
"->",
"hasAttribute",
"(",
"'style'",
")",
")",
"{",
"// possible if style attribute has been removed",
"if",
"(",
"$",
"this",
"->",
"styleString",
"!==",
"''",
")",
"{",
"$",
"this",
"->",
"styleString",
"=",
"''",
";",
"$",
"this",
"->",
"properties",
"=",
"[",
"]",
";",
"}",
"return",
";",
"}",
"// if style attribute is not changed",
"if",
"(",
"$",
"this",
"->",
"element",
"->",
"getAttribute",
"(",
"'style'",
")",
"===",
"$",
"this",
"->",
"styleString",
")",
"{",
"return",
";",
"}",
"// save style attribute as is (without trimming)",
"$",
"this",
"->",
"styleString",
"=",
"$",
"this",
"->",
"element",
"->",
"getAttribute",
"(",
"'style'",
")",
";",
"$",
"styleString",
"=",
"trim",
"(",
"$",
"this",
"->",
"styleString",
",",
"' ;'",
")",
";",
"if",
"(",
"$",
"styleString",
"===",
"''",
")",
"{",
"$",
"this",
"->",
"properties",
"=",
"[",
"]",
";",
"return",
";",
"}",
"$",
"properties",
"=",
"explode",
"(",
"';'",
",",
"$",
"styleString",
")",
";",
"foreach",
"(",
"$",
"properties",
"as",
"$",
"property",
")",
"{",
"list",
"(",
"$",
"name",
",",
"$",
"value",
")",
"=",
"explode",
"(",
"':'",
",",
"$",
"property",
")",
";",
"$",
"name",
"=",
"trim",
"(",
"$",
"name",
")",
";",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"$",
"this",
"->",
"properties",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"}"
] | Parses style attribute of the element. | [
"Parses",
"style",
"attribute",
"of",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L47-L85 | train |
Imangazaliev/DiDOM | src/DiDom/StyleAttribute.php | StyleAttribute.updateStyleAttribute | protected function updateStyleAttribute()
{
$this->styleString = $this->buildStyleString();
$this->element->setAttribute('style', $this->styleString);
} | php | protected function updateStyleAttribute()
{
$this->styleString = $this->buildStyleString();
$this->element->setAttribute('style', $this->styleString);
} | [
"protected",
"function",
"updateStyleAttribute",
"(",
")",
"{",
"$",
"this",
"->",
"styleString",
"=",
"$",
"this",
"->",
"buildStyleString",
"(",
")",
";",
"$",
"this",
"->",
"element",
"->",
"setAttribute",
"(",
"'style'",
",",
"$",
"this",
"->",
"styleString",
")",
";",
"}"
] | Updates style attribute of the element. | [
"Updates",
"style",
"attribute",
"of",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/StyleAttribute.php#L90-L95 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.prependChild | public function prependChild($nodes)
{
if ($this->node->ownerDocument === null) {
throw new LogicException('Can not prepend child to element without owner document');
}
$returnArray = true;
if (!is_array($nodes)) {
$nodes = [$nodes];
$returnArray = false;
}
$nodes = array_reverse($nodes);
$result = [];
$referenceNode = $this->node->firstChild;
foreach ($nodes as $node) {
$result[] = $this->insertBefore($node, $referenceNode);
$referenceNode = $this->node->firstChild;
}
return $returnArray ? $result : $result[0];
} | php | public function prependChild($nodes)
{
if ($this->node->ownerDocument === null) {
throw new LogicException('Can not prepend child to element without owner document');
}
$returnArray = true;
if (!is_array($nodes)) {
$nodes = [$nodes];
$returnArray = false;
}
$nodes = array_reverse($nodes);
$result = [];
$referenceNode = $this->node->firstChild;
foreach ($nodes as $node) {
$result[] = $this->insertBefore($node, $referenceNode);
$referenceNode = $this->node->firstChild;
}
return $returnArray ? $result : $result[0];
} | [
"public",
"function",
"prependChild",
"(",
"$",
"nodes",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not prepend child to element without owner document'",
")",
";",
"}",
"$",
"returnArray",
"=",
"true",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"nodes",
")",
")",
"{",
"$",
"nodes",
"=",
"[",
"$",
"nodes",
"]",
";",
"$",
"returnArray",
"=",
"false",
";",
"}",
"$",
"nodes",
"=",
"array_reverse",
"(",
"$",
"nodes",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"referenceNode",
"=",
"$",
"this",
"->",
"node",
"->",
"firstChild",
";",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"this",
"->",
"insertBefore",
"(",
"$",
"node",
",",
"$",
"referenceNode",
")",
";",
"$",
"referenceNode",
"=",
"$",
"this",
"->",
"node",
"->",
"firstChild",
";",
"}",
"return",
"$",
"returnArray",
"?",
"$",
"result",
":",
"$",
"result",
"[",
"0",
"]",
";",
"}"
] | Adds a new child at the start of the children.
@param \DiDom\Element|\DOMNode|array $nodes The prepended child
@return \DiDom\Element|\DiDom\Element[]
@throws \LogicException if current node has no owner document
@throws \InvalidArgumentException if the provided argument is not an instance of \DOMNode or \DiDom\Element | [
"Adds",
"a",
"new",
"child",
"at",
"the",
"start",
"of",
"the",
"children",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L103-L130 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.insertBefore | public function insertBefore($node, $referenceNode = null)
{
if ($this->node->ownerDocument === null) {
throw new LogicException('Can not insert child to element without owner document');
}
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node))));
}
if ($referenceNode !== null) {
if ($referenceNode instanceof Element) {
$referenceNode = $referenceNode->getNode();
}
if (!$referenceNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode))));
}
}
Errors::disable();
$clonedNode = $node->cloneNode(true);
$newNode = $this->node->ownerDocument->importNode($clonedNode, true);
$insertedNode = $this->node->insertBefore($newNode, $referenceNode);
Errors::restore();
return new Element($insertedNode);
} | php | public function insertBefore($node, $referenceNode = null)
{
if ($this->node->ownerDocument === null) {
throw new LogicException('Can not insert child to element without owner document');
}
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node))));
}
if ($referenceNode !== null) {
if ($referenceNode instanceof Element) {
$referenceNode = $referenceNode->getNode();
}
if (!$referenceNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode))));
}
}
Errors::disable();
$clonedNode = $node->cloneNode(true);
$newNode = $this->node->ownerDocument->importNode($clonedNode, true);
$insertedNode = $this->node->insertBefore($newNode, $referenceNode);
Errors::restore();
return new Element($insertedNode);
} | [
"public",
"function",
"insertBefore",
"(",
"$",
"node",
",",
"$",
"referenceNode",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not insert child to element without owner document'",
")",
";",
"}",
"if",
"(",
"$",
"node",
"instanceof",
"Element",
")",
"{",
"$",
"node",
"=",
"$",
"node",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"node",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s\\Element or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__NAMESPACE__",
",",
"(",
"is_object",
"(",
"$",
"node",
")",
"?",
"get_class",
"(",
"$",
"node",
")",
":",
"gettype",
"(",
"$",
"node",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"referenceNode",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"referenceNode",
"instanceof",
"Element",
")",
"{",
"$",
"referenceNode",
"=",
"$",
"referenceNode",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"referenceNode",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 2 passed to %s must be an instance of %s\\Element or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__NAMESPACE__",
",",
"(",
"is_object",
"(",
"$",
"referenceNode",
")",
"?",
"get_class",
"(",
"$",
"referenceNode",
")",
":",
"gettype",
"(",
"$",
"referenceNode",
")",
")",
")",
")",
";",
"}",
"}",
"Errors",
"::",
"disable",
"(",
")",
";",
"$",
"clonedNode",
"=",
"$",
"node",
"->",
"cloneNode",
"(",
"true",
")",
";",
"$",
"newNode",
"=",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"->",
"importNode",
"(",
"$",
"clonedNode",
",",
"true",
")",
";",
"$",
"insertedNode",
"=",
"$",
"this",
"->",
"node",
"->",
"insertBefore",
"(",
"$",
"newNode",
",",
"$",
"referenceNode",
")",
";",
"Errors",
"::",
"restore",
"(",
")",
";",
"return",
"new",
"Element",
"(",
"$",
"insertedNode",
")",
";",
"}"
] | Adds a new child before a reference node.
@param \DiDom\Element|\DOMNode $node The new node
@param \DiDom\Element|\DOMNode|null $referenceNode The reference node
@return \DiDom\Element
@throws \LogicException if current node has no owner document
@throws \InvalidArgumentException if $node is not an instance of \DOMNode or \DiDom\Element
@throws \InvalidArgumentException if $referenceNode is not an instance of \DOMNode or \DiDom\Element | [
"Adds",
"a",
"new",
"child",
"before",
"a",
"reference",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L196-L230 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.insertAfter | public function insertAfter($node, $referenceNode = null)
{
if ($referenceNode === null) {
return $this->insertBefore($node);
}
if ($referenceNode instanceof Element) {
$referenceNode = $referenceNode->getNode();
}
if (!$referenceNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode))));
}
return $this->insertBefore($node, $referenceNode->nextSibling);
} | php | public function insertAfter($node, $referenceNode = null)
{
if ($referenceNode === null) {
return $this->insertBefore($node);
}
if ($referenceNode instanceof Element) {
$referenceNode = $referenceNode->getNode();
}
if (!$referenceNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 2 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($referenceNode) ? get_class($referenceNode) : gettype($referenceNode))));
}
return $this->insertBefore($node, $referenceNode->nextSibling);
} | [
"public",
"function",
"insertAfter",
"(",
"$",
"node",
",",
"$",
"referenceNode",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"referenceNode",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"insertBefore",
"(",
"$",
"node",
")",
";",
"}",
"if",
"(",
"$",
"referenceNode",
"instanceof",
"Element",
")",
"{",
"$",
"referenceNode",
"=",
"$",
"referenceNode",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"referenceNode",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 2 passed to %s must be an instance of %s\\Element or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__NAMESPACE__",
",",
"(",
"is_object",
"(",
"$",
"referenceNode",
")",
"?",
"get_class",
"(",
"$",
"referenceNode",
")",
":",
"gettype",
"(",
"$",
"referenceNode",
")",
")",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"insertBefore",
"(",
"$",
"node",
",",
"$",
"referenceNode",
"->",
"nextSibling",
")",
";",
"}"
] | Adds a new child after a reference node.
@param \DiDom\Element|\DOMNode $node The new node
@param \DiDom\Element|\DOMNode|null $referenceNode The reference node
@return \DiDom\Element
@throws \LogicException if current node has no owner document
@throws \InvalidArgumentException if $node is not an instance of \DOMNode or \DiDom\Element
@throws \InvalidArgumentException if $referenceNode is not an instance of \DOMNode or \DiDom\Element | [
"Adds",
"a",
"new",
"child",
"after",
"a",
"reference",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L244-L259 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.findInDocument | public function findInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true)
{
$ownerDocument = $this->getDocument();
if ($ownerDocument === null) {
throw new LogicException('Can not search in context without owner document');
}
return $ownerDocument->find($expression, $type, $wrapNode, $this->node);
} | php | public function findInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true)
{
$ownerDocument = $this->getDocument();
if ($ownerDocument === null) {
throw new LogicException('Can not search in context without owner document');
}
return $ownerDocument->find($expression, $type, $wrapNode, $this->node);
} | [
"public",
"function",
"findInDocument",
"(",
"$",
"expression",
",",
"$",
"type",
"=",
"Query",
"::",
"TYPE_CSS",
",",
"$",
"wrapNode",
"=",
"true",
")",
"{",
"$",
"ownerDocument",
"=",
"$",
"this",
"->",
"getDocument",
"(",
")",
";",
"if",
"(",
"$",
"ownerDocument",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not search in context without owner document'",
")",
";",
"}",
"return",
"$",
"ownerDocument",
"->",
"find",
"(",
"$",
"expression",
",",
"$",
"type",
",",
"$",
"wrapNode",
",",
"$",
"this",
"->",
"node",
")",
";",
"}"
] | Searches for an node in the owner document using current node as context.
@param string $expression XPath expression or a CSS selector
@param string $type The type of the expression
@param bool $wrapNode Returns array of \DiDom\Element if true, otherwise array of \DOMElement
@return \DiDom\Element[]|\DOMElement[]
@throws \LogicException if current node has no owner document | [
"Searches",
"for",
"an",
"node",
"in",
"the",
"owner",
"document",
"using",
"current",
"node",
"as",
"context",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L299-L308 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.firstInDocument | public function firstInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true)
{
$ownerDocument = $this->getDocument();
if ($ownerDocument === null) {
throw new LogicException('Can not search in context without owner document');
}
return $ownerDocument->first($expression, $type, $wrapNode, $this->node);
} | php | public function firstInDocument($expression, $type = Query::TYPE_CSS, $wrapNode = true)
{
$ownerDocument = $this->getDocument();
if ($ownerDocument === null) {
throw new LogicException('Can not search in context without owner document');
}
return $ownerDocument->first($expression, $type, $wrapNode, $this->node);
} | [
"public",
"function",
"firstInDocument",
"(",
"$",
"expression",
",",
"$",
"type",
"=",
"Query",
"::",
"TYPE_CSS",
",",
"$",
"wrapNode",
"=",
"true",
")",
"{",
"$",
"ownerDocument",
"=",
"$",
"this",
"->",
"getDocument",
"(",
")",
";",
"if",
"(",
"$",
"ownerDocument",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not search in context without owner document'",
")",
";",
"}",
"return",
"$",
"ownerDocument",
"->",
"first",
"(",
"$",
"expression",
",",
"$",
"type",
",",
"$",
"wrapNode",
",",
"$",
"this",
"->",
"node",
")",
";",
"}"
] | Searches for an node in the owner document using current node as context and returns first element or null.
@param string $expression XPath expression or a CSS selector
@param string $type The type of the expression
@param bool $wrapNode Returns \DiDom\Element if true, otherwise \DOMElement
@return \DiDom\Element|\DOMElement|null | [
"Searches",
"for",
"an",
"node",
"in",
"the",
"owner",
"document",
"using",
"current",
"node",
"as",
"context",
"and",
"returns",
"first",
"element",
"or",
"null",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L333-L342 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.xpath | public function xpath($expression, $wrapNode = true)
{
return $this->find($expression, Query::TYPE_XPATH, $wrapNode);
} | php | public function xpath($expression, $wrapNode = true)
{
return $this->find($expression, Query::TYPE_XPATH, $wrapNode);
} | [
"public",
"function",
"xpath",
"(",
"$",
"expression",
",",
"$",
"wrapNode",
"=",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"find",
"(",
"$",
"expression",
",",
"Query",
"::",
"TYPE_XPATH",
",",
"$",
"wrapNode",
")",
";",
"}"
] | Searches for an node in the DOM tree for a given XPath expression.
@param string $expression XPath expression
@param bool $wrapNode Returns array of \DiDom\Element if true, otherwise array of \DOMElement
@return \DiDom\Element[]|\DOMElement[] | [
"Searches",
"for",
"an",
"node",
"in",
"the",
"DOM",
"tree",
"for",
"a",
"given",
"XPath",
"expression",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L352-L355 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.matches | public function matches($selector, $strict = false)
{
if (!is_string($selector)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($selector)));
}
if (!$this->node instanceof DOMElement) {
return false;
}
if ($selector === '*') {
return true;
}
if (!$strict) {
$innerHtml = $this->html();
$html = "<root>$innerHtml</root>";
$selector = 'root > ' . trim($selector);
$document = new Document();
$document->loadHtml($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
return $document->has($selector);
}
$segments = Query::getSegments($selector);
if (!array_key_exists('tag', $segments)) {
throw new RuntimeException(sprintf('Tag name must be specified in %s', $selector));
}
if ($segments['tag'] !== $this->tag && $segments['tag'] !== '*') {
return false;
}
$segments['id'] = array_key_exists('id', $segments) ? $segments['id'] : null;
if ($segments['id'] !== $this->getAttribute('id')) {
return false;
}
$classes = $this->hasAttribute('class') ? explode(' ', trim($this->getAttribute('class'))) : [];
$segments['classes'] = array_key_exists('classes', $segments) ? $segments['classes'] : [];
$diff1 = array_diff($segments['classes'], $classes);
$diff2 = array_diff($classes, $segments['classes']);
if (count($diff1) > 0 || count($diff2) > 0) {
return false;
}
$attributes = $this->attributes();
unset($attributes['id'], $attributes['class']);
$segments['attributes'] = array_key_exists('attributes', $segments) ? $segments['attributes'] : [];
$diff1 = array_diff_assoc($segments['attributes'], $attributes);
$diff2 = array_diff_assoc($attributes, $segments['attributes']);
// if the attributes are not equal
if (count($diff1) > 0 || count($diff2) > 0) {
return false;
}
return true;
} | php | public function matches($selector, $strict = false)
{
if (!is_string($selector)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($selector)));
}
if (!$this->node instanceof DOMElement) {
return false;
}
if ($selector === '*') {
return true;
}
if (!$strict) {
$innerHtml = $this->html();
$html = "<root>$innerHtml</root>";
$selector = 'root > ' . trim($selector);
$document = new Document();
$document->loadHtml($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
return $document->has($selector);
}
$segments = Query::getSegments($selector);
if (!array_key_exists('tag', $segments)) {
throw new RuntimeException(sprintf('Tag name must be specified in %s', $selector));
}
if ($segments['tag'] !== $this->tag && $segments['tag'] !== '*') {
return false;
}
$segments['id'] = array_key_exists('id', $segments) ? $segments['id'] : null;
if ($segments['id'] !== $this->getAttribute('id')) {
return false;
}
$classes = $this->hasAttribute('class') ? explode(' ', trim($this->getAttribute('class'))) : [];
$segments['classes'] = array_key_exists('classes', $segments) ? $segments['classes'] : [];
$diff1 = array_diff($segments['classes'], $classes);
$diff2 = array_diff($classes, $segments['classes']);
if (count($diff1) > 0 || count($diff2) > 0) {
return false;
}
$attributes = $this->attributes();
unset($attributes['id'], $attributes['class']);
$segments['attributes'] = array_key_exists('attributes', $segments) ? $segments['attributes'] : [];
$diff1 = array_diff_assoc($segments['attributes'], $attributes);
$diff2 = array_diff_assoc($attributes, $segments['attributes']);
// if the attributes are not equal
if (count($diff1) > 0 || count($diff2) > 0) {
return false;
}
return true;
} | [
"public",
"function",
"matches",
"(",
"$",
"selector",
",",
"$",
"strict",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"selector",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be string, %s given'",
",",
"__METHOD__",
",",
"gettype",
"(",
"$",
"selector",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"node",
"instanceof",
"DOMElement",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"selector",
"===",
"'*'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"$",
"strict",
")",
"{",
"$",
"innerHtml",
"=",
"$",
"this",
"->",
"html",
"(",
")",
";",
"$",
"html",
"=",
"\"<root>$innerHtml</root>\"",
";",
"$",
"selector",
"=",
"'root > '",
".",
"trim",
"(",
"$",
"selector",
")",
";",
"$",
"document",
"=",
"new",
"Document",
"(",
")",
";",
"$",
"document",
"->",
"loadHtml",
"(",
"$",
"html",
",",
"LIBXML_HTML_NODEFDTD",
"|",
"LIBXML_HTML_NOIMPLIED",
")",
";",
"return",
"$",
"document",
"->",
"has",
"(",
"$",
"selector",
")",
";",
"}",
"$",
"segments",
"=",
"Query",
"::",
"getSegments",
"(",
"$",
"selector",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"'tag'",
",",
"$",
"segments",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Tag name must be specified in %s'",
",",
"$",
"selector",
")",
")",
";",
"}",
"if",
"(",
"$",
"segments",
"[",
"'tag'",
"]",
"!==",
"$",
"this",
"->",
"tag",
"&&",
"$",
"segments",
"[",
"'tag'",
"]",
"!==",
"'*'",
")",
"{",
"return",
"false",
";",
"}",
"$",
"segments",
"[",
"'id'",
"]",
"=",
"array_key_exists",
"(",
"'id'",
",",
"$",
"segments",
")",
"?",
"$",
"segments",
"[",
"'id'",
"]",
":",
"null",
";",
"if",
"(",
"$",
"segments",
"[",
"'id'",
"]",
"!==",
"$",
"this",
"->",
"getAttribute",
"(",
"'id'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"classes",
"=",
"$",
"this",
"->",
"hasAttribute",
"(",
"'class'",
")",
"?",
"explode",
"(",
"' '",
",",
"trim",
"(",
"$",
"this",
"->",
"getAttribute",
"(",
"'class'",
")",
")",
")",
":",
"[",
"]",
";",
"$",
"segments",
"[",
"'classes'",
"]",
"=",
"array_key_exists",
"(",
"'classes'",
",",
"$",
"segments",
")",
"?",
"$",
"segments",
"[",
"'classes'",
"]",
":",
"[",
"]",
";",
"$",
"diff1",
"=",
"array_diff",
"(",
"$",
"segments",
"[",
"'classes'",
"]",
",",
"$",
"classes",
")",
";",
"$",
"diff2",
"=",
"array_diff",
"(",
"$",
"classes",
",",
"$",
"segments",
"[",
"'classes'",
"]",
")",
";",
"if",
"(",
"count",
"(",
"$",
"diff1",
")",
">",
"0",
"||",
"count",
"(",
"$",
"diff2",
")",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"$",
"attributes",
"=",
"$",
"this",
"->",
"attributes",
"(",
")",
";",
"unset",
"(",
"$",
"attributes",
"[",
"'id'",
"]",
",",
"$",
"attributes",
"[",
"'class'",
"]",
")",
";",
"$",
"segments",
"[",
"'attributes'",
"]",
"=",
"array_key_exists",
"(",
"'attributes'",
",",
"$",
"segments",
")",
"?",
"$",
"segments",
"[",
"'attributes'",
"]",
":",
"[",
"]",
";",
"$",
"diff1",
"=",
"array_diff_assoc",
"(",
"$",
"segments",
"[",
"'attributes'",
"]",
",",
"$",
"attributes",
")",
";",
"$",
"diff2",
"=",
"array_diff_assoc",
"(",
"$",
"attributes",
",",
"$",
"segments",
"[",
"'attributes'",
"]",
")",
";",
"// if the attributes are not equal",
"if",
"(",
"count",
"(",
"$",
"diff1",
")",
">",
"0",
"||",
"count",
"(",
"$",
"diff2",
")",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Checks that the node matches selector.
@param string $selector CSS selector
@param bool $strict
@return bool
@throws \InvalidArgumentException if the tag name is not a string
@throws \RuntimeException if the tag name is not specified in strict mode | [
"Checks",
"that",
"the",
"node",
"matches",
"selector",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L381-L450 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.setAttribute | public function setAttribute($name, $value)
{
if (is_numeric($value)) {
$value = (string) $value;
}
if (!is_string($value) && $value !== null) {
throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string or null, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value))));
}
$this->node->setAttribute($name, $value);
return $this;
} | php | public function setAttribute($name, $value)
{
if (is_numeric($value)) {
$value = (string) $value;
}
if (!is_string($value) && $value !== null) {
throw new InvalidArgumentException(sprintf('%s expects parameter 2 to be string or null, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value))));
}
$this->node->setAttribute($name, $value);
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"value",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
"&&",
"$",
"value",
"!==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 2 to be string or null, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"node",
"->",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Set an attribute on the element.
@param string $name The attribute name
@param string $value The attribute value
@return \DiDom\Element | [
"Set",
"an",
"attribute",
"on",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L472-L485 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.getAttribute | public function getAttribute($name, $default = null)
{
if ($this->hasAttribute($name)) {
return $this->node->getAttribute($name);
}
return $default;
} | php | public function getAttribute($name, $default = null)
{
if ($this->hasAttribute($name)) {
return $this->node->getAttribute($name);
}
return $default;
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasAttribute",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"node",
"->",
"getAttribute",
"(",
"$",
"name",
")",
";",
"}",
"return",
"$",
"default",
";",
"}"
] | Access to the element's attributes.
@param string $name The attribute name
@param string|null $default The value returned if the attribute does not exist
@return string|null The value of the attribute or null if attribute does not exist | [
"Access",
"to",
"the",
"element",
"s",
"attributes",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L495-L502 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.removeAllAttributes | public function removeAllAttributes(array $exclusions = [])
{
if (!$this->node instanceof DOMElement) {
return $this;
}
foreach ($this->attributes() as $name => $value) {
if (in_array($name, $exclusions, true)) {
continue;
}
$this->node->removeAttribute($name);
}
return $this;
} | php | public function removeAllAttributes(array $exclusions = [])
{
if (!$this->node instanceof DOMElement) {
return $this;
}
foreach ($this->attributes() as $name => $value) {
if (in_array($name, $exclusions, true)) {
continue;
}
$this->node->removeAttribute($name);
}
return $this;
} | [
"public",
"function",
"removeAllAttributes",
"(",
"array",
"$",
"exclusions",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"node",
"instanceof",
"DOMElement",
")",
"{",
"return",
"$",
"this",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"$",
"exclusions",
",",
"true",
")",
")",
"{",
"continue",
";",
"}",
"$",
"this",
"->",
"node",
"->",
"removeAttribute",
"(",
"$",
"name",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Unset all attributes of the element.
@param string[] $exclusions
@return \DiDom\Element | [
"Unset",
"all",
"attributes",
"of",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L525-L540 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.attr | public function attr($name, $value = null)
{
if ($value === null) {
return $this->getAttribute($name);
}
return $this->setAttribute($name, $value);
} | php | public function attr($name, $value = null)
{
if ($value === null) {
return $this->getAttribute($name);
}
return $this->setAttribute($name, $value);
} | [
"public",
"function",
"attr",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getAttribute",
"(",
"$",
"name",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}"
] | Alias for getAttribute and setAttribute methods.
@param string $name The attribute name
@param string|null $value The attribute value or null if the attribute does not exist
@return string|null|\DiDom\Element | [
"Alias",
"for",
"getAttribute",
"and",
"setAttribute",
"methods",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L550-L557 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.attributes | public function attributes(array $names = null)
{
if (!$this->node instanceof DOMElement) {
return null;
}
if ($names === null) {
$result = [];
foreach ($this->node->attributes as $name => $attribute) {
$result[$name] = $attribute->value;
}
return $result;
}
$result = [];
foreach ($this->node->attributes as $name => $attribute) {
if (in_array($name, $names, true)) {
$result[$name] = $attribute->value;
}
}
return $result;
} | php | public function attributes(array $names = null)
{
if (!$this->node instanceof DOMElement) {
return null;
}
if ($names === null) {
$result = [];
foreach ($this->node->attributes as $name => $attribute) {
$result[$name] = $attribute->value;
}
return $result;
}
$result = [];
foreach ($this->node->attributes as $name => $attribute) {
if (in_array($name, $names, true)) {
$result[$name] = $attribute->value;
}
}
return $result;
} | [
"public",
"function",
"attributes",
"(",
"array",
"$",
"names",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"node",
"instanceof",
"DOMElement",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"names",
"===",
"null",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"node",
"->",
"attributes",
"as",
"$",
"name",
"=>",
"$",
"attribute",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"$",
"attribute",
"->",
"value",
";",
"}",
"return",
"$",
"result",
";",
"}",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"node",
"->",
"attributes",
"as",
"$",
"name",
"=>",
"$",
"attribute",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"$",
"names",
",",
"true",
")",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"$",
"attribute",
"->",
"value",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Returns the node attributes or null, if it is not DOMElement.
@param string[] $names
@return array|null | [
"Returns",
"the",
"node",
"attributes",
"or",
"null",
"if",
"it",
"is",
"not",
"DOMElement",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L566-L591 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.innerHtml | public function innerHtml($delimiter = '')
{
$innerHtml = [];
foreach ($this->node->childNodes as $childNode) {
$innerHtml[] = $childNode->ownerDocument->saveHTML($childNode);
}
return implode($delimiter, $innerHtml);
} | php | public function innerHtml($delimiter = '')
{
$innerHtml = [];
foreach ($this->node->childNodes as $childNode) {
$innerHtml[] = $childNode->ownerDocument->saveHTML($childNode);
}
return implode($delimiter, $innerHtml);
} | [
"public",
"function",
"innerHtml",
"(",
"$",
"delimiter",
"=",
"''",
")",
"{",
"$",
"innerHtml",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"node",
"->",
"childNodes",
"as",
"$",
"childNode",
")",
"{",
"$",
"innerHtml",
"[",
"]",
"=",
"$",
"childNode",
"->",
"ownerDocument",
"->",
"saveHTML",
"(",
"$",
"childNode",
")",
";",
"}",
"return",
"implode",
"(",
"$",
"delimiter",
",",
"$",
"innerHtml",
")",
";",
"}"
] | Dumps the node descendants into a string using HTML formatting.
@param string $delimiter
@return string | [
"Dumps",
"the",
"node",
"descendants",
"into",
"a",
"string",
"using",
"HTML",
"formatting",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L664-L673 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.innerXml | public function innerXml($delimiter = '')
{
$innerXml = [];
foreach ($this->node->childNodes as $childNode) {
$innerXml[] = $childNode->ownerDocument->saveXML($childNode);
}
return implode($delimiter, $innerXml);
} | php | public function innerXml($delimiter = '')
{
$innerXml = [];
foreach ($this->node->childNodes as $childNode) {
$innerXml[] = $childNode->ownerDocument->saveXML($childNode);
}
return implode($delimiter, $innerXml);
} | [
"public",
"function",
"innerXml",
"(",
"$",
"delimiter",
"=",
"''",
")",
"{",
"$",
"innerXml",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"node",
"->",
"childNodes",
"as",
"$",
"childNode",
")",
"{",
"$",
"innerXml",
"[",
"]",
"=",
"$",
"childNode",
"->",
"ownerDocument",
"->",
"saveXML",
"(",
"$",
"childNode",
")",
";",
"}",
"return",
"implode",
"(",
"$",
"delimiter",
",",
"$",
"innerXml",
")",
";",
"}"
] | Dumps the node descendants into a string using XML formatting.
@param string $delimiter
@return string | [
"Dumps",
"the",
"node",
"descendants",
"into",
"a",
"string",
"using",
"XML",
"formatting",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L682-L691 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.setInnerHtml | public function setInnerHtml($html)
{
if (!is_string($html)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($html) ? get_class($html) : gettype($html))));
}
$this->removeChildren();
if ($html !== '') {
Errors::disable();
$html = "<htmlfragment>$html</htmlfragment>";
$document = new Document($html);
$fragment = $document->first('htmlfragment')->getNode();
foreach ($fragment->childNodes as $node) {
$newNode = $this->node->ownerDocument->importNode($node, true);
$this->node->appendChild($newNode);
}
Errors::restore();
}
return $this;
} | php | public function setInnerHtml($html)
{
if (!is_string($html)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($html) ? get_class($html) : gettype($html))));
}
$this->removeChildren();
if ($html !== '') {
Errors::disable();
$html = "<htmlfragment>$html</htmlfragment>";
$document = new Document($html);
$fragment = $document->first('htmlfragment')->getNode();
foreach ($fragment->childNodes as $node) {
$newNode = $this->node->ownerDocument->importNode($node, true);
$this->node->appendChild($newNode);
}
Errors::restore();
}
return $this;
} | [
"public",
"function",
"setInnerHtml",
"(",
"$",
"html",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"html",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be string, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"html",
")",
"?",
"get_class",
"(",
"$",
"html",
")",
":",
"gettype",
"(",
"$",
"html",
")",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"removeChildren",
"(",
")",
";",
"if",
"(",
"$",
"html",
"!==",
"''",
")",
"{",
"Errors",
"::",
"disable",
"(",
")",
";",
"$",
"html",
"=",
"\"<htmlfragment>$html</htmlfragment>\"",
";",
"$",
"document",
"=",
"new",
"Document",
"(",
"$",
"html",
")",
";",
"$",
"fragment",
"=",
"$",
"document",
"->",
"first",
"(",
"'htmlfragment'",
")",
"->",
"getNode",
"(",
")",
";",
"foreach",
"(",
"$",
"fragment",
"->",
"childNodes",
"as",
"$",
"node",
")",
"{",
"$",
"newNode",
"=",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"->",
"importNode",
"(",
"$",
"node",
",",
"true",
")",
";",
"$",
"this",
"->",
"node",
"->",
"appendChild",
"(",
"$",
"newNode",
")",
";",
"}",
"Errors",
"::",
"restore",
"(",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets inner HTML.
@param string $html
@return \DiDom\Element
@throws InvalidArgumentException if passed argument is not a string | [
"Sets",
"inner",
"HTML",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L702-L729 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.setValue | public function setValue($value)
{
if (is_numeric($value)) {
$value = (string) $value;
}
if (!is_string($value) && $value !== null) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value))));
}
$this->node->nodeValue = $value;
return $this;
} | php | public function setValue($value)
{
if (is_numeric($value)) {
$value = (string) $value;
}
if (!is_string($value) && $value !== null) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($value) ? get_class($value) : gettype($value))));
}
$this->node->nodeValue = $value;
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"value",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
"&&",
"$",
"value",
"!==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be string, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"node",
"->",
"nodeValue",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | Set the value of this node.
@param string $value The new value of the node
@return \DiDom\Element
@throws \InvalidArgumentException if value is not string | [
"Set",
"the",
"value",
"of",
"this",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L762-L775 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.is | public function is($node)
{
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($node) ? get_class($node) : gettype($node))));
}
return $this->node->isSameNode($node);
} | php | public function is($node)
{
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($node) ? get_class($node) : gettype($node))));
}
return $this->node->isSameNode($node);
} | [
"public",
"function",
"is",
"(",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"Element",
")",
"{",
"$",
"node",
"=",
"$",
"node",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"node",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__CLASS__",
",",
"(",
"is_object",
"(",
"$",
"node",
")",
"?",
"get_class",
"(",
"$",
"node",
")",
":",
"gettype",
"(",
"$",
"node",
")",
")",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"node",
"->",
"isSameNode",
"(",
"$",
"node",
")",
";",
"}"
] | Indicates if two nodes are the same node.
@param \DiDom\Element|\DOMNode $node
@return bool
@throws \InvalidArgumentException if the provided argument is not an instance of \DOMNode | [
"Indicates",
"if",
"two",
"nodes",
"are",
"the",
"same",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L826-L837 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.closest | public function closest($selector, $strict = false)
{
$node = $this;
while (true) {
$parent = $node->parent();
if ($parent === null || $parent instanceof Document) {
return null;
}
if ($parent->matches($selector, $strict)) {
return $parent;
}
$node = $parent;
}
} | php | public function closest($selector, $strict = false)
{
$node = $this;
while (true) {
$parent = $node->parent();
if ($parent === null || $parent instanceof Document) {
return null;
}
if ($parent->matches($selector, $strict)) {
return $parent;
}
$node = $parent;
}
} | [
"public",
"function",
"closest",
"(",
"$",
"selector",
",",
"$",
"strict",
"=",
"false",
")",
"{",
"$",
"node",
"=",
"$",
"this",
";",
"while",
"(",
"true",
")",
"{",
"$",
"parent",
"=",
"$",
"node",
"->",
"parent",
"(",
")",
";",
"if",
"(",
"$",
"parent",
"===",
"null",
"||",
"$",
"parent",
"instanceof",
"Document",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"$",
"parent",
"->",
"matches",
"(",
"$",
"selector",
",",
"$",
"strict",
")",
")",
"{",
"return",
"$",
"parent",
";",
"}",
"$",
"node",
"=",
"$",
"parent",
";",
"}",
"}"
] | Returns first parent node matches passed selector.
@param string $selector
@param bool $strict
@return \DiDom\Element|null | [
"Returns",
"first",
"parent",
"node",
"matches",
"passed",
"selector",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L863-L880 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.removeChild | public function removeChild($childNode)
{
if ($childNode instanceof Element) {
$childNode = $childNode->getNode();
}
if (!$childNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($childNode) ? get_class($childNode) : gettype($childNode))));
}
$removedNode = $this->node->removeChild($childNode);
return new Element($removedNode);
} | php | public function removeChild($childNode)
{
if ($childNode instanceof Element) {
$childNode = $childNode->getNode();
}
if (!$childNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($childNode) ? get_class($childNode) : gettype($childNode))));
}
$removedNode = $this->node->removeChild($childNode);
return new Element($removedNode);
} | [
"public",
"function",
"removeChild",
"(",
"$",
"childNode",
")",
"{",
"if",
"(",
"$",
"childNode",
"instanceof",
"Element",
")",
"{",
"$",
"childNode",
"=",
"$",
"childNode",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"childNode",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__CLASS__",
",",
"(",
"is_object",
"(",
"$",
"childNode",
")",
"?",
"get_class",
"(",
"$",
"childNode",
")",
":",
"gettype",
"(",
"$",
"childNode",
")",
")",
")",
")",
";",
"}",
"$",
"removedNode",
"=",
"$",
"this",
"->",
"node",
"->",
"removeChild",
"(",
"$",
"childNode",
")",
";",
"return",
"new",
"Element",
"(",
"$",
"removedNode",
")",
";",
"}"
] | Removes child from list of children.
@param \DOMNode|\DiDom\Element $childNode
@return \DiDom\Element the node that has been removed | [
"Removes",
"child",
"from",
"list",
"of",
"children",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1223-L1236 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.removeChildren | public function removeChildren()
{
// we need to collect child nodes to array
// because removing nodes from the DOMNodeList on iterating is not working
$childNodes = [];
foreach ($this->node->childNodes as $childNode) {
$childNodes[] = $childNode;
}
$removedNodes = [];
foreach ($childNodes as $childNode) {
$removedNode = $this->node->removeChild($childNode);
$removedNodes[] = new Element($removedNode);
}
return $removedNodes;
} | php | public function removeChildren()
{
// we need to collect child nodes to array
// because removing nodes from the DOMNodeList on iterating is not working
$childNodes = [];
foreach ($this->node->childNodes as $childNode) {
$childNodes[] = $childNode;
}
$removedNodes = [];
foreach ($childNodes as $childNode) {
$removedNode = $this->node->removeChild($childNode);
$removedNodes[] = new Element($removedNode);
}
return $removedNodes;
} | [
"public",
"function",
"removeChildren",
"(",
")",
"{",
"// we need to collect child nodes to array",
"// because removing nodes from the DOMNodeList on iterating is not working",
"$",
"childNodes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"node",
"->",
"childNodes",
"as",
"$",
"childNode",
")",
"{",
"$",
"childNodes",
"[",
"]",
"=",
"$",
"childNode",
";",
"}",
"$",
"removedNodes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"childNodes",
"as",
"$",
"childNode",
")",
"{",
"$",
"removedNode",
"=",
"$",
"this",
"->",
"node",
"->",
"removeChild",
"(",
"$",
"childNode",
")",
";",
"$",
"removedNodes",
"[",
"]",
"=",
"new",
"Element",
"(",
"$",
"removedNode",
")",
";",
"}",
"return",
"$",
"removedNodes",
";",
"}"
] | Removes all child nodes.
@return \DiDom\Element[] the nodes that has been removed | [
"Removes",
"all",
"child",
"nodes",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1243-L1262 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.remove | public function remove()
{
if ($this->node->parentNode === null) {
throw new LogicException('Can not remove element without parent node');
}
$removedNode = $this->node->parentNode->removeChild($this->node);
return new Element($removedNode);
} | php | public function remove()
{
if ($this->node->parentNode === null) {
throw new LogicException('Can not remove element without parent node');
}
$removedNode = $this->node->parentNode->removeChild($this->node);
return new Element($removedNode);
} | [
"public",
"function",
"remove",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"parentNode",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not remove element without parent node'",
")",
";",
"}",
"$",
"removedNode",
"=",
"$",
"this",
"->",
"node",
"->",
"parentNode",
"->",
"removeChild",
"(",
"$",
"this",
"->",
"node",
")",
";",
"return",
"new",
"Element",
"(",
"$",
"removedNode",
")",
";",
"}"
] | Removes current node from the parent.
@return \DiDom\Element the node that has been removed
@throws \LogicException if current node has no parent node | [
"Removes",
"current",
"node",
"from",
"the",
"parent",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1271-L1280 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.replace | public function replace($newNode, $clone = true)
{
if ($this->node->parentNode === null) {
throw new LogicException('Can not replace element without parent node');
}
if ($newNode instanceof Element) {
$newNode = $newNode->getNode();
}
if (!$newNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($newNode) ? get_class($newNode) : gettype($newNode))));
}
if ($clone) {
$newNode = $newNode->cloneNode(true);
}
if ($newNode->ownerDocument === null || !$this->getDocument()->is($newNode->ownerDocument)) {
$newNode = $this->node->ownerDocument->importNode($newNode, true);
}
$node = $this->node->parentNode->replaceChild($newNode, $this->node);
return new Element($node);
} | php | public function replace($newNode, $clone = true)
{
if ($this->node->parentNode === null) {
throw new LogicException('Can not replace element without parent node');
}
if ($newNode instanceof Element) {
$newNode = $newNode->getNode();
}
if (!$newNode instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, (is_object($newNode) ? get_class($newNode) : gettype($newNode))));
}
if ($clone) {
$newNode = $newNode->cloneNode(true);
}
if ($newNode->ownerDocument === null || !$this->getDocument()->is($newNode->ownerDocument)) {
$newNode = $this->node->ownerDocument->importNode($newNode, true);
}
$node = $this->node->parentNode->replaceChild($newNode, $this->node);
return new Element($node);
} | [
"public",
"function",
"replace",
"(",
"$",
"newNode",
",",
"$",
"clone",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"parentNode",
"===",
"null",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Can not replace element without parent node'",
")",
";",
"}",
"if",
"(",
"$",
"newNode",
"instanceof",
"Element",
")",
"{",
"$",
"newNode",
"=",
"$",
"newNode",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"newNode",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__CLASS__",
",",
"(",
"is_object",
"(",
"$",
"newNode",
")",
"?",
"get_class",
"(",
"$",
"newNode",
")",
":",
"gettype",
"(",
"$",
"newNode",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"clone",
")",
"{",
"$",
"newNode",
"=",
"$",
"newNode",
"->",
"cloneNode",
"(",
"true",
")",
";",
"}",
"if",
"(",
"$",
"newNode",
"->",
"ownerDocument",
"===",
"null",
"||",
"!",
"$",
"this",
"->",
"getDocument",
"(",
")",
"->",
"is",
"(",
"$",
"newNode",
"->",
"ownerDocument",
")",
")",
"{",
"$",
"newNode",
"=",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"->",
"importNode",
"(",
"$",
"newNode",
",",
"true",
")",
";",
"}",
"$",
"node",
"=",
"$",
"this",
"->",
"node",
"->",
"parentNode",
"->",
"replaceChild",
"(",
"$",
"newNode",
",",
"$",
"this",
"->",
"node",
")",
";",
"return",
"new",
"Element",
"(",
"$",
"node",
")",
";",
"}"
] | Replaces a child.
@param \DOMNode|\DiDom\Element $newNode The new node
@param bool $clone Clone the node if true, otherwise move it
@return \DiDom\Element The node that has been replaced
@throws \LogicException if current node has no parent node | [
"Replaces",
"a",
"child",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1292-L1317 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.setNode | protected function setNode($node)
{
$allowedClasses = ['DOMElement', 'DOMText', 'DOMComment', 'DOMCdataSection'];
if (!is_object($node) || !in_array(get_class($node), $allowedClasses, true)) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of DOMElement, DOMText, DOMComment or DOMCdataSection, %s given', __METHOD__, (is_object($node) ? get_class($node) : gettype($node))));
}
$this->node = $node;
return $this;
} | php | protected function setNode($node)
{
$allowedClasses = ['DOMElement', 'DOMText', 'DOMComment', 'DOMCdataSection'];
if (!is_object($node) || !in_array(get_class($node), $allowedClasses, true)) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of DOMElement, DOMText, DOMComment or DOMCdataSection, %s given', __METHOD__, (is_object($node) ? get_class($node) : gettype($node))));
}
$this->node = $node;
return $this;
} | [
"protected",
"function",
"setNode",
"(",
"$",
"node",
")",
"{",
"$",
"allowedClasses",
"=",
"[",
"'DOMElement'",
",",
"'DOMText'",
",",
"'DOMComment'",
",",
"'DOMCdataSection'",
"]",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"node",
")",
"||",
"!",
"in_array",
"(",
"get_class",
"(",
"$",
"node",
")",
",",
"$",
"allowedClasses",
",",
"true",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of DOMElement, DOMText, DOMComment or DOMCdataSection, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"node",
")",
"?",
"get_class",
"(",
"$",
"node",
")",
":",
"gettype",
"(",
"$",
"node",
")",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"node",
"=",
"$",
"node",
";",
"return",
"$",
"this",
";",
"}"
] | Sets current node instance.
@param \DOMElement|\DOMText|\DOMComment|\DOMCdataSection $node
@return \DiDom\Element | [
"Sets",
"current",
"node",
"instance",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1348-L1359 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.getDocument | public function getDocument()
{
if ($this->node->ownerDocument === null) {
return null;
}
return new Document($this->node->ownerDocument);
} | php | public function getDocument()
{
if ($this->node->ownerDocument === null) {
return null;
}
return new Document($this->node->ownerDocument);
} | [
"public",
"function",
"getDocument",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"Document",
"(",
"$",
"this",
"->",
"node",
"->",
"ownerDocument",
")",
";",
"}"
] | Returns the document associated with this node.
@return \DiDom\Document|null | [
"Returns",
"the",
"document",
"associated",
"with",
"this",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1376-L1383 | train |
Imangazaliev/DiDOM | src/DiDom/Element.php | Element.toDocument | public function toDocument($encoding = 'UTF-8')
{
$document = new Document(null, false, $encoding);
$document->appendChild($this->node);
return $document;
} | php | public function toDocument($encoding = 'UTF-8')
{
$document = new Document(null, false, $encoding);
$document->appendChild($this->node);
return $document;
} | [
"public",
"function",
"toDocument",
"(",
"$",
"encoding",
"=",
"'UTF-8'",
")",
"{",
"$",
"document",
"=",
"new",
"Document",
"(",
"null",
",",
"false",
",",
"$",
"encoding",
")",
";",
"$",
"document",
"->",
"appendChild",
"(",
"$",
"this",
"->",
"node",
")",
";",
"return",
"$",
"document",
";",
"}"
] | Get the DOM document with the current element.
@param string $encoding The document encoding
@return \DiDom\Document | [
"Get",
"the",
"DOM",
"document",
"with",
"the",
"current",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Element.php#L1392-L1399 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.createElement | public function createElement($name, $value = null, array $attributes = [])
{
$node = $this->document->createElement($name);
return new Element($node, $value, $attributes);
} | php | public function createElement($name, $value = null, array $attributes = [])
{
$node = $this->document->createElement($name);
return new Element($node, $value, $attributes);
} | [
"public",
"function",
"createElement",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"document",
"->",
"createElement",
"(",
"$",
"name",
")",
";",
"return",
"new",
"Element",
"(",
"$",
"node",
",",
"$",
"value",
",",
"$",
"attributes",
")",
";",
"}"
] | Creates a new element node.
@param string $name The tag name of the element
@param string|null $value The value of the element
@param array $attributes The attributes of the element
@return \DiDom\Element created element | [
"Creates",
"a",
"new",
"element",
"node",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L97-L102 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.appendChild | public function appendChild($nodes)
{
$returnArray = true;
if (!is_array($nodes)) {
$nodes = [$nodes];
$returnArray = false;
}
$result = [];
foreach ($nodes as $node) {
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node))));
}
Errors::disable();
$cloned = $node->cloneNode(true);
$newNode = $this->document->importNode($cloned, true);
$result[] = $this->document->appendChild($newNode);
Errors::restore();
}
$result = array_map(function (DOMNode $node) {
return new Element($node);
}, $result);
return $returnArray ? $result : $result[0];
} | php | public function appendChild($nodes)
{
$returnArray = true;
if (!is_array($nodes)) {
$nodes = [$nodes];
$returnArray = false;
}
$result = [];
foreach ($nodes as $node) {
if ($node instanceof Element) {
$node = $node->getNode();
}
if (!$node instanceof DOMNode) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMNode, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node))));
}
Errors::disable();
$cloned = $node->cloneNode(true);
$newNode = $this->document->importNode($cloned, true);
$result[] = $this->document->appendChild($newNode);
Errors::restore();
}
$result = array_map(function (DOMNode $node) {
return new Element($node);
}, $result);
return $returnArray ? $result : $result[0];
} | [
"public",
"function",
"appendChild",
"(",
"$",
"nodes",
")",
"{",
"$",
"returnArray",
"=",
"true",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"nodes",
")",
")",
"{",
"$",
"nodes",
"=",
"[",
"$",
"nodes",
"]",
";",
"$",
"returnArray",
"=",
"false",
";",
"}",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"Element",
")",
"{",
"$",
"node",
"=",
"$",
"node",
"->",
"getNode",
"(",
")",
";",
"}",
"if",
"(",
"!",
"$",
"node",
"instanceof",
"DOMNode",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s\\Element or DOMNode, %s given'",
",",
"__METHOD__",
",",
"__NAMESPACE__",
",",
"(",
"is_object",
"(",
"$",
"node",
")",
"?",
"get_class",
"(",
"$",
"node",
")",
":",
"gettype",
"(",
"$",
"node",
")",
")",
")",
")",
";",
"}",
"Errors",
"::",
"disable",
"(",
")",
";",
"$",
"cloned",
"=",
"$",
"node",
"->",
"cloneNode",
"(",
"true",
")",
";",
"$",
"newNode",
"=",
"$",
"this",
"->",
"document",
"->",
"importNode",
"(",
"$",
"cloned",
",",
"true",
")",
";",
"$",
"result",
"[",
"]",
"=",
"$",
"this",
"->",
"document",
"->",
"appendChild",
"(",
"$",
"newNode",
")",
";",
"Errors",
"::",
"restore",
"(",
")",
";",
"}",
"$",
"result",
"=",
"array_map",
"(",
"function",
"(",
"DOMNode",
"$",
"node",
")",
"{",
"return",
"new",
"Element",
"(",
"$",
"node",
")",
";",
"}",
",",
"$",
"result",
")",
";",
"return",
"$",
"returnArray",
"?",
"$",
"result",
":",
"$",
"result",
"[",
"0",
"]",
";",
"}"
] | Adds a new child at the end of the children.
@param \DiDom\Element|\DOMNode|array $nodes The appended child
@return \DiDom\Element|\DiDom\Element[]
@throws \InvalidArgumentException if the passed argument is not an instance of \DOMNode or \DiDom\Element | [
"Adds",
"a",
"new",
"child",
"at",
"the",
"end",
"of",
"the",
"children",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L173-L209 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.preserveWhiteSpace | public function preserveWhiteSpace($value = true)
{
if (!is_bool($value)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($value)));
}
$this->document->preserveWhiteSpace = $value;
return $this;
} | php | public function preserveWhiteSpace($value = true)
{
if (!is_bool($value)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($value)));
}
$this->document->preserveWhiteSpace = $value;
return $this;
} | [
"public",
"function",
"preserveWhiteSpace",
"(",
"$",
"value",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be boolean, %s given'",
",",
"__METHOD__",
",",
"gettype",
"(",
"$",
"value",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"document",
"->",
"preserveWhiteSpace",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | Set preserveWhiteSpace property.
@param bool $value
@return \DiDom\Document | [
"Set",
"preserveWhiteSpace",
"property",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L218-L227 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.load | public function load($string, $isFile = false, $type = Document::TYPE_HTML, $options = null)
{
if (!is_string($string)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($string) ? get_class($string) : gettype($string))));
}
if (!is_string($type)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 3 to be string, %s given', __METHOD__, (is_object($type) ? get_class($type) : gettype($type))));
}
if (!in_array(strtolower($type), [Document::TYPE_HTML, Document::TYPE_XML], true)) {
throw new RuntimeException(sprintf('Document type must be "xml" or "html", %s given', $type));
}
if ($options === null) {
// LIBXML_HTML_NODEFDTD - prevents a default doctype being added when one is not found
$options = LIBXML_HTML_NODEFDTD;
}
if (!is_int($options)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 4 to be integer, %s given', __METHOD__, (is_object($options) ? get_class($options) : gettype($options))));
}
$string = trim($string);
if ($isFile) {
$string = $this->loadFile($string);
}
if (strtolower($type) === Document::TYPE_HTML) {
$string = Encoder::convertToHtmlEntities($string, $this->encoding);
}
$this->type = strtolower($type);
Errors::disable();
if ($this->type === Document::TYPE_HTML) {
$this->document->loadHtml($string, $options);
} else {
$this->document->loadXml($string, $options);
}
Errors::restore();
return $this;
} | php | public function load($string, $isFile = false, $type = Document::TYPE_HTML, $options = null)
{
if (!is_string($string)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, (is_object($string) ? get_class($string) : gettype($string))));
}
if (!is_string($type)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 3 to be string, %s given', __METHOD__, (is_object($type) ? get_class($type) : gettype($type))));
}
if (!in_array(strtolower($type), [Document::TYPE_HTML, Document::TYPE_XML], true)) {
throw new RuntimeException(sprintf('Document type must be "xml" or "html", %s given', $type));
}
if ($options === null) {
// LIBXML_HTML_NODEFDTD - prevents a default doctype being added when one is not found
$options = LIBXML_HTML_NODEFDTD;
}
if (!is_int($options)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 4 to be integer, %s given', __METHOD__, (is_object($options) ? get_class($options) : gettype($options))));
}
$string = trim($string);
if ($isFile) {
$string = $this->loadFile($string);
}
if (strtolower($type) === Document::TYPE_HTML) {
$string = Encoder::convertToHtmlEntities($string, $this->encoding);
}
$this->type = strtolower($type);
Errors::disable();
if ($this->type === Document::TYPE_HTML) {
$this->document->loadHtml($string, $options);
} else {
$this->document->loadXml($string, $options);
}
Errors::restore();
return $this;
} | [
"public",
"function",
"load",
"(",
"$",
"string",
",",
"$",
"isFile",
"=",
"false",
",",
"$",
"type",
"=",
"Document",
"::",
"TYPE_HTML",
",",
"$",
"options",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"string",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be string, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"string",
")",
"?",
"get_class",
"(",
"$",
"string",
")",
":",
"gettype",
"(",
"$",
"string",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"type",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 3 to be string, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"type",
")",
"?",
"get_class",
"(",
"$",
"type",
")",
":",
"gettype",
"(",
"$",
"type",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"strtolower",
"(",
"$",
"type",
")",
",",
"[",
"Document",
"::",
"TYPE_HTML",
",",
"Document",
"::",
"TYPE_XML",
"]",
",",
"true",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Document type must be \"xml\" or \"html\", %s given'",
",",
"$",
"type",
")",
")",
";",
"}",
"if",
"(",
"$",
"options",
"===",
"null",
")",
"{",
"// LIBXML_HTML_NODEFDTD - prevents a default doctype being added when one is not found",
"$",
"options",
"=",
"LIBXML_HTML_NODEFDTD",
";",
"}",
"if",
"(",
"!",
"is_int",
"(",
"$",
"options",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 4 to be integer, %s given'",
",",
"__METHOD__",
",",
"(",
"is_object",
"(",
"$",
"options",
")",
"?",
"get_class",
"(",
"$",
"options",
")",
":",
"gettype",
"(",
"$",
"options",
")",
")",
")",
")",
";",
"}",
"$",
"string",
"=",
"trim",
"(",
"$",
"string",
")",
";",
"if",
"(",
"$",
"isFile",
")",
"{",
"$",
"string",
"=",
"$",
"this",
"->",
"loadFile",
"(",
"$",
"string",
")",
";",
"}",
"if",
"(",
"strtolower",
"(",
"$",
"type",
")",
"===",
"Document",
"::",
"TYPE_HTML",
")",
"{",
"$",
"string",
"=",
"Encoder",
"::",
"convertToHtmlEntities",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"encoding",
")",
";",
"}",
"$",
"this",
"->",
"type",
"=",
"strtolower",
"(",
"$",
"type",
")",
";",
"Errors",
"::",
"disable",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"===",
"Document",
"::",
"TYPE_HTML",
")",
"{",
"$",
"this",
"->",
"document",
"->",
"loadHtml",
"(",
"$",
"string",
",",
"$",
"options",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"document",
"->",
"loadXml",
"(",
"$",
"string",
",",
"$",
"options",
")",
";",
"}",
"Errors",
"::",
"restore",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Load HTML or XML.
@param string $string HTML or XML string or file path
@param bool $isFile Indicates that in first parameter was passed to the file path
@param string $type Type of the document
@param int|null $options Additional parameters
@return \DiDom\Document
@throws \InvalidArgumentException if first parameter is not a string
@throws \InvalidArgumentException if document type parameter is not a string
@throws \RuntimeException if document type is not HTML or XML | [
"Load",
"HTML",
"or",
"XML",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L243-L289 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.loadHtmlFile | public function loadHtmlFile($filename, $options = null)
{
return $this->load($filename, true, Document::TYPE_HTML, $options);
} | php | public function loadHtmlFile($filename, $options = null)
{
return $this->load($filename, true, Document::TYPE_HTML, $options);
} | [
"public",
"function",
"loadHtmlFile",
"(",
"$",
"filename",
",",
"$",
"options",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"load",
"(",
"$",
"filename",
",",
"true",
",",
"Document",
"::",
"TYPE_HTML",
",",
"$",
"options",
")",
";",
"}"
] | Load HTML from a file.
@param string $filename The path to the HTML file
@param int|null $options Additional parameters
@return \DiDom\Document
@throws \InvalidArgumentException if the file path is not a string
@throws \RuntimeException if the file does not exist
@throws \RuntimeException if you are unable to load the file | [
"Load",
"HTML",
"from",
"a",
"file",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L318-L321 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.loadXml | public function loadXml($xml, $options = null)
{
return $this->load($xml, false, Document::TYPE_XML, $options);
} | php | public function loadXml($xml, $options = null)
{
return $this->load($xml, false, Document::TYPE_XML, $options);
} | [
"public",
"function",
"loadXml",
"(",
"$",
"xml",
",",
"$",
"options",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"load",
"(",
"$",
"xml",
",",
"false",
",",
"Document",
"::",
"TYPE_XML",
",",
"$",
"options",
")",
";",
"}"
] | Load XML from a string.
@param string $xml The XML string
@param int|null $options Additional parameters
@return \DiDom\Document
@throws \InvalidArgumentException if the provided argument is not a string | [
"Load",
"XML",
"from",
"a",
"string",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L333-L336 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.loadXmlFile | public function loadXmlFile($filename, $options = null)
{
return $this->load($filename, true, Document::TYPE_XML, $options);
} | php | public function loadXmlFile($filename, $options = null)
{
return $this->load($filename, true, Document::TYPE_XML, $options);
} | [
"public",
"function",
"loadXmlFile",
"(",
"$",
"filename",
",",
"$",
"options",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"load",
"(",
"$",
"filename",
",",
"true",
",",
"Document",
"::",
"TYPE_XML",
",",
"$",
"options",
")",
";",
"}"
] | Load XML from a file.
@param string $filename The path to the XML file
@param int|null $options Additional parameters
@return \DiDom\Document
@throws \InvalidArgumentException if the file path is not a string
@throws \RuntimeException if the file does not exist
@throws \RuntimeException if you are unable to load the file | [
"Load",
"XML",
"from",
"a",
"file",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L350-L353 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.loadFile | protected function loadFile($filename)
{
if (!is_string($filename)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($filename)));
}
try {
$content = file_get_contents($filename);
} catch (\Exception $exception) {
throw new RuntimeException(sprintf('Could not load file %s', $filename));
}
if ($content === false) {
throw new RuntimeException(sprintf('Could not load file %s', $filename));
}
return $content;
} | php | protected function loadFile($filename)
{
if (!is_string($filename)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, gettype($filename)));
}
try {
$content = file_get_contents($filename);
} catch (\Exception $exception) {
throw new RuntimeException(sprintf('Could not load file %s', $filename));
}
if ($content === false) {
throw new RuntimeException(sprintf('Could not load file %s', $filename));
}
return $content;
} | [
"protected",
"function",
"loadFile",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"filename",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be string, %s given'",
",",
"__METHOD__",
",",
"gettype",
"(",
"$",
"filename",
")",
")",
")",
";",
"}",
"try",
"{",
"$",
"content",
"=",
"file_get_contents",
"(",
"$",
"filename",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"exception",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Could not load file %s'",
",",
"$",
"filename",
")",
")",
";",
"}",
"if",
"(",
"$",
"content",
"===",
"false",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Could not load file %s'",
",",
"$",
"filename",
")",
")",
";",
"}",
"return",
"$",
"content",
";",
"}"
] | Reads entire file into a string.
@param string $filename The path to the file
@return string
@throws \InvalidArgumentException if the file path is not a string
@throws \RuntimeException if an error occurred | [
"Reads",
"entire",
"file",
"into",
"a",
"string",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L365-L382 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.format | public function format($format = true)
{
if (!is_bool($format)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($format)));
}
$this->document->formatOutput = $format;
return $this;
} | php | public function format($format = true)
{
if (!is_bool($format)) {
throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($format)));
}
$this->document->formatOutput = $format;
return $this;
} | [
"public",
"function",
"format",
"(",
"$",
"format",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"format",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'%s expects parameter 1 to be boolean, %s given'",
",",
"__METHOD__",
",",
"gettype",
"(",
"$",
"format",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"document",
"->",
"formatOutput",
"=",
"$",
"format",
";",
"return",
"$",
"this",
";",
"}"
] | Nicely formats output with indentation and extra space.
@param bool $format Formats output if true
@return \DiDom\Document | [
"Nicely",
"formats",
"output",
"with",
"indentation",
"and",
"extra",
"space",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L577-L586 | train |
Imangazaliev/DiDOM | src/DiDom/Document.php | Document.is | public function is($document)
{
if ($document instanceof Document) {
$element = $document->getElement();
} else {
if (!$document instanceof DOMDocument) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMDocument, %s given', __METHOD__, __CLASS__, (is_object($document) ? get_class($document) : gettype($document))));
}
$element = $document->documentElement;
}
if ($element === null) {
return false;
}
return $this->getElement()->isSameNode($element);
} | php | public function is($document)
{
if ($document instanceof Document) {
$element = $document->getElement();
} else {
if (!$document instanceof DOMDocument) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMDocument, %s given', __METHOD__, __CLASS__, (is_object($document) ? get_class($document) : gettype($document))));
}
$element = $document->documentElement;
}
if ($element === null) {
return false;
}
return $this->getElement()->isSameNode($element);
} | [
"public",
"function",
"is",
"(",
"$",
"document",
")",
"{",
"if",
"(",
"$",
"document",
"instanceof",
"Document",
")",
"{",
"$",
"element",
"=",
"$",
"document",
"->",
"getElement",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"$",
"document",
"instanceof",
"DOMDocument",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Argument 1 passed to %s must be an instance of %s or DOMDocument, %s given'",
",",
"__METHOD__",
",",
"__CLASS__",
",",
"(",
"is_object",
"(",
"$",
"document",
")",
"?",
"get_class",
"(",
"$",
"document",
")",
":",
"gettype",
"(",
"$",
"document",
")",
")",
")",
")",
";",
"}",
"$",
"element",
"=",
"$",
"document",
"->",
"documentElement",
";",
"}",
"if",
"(",
"$",
"element",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getElement",
"(",
")",
"->",
"isSameNode",
"(",
"$",
"element",
")",
";",
"}"
] | Indicates if two documents are the same document.
@param \DiDom\Document|\DOMDocument $document The compared document
@return bool
@throws \InvalidArgumentException if the provided argument is not an instance of \DOMDocument or \DiDom\Document | [
"Indicates",
"if",
"two",
"documents",
"are",
"the",
"same",
"document",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Document.php#L607-L624 | train |
Imangazaliev/DiDOM | src/DiDom/ClassAttribute.php | ClassAttribute.parseClassAttribute | protected function parseClassAttribute()
{
if (!$this->element->hasAttribute('class')) {
// possible if class attribute has been removed
if ($this->classesString !== '') {
$this->classesString = '';
$this->classes = [];
}
return;
}
// if class attribute is not changed
if ($this->element->getAttribute('class') === $this->classesString) {
return;
}
// save class attribute as is (without trimming)
$this->classesString = $this->element->getAttribute('class');
$classesString = trim($this->classesString);
if ($classesString === '') {
$this->classes = [];
return;
}
$classes = explode(' ', $classesString);
$classes = array_map('trim', $classes);
$classes = array_filter($classes);
$classes = array_unique($classes);
$this->classes = array_values($classes);
} | php | protected function parseClassAttribute()
{
if (!$this->element->hasAttribute('class')) {
// possible if class attribute has been removed
if ($this->classesString !== '') {
$this->classesString = '';
$this->classes = [];
}
return;
}
// if class attribute is not changed
if ($this->element->getAttribute('class') === $this->classesString) {
return;
}
// save class attribute as is (without trimming)
$this->classesString = $this->element->getAttribute('class');
$classesString = trim($this->classesString);
if ($classesString === '') {
$this->classes = [];
return;
}
$classes = explode(' ', $classesString);
$classes = array_map('trim', $classes);
$classes = array_filter($classes);
$classes = array_unique($classes);
$this->classes = array_values($classes);
} | [
"protected",
"function",
"parseClassAttribute",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"element",
"->",
"hasAttribute",
"(",
"'class'",
")",
")",
"{",
"// possible if class attribute has been removed",
"if",
"(",
"$",
"this",
"->",
"classesString",
"!==",
"''",
")",
"{",
"$",
"this",
"->",
"classesString",
"=",
"''",
";",
"$",
"this",
"->",
"classes",
"=",
"[",
"]",
";",
"}",
"return",
";",
"}",
"// if class attribute is not changed",
"if",
"(",
"$",
"this",
"->",
"element",
"->",
"getAttribute",
"(",
"'class'",
")",
"===",
"$",
"this",
"->",
"classesString",
")",
"{",
"return",
";",
"}",
"// save class attribute as is (without trimming)",
"$",
"this",
"->",
"classesString",
"=",
"$",
"this",
"->",
"element",
"->",
"getAttribute",
"(",
"'class'",
")",
";",
"$",
"classesString",
"=",
"trim",
"(",
"$",
"this",
"->",
"classesString",
")",
";",
"if",
"(",
"$",
"classesString",
"===",
"''",
")",
"{",
"$",
"this",
"->",
"classes",
"=",
"[",
"]",
";",
"return",
";",
"}",
"$",
"classes",
"=",
"explode",
"(",
"' '",
",",
"$",
"classesString",
")",
";",
"$",
"classes",
"=",
"array_map",
"(",
"'trim'",
",",
"$",
"classes",
")",
";",
"$",
"classes",
"=",
"array_filter",
"(",
"$",
"classes",
")",
";",
"$",
"classes",
"=",
"array_unique",
"(",
"$",
"classes",
")",
";",
"$",
"this",
"->",
"classes",
"=",
"array_values",
"(",
"$",
"classes",
")",
";",
"}"
] | Parses class attribute of the element. | [
"Parses",
"class",
"attribute",
"of",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/ClassAttribute.php#L47-L82 | train |
Imangazaliev/DiDOM | src/DiDom/ClassAttribute.php | ClassAttribute.updateClassAttribute | protected function updateClassAttribute()
{
$this->classesString = implode(' ', $this->classes);
$this->element->setAttribute('class', $this->classesString);
} | php | protected function updateClassAttribute()
{
$this->classesString = implode(' ', $this->classes);
$this->element->setAttribute('class', $this->classesString);
} | [
"protected",
"function",
"updateClassAttribute",
"(",
")",
"{",
"$",
"this",
"->",
"classesString",
"=",
"implode",
"(",
"' '",
",",
"$",
"this",
"->",
"classes",
")",
";",
"$",
"this",
"->",
"element",
"->",
"setAttribute",
"(",
"'class'",
",",
"$",
"this",
"->",
"classesString",
")",
";",
"}"
] | Updates class attribute of the element. | [
"Updates",
"class",
"attribute",
"of",
"the",
"element",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/ClassAttribute.php#L87-L92 | train |
Imangazaliev/DiDOM | src/DiDom/Query.php | Query.convertPseudo | protected static function convertPseudo($pseudo, &$tagName, array $parameters = [])
{
switch ($pseudo) {
case 'first-child':
return 'position() = 1';
break;
case 'last-child':
return 'position() = last()';
break;
case 'nth-child':
$xpath = sprintf('(name()="%s") and (%s)', $tagName, self::convertNthExpression($parameters[0]));
$tagName = '*';
return $xpath;
break;
case 'contains':
$string = trim($parameters[0], '\'"');
if (count($parameters) === 1) {
return self::convertContains($string);
}
if ($parameters[1] !== 'true' && $parameters[1] !== 'false') {
throw new InvalidSelectorException(sprintf('Parameter 2 of "contains" pseudo-class must be equal true or false, "%s" given', $parameters[1]));
}
$caseSensitive = $parameters[1] === 'true';
if (count($parameters) === 2) {
return self::convertContains($string, $caseSensitive);
}
if ($parameters[2] !== 'true' && $parameters[2] !== 'false') {
throw new InvalidSelectorException(sprintf('Parameter 3 of "contains" pseudo-class must be equal true or false, "%s" given', $parameters[2]));
}
$fullMatch = $parameters[2] === 'true';
return self::convertContains($string, $caseSensitive, $fullMatch);
break;
case 'has':
return self::cssToXpath($parameters[0], './/');
break;
case 'not':
return sprintf('not(self::%s)', self::cssToXpath($parameters[0], ''));
break;
case 'nth-of-type':
return self::convertNthExpression($parameters[0]);
break;
case 'empty':
return 'count(descendant::*) = 0';
break;
case 'not-empty':
return 'count(descendant::*) > 0';
break;
}
throw new InvalidSelectorException(sprintf('Unknown pseudo-class "%s"', $pseudo));
} | php | protected static function convertPseudo($pseudo, &$tagName, array $parameters = [])
{
switch ($pseudo) {
case 'first-child':
return 'position() = 1';
break;
case 'last-child':
return 'position() = last()';
break;
case 'nth-child':
$xpath = sprintf('(name()="%s") and (%s)', $tagName, self::convertNthExpression($parameters[0]));
$tagName = '*';
return $xpath;
break;
case 'contains':
$string = trim($parameters[0], '\'"');
if (count($parameters) === 1) {
return self::convertContains($string);
}
if ($parameters[1] !== 'true' && $parameters[1] !== 'false') {
throw new InvalidSelectorException(sprintf('Parameter 2 of "contains" pseudo-class must be equal true or false, "%s" given', $parameters[1]));
}
$caseSensitive = $parameters[1] === 'true';
if (count($parameters) === 2) {
return self::convertContains($string, $caseSensitive);
}
if ($parameters[2] !== 'true' && $parameters[2] !== 'false') {
throw new InvalidSelectorException(sprintf('Parameter 3 of "contains" pseudo-class must be equal true or false, "%s" given', $parameters[2]));
}
$fullMatch = $parameters[2] === 'true';
return self::convertContains($string, $caseSensitive, $fullMatch);
break;
case 'has':
return self::cssToXpath($parameters[0], './/');
break;
case 'not':
return sprintf('not(self::%s)', self::cssToXpath($parameters[0], ''));
break;
case 'nth-of-type':
return self::convertNthExpression($parameters[0]);
break;
case 'empty':
return 'count(descendant::*) = 0';
break;
case 'not-empty':
return 'count(descendant::*) > 0';
break;
}
throw new InvalidSelectorException(sprintf('Unknown pseudo-class "%s"', $pseudo));
} | [
"protected",
"static",
"function",
"convertPseudo",
"(",
"$",
"pseudo",
",",
"&",
"$",
"tagName",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"switch",
"(",
"$",
"pseudo",
")",
"{",
"case",
"'first-child'",
":",
"return",
"'position() = 1'",
";",
"break",
";",
"case",
"'last-child'",
":",
"return",
"'position() = last()'",
";",
"break",
";",
"case",
"'nth-child'",
":",
"$",
"xpath",
"=",
"sprintf",
"(",
"'(name()=\"%s\") and (%s)'",
",",
"$",
"tagName",
",",
"self",
"::",
"convertNthExpression",
"(",
"$",
"parameters",
"[",
"0",
"]",
")",
")",
";",
"$",
"tagName",
"=",
"'*'",
";",
"return",
"$",
"xpath",
";",
"break",
";",
"case",
"'contains'",
":",
"$",
"string",
"=",
"trim",
"(",
"$",
"parameters",
"[",
"0",
"]",
",",
"'\\'\"'",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parameters",
")",
"===",
"1",
")",
"{",
"return",
"self",
"::",
"convertContains",
"(",
"$",
"string",
")",
";",
"}",
"if",
"(",
"$",
"parameters",
"[",
"1",
"]",
"!==",
"'true'",
"&&",
"$",
"parameters",
"[",
"1",
"]",
"!==",
"'false'",
")",
"{",
"throw",
"new",
"InvalidSelectorException",
"(",
"sprintf",
"(",
"'Parameter 2 of \"contains\" pseudo-class must be equal true or false, \"%s\" given'",
",",
"$",
"parameters",
"[",
"1",
"]",
")",
")",
";",
"}",
"$",
"caseSensitive",
"=",
"$",
"parameters",
"[",
"1",
"]",
"===",
"'true'",
";",
"if",
"(",
"count",
"(",
"$",
"parameters",
")",
"===",
"2",
")",
"{",
"return",
"self",
"::",
"convertContains",
"(",
"$",
"string",
",",
"$",
"caseSensitive",
")",
";",
"}",
"if",
"(",
"$",
"parameters",
"[",
"2",
"]",
"!==",
"'true'",
"&&",
"$",
"parameters",
"[",
"2",
"]",
"!==",
"'false'",
")",
"{",
"throw",
"new",
"InvalidSelectorException",
"(",
"sprintf",
"(",
"'Parameter 3 of \"contains\" pseudo-class must be equal true or false, \"%s\" given'",
",",
"$",
"parameters",
"[",
"2",
"]",
")",
")",
";",
"}",
"$",
"fullMatch",
"=",
"$",
"parameters",
"[",
"2",
"]",
"===",
"'true'",
";",
"return",
"self",
"::",
"convertContains",
"(",
"$",
"string",
",",
"$",
"caseSensitive",
",",
"$",
"fullMatch",
")",
";",
"break",
";",
"case",
"'has'",
":",
"return",
"self",
"::",
"cssToXpath",
"(",
"$",
"parameters",
"[",
"0",
"]",
",",
"'.//'",
")",
";",
"break",
";",
"case",
"'not'",
":",
"return",
"sprintf",
"(",
"'not(self::%s)'",
",",
"self",
"::",
"cssToXpath",
"(",
"$",
"parameters",
"[",
"0",
"]",
",",
"''",
")",
")",
";",
"break",
";",
"case",
"'nth-of-type'",
":",
"return",
"self",
"::",
"convertNthExpression",
"(",
"$",
"parameters",
"[",
"0",
"]",
")",
";",
"break",
";",
"case",
"'empty'",
":",
"return",
"'count(descendant::*) = 0'",
";",
"break",
";",
"case",
"'not-empty'",
":",
"return",
"'count(descendant::*) > 0'",
";",
"break",
";",
"}",
"throw",
"new",
"InvalidSelectorException",
"(",
"sprintf",
"(",
"'Unknown pseudo-class \"%s\"'",
",",
"$",
"pseudo",
")",
")",
";",
"}"
] | Converts a CSS pseudo-class into an XPath expression.
@param string $pseudo Pseudo-class
@param string $tagName
@param array $parameters
@return string
@throws InvalidSelectorException if passed an unknown pseudo-class | [
"Converts",
"a",
"CSS",
"pseudo",
"-",
"class",
"into",
"an",
"XPath",
"expression",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Query.php#L205-L263 | train |
Imangazaliev/DiDOM | src/DiDom/Query.php | Query.convertNthExpression | protected static function convertNthExpression($expression)
{
if ($expression === '') {
throw new InvalidSelectorException('nth-child (or nth-last-child) expression must not be empty');
}
if ($expression === 'odd') {
return 'position() mod 2 = 1 and position() >= 1';
}
if ($expression === 'even') {
return 'position() mod 2 = 0 and position() >= 0';
}
if (is_numeric($expression)) {
return sprintf('position() = %d', $expression);
}
if (preg_match("/^(?P<mul>[0-9]?n)(?:(?P<sign>\+|\-)(?P<pos>[0-9]+))?$/is", $expression, $segments)) {
if (isset($segments['mul'])) {
$multiplier = $segments['mul'] === 'n' ? 1 : trim($segments['mul'], 'n');
$sign = (isset($segments['sign']) && $segments['sign'] === '+') ? '-' : '+';
$position = isset($segments['pos']) ? $segments['pos'] : 0;
return sprintf('(position() %s %d) mod %d = 0 and position() >= %d', $sign, $position, $multiplier, $position);
}
}
throw new InvalidSelectorException(sprintf('Invalid nth-child expression "%s"', $expression));
} | php | protected static function convertNthExpression($expression)
{
if ($expression === '') {
throw new InvalidSelectorException('nth-child (or nth-last-child) expression must not be empty');
}
if ($expression === 'odd') {
return 'position() mod 2 = 1 and position() >= 1';
}
if ($expression === 'even') {
return 'position() mod 2 = 0 and position() >= 0';
}
if (is_numeric($expression)) {
return sprintf('position() = %d', $expression);
}
if (preg_match("/^(?P<mul>[0-9]?n)(?:(?P<sign>\+|\-)(?P<pos>[0-9]+))?$/is", $expression, $segments)) {
if (isset($segments['mul'])) {
$multiplier = $segments['mul'] === 'n' ? 1 : trim($segments['mul'], 'n');
$sign = (isset($segments['sign']) && $segments['sign'] === '+') ? '-' : '+';
$position = isset($segments['pos']) ? $segments['pos'] : 0;
return sprintf('(position() %s %d) mod %d = 0 and position() >= %d', $sign, $position, $multiplier, $position);
}
}
throw new InvalidSelectorException(sprintf('Invalid nth-child expression "%s"', $expression));
} | [
"protected",
"static",
"function",
"convertNthExpression",
"(",
"$",
"expression",
")",
"{",
"if",
"(",
"$",
"expression",
"===",
"''",
")",
"{",
"throw",
"new",
"InvalidSelectorException",
"(",
"'nth-child (or nth-last-child) expression must not be empty'",
")",
";",
"}",
"if",
"(",
"$",
"expression",
"===",
"'odd'",
")",
"{",
"return",
"'position() mod 2 = 1 and position() >= 1'",
";",
"}",
"if",
"(",
"$",
"expression",
"===",
"'even'",
")",
"{",
"return",
"'position() mod 2 = 0 and position() >= 0'",
";",
"}",
"if",
"(",
"is_numeric",
"(",
"$",
"expression",
")",
")",
"{",
"return",
"sprintf",
"(",
"'position() = %d'",
",",
"$",
"expression",
")",
";",
"}",
"if",
"(",
"preg_match",
"(",
"\"/^(?P<mul>[0-9]?n)(?:(?P<sign>\\+|\\-)(?P<pos>[0-9]+))?$/is\"",
",",
"$",
"expression",
",",
"$",
"segments",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"segments",
"[",
"'mul'",
"]",
")",
")",
"{",
"$",
"multiplier",
"=",
"$",
"segments",
"[",
"'mul'",
"]",
"===",
"'n'",
"?",
"1",
":",
"trim",
"(",
"$",
"segments",
"[",
"'mul'",
"]",
",",
"'n'",
")",
";",
"$",
"sign",
"=",
"(",
"isset",
"(",
"$",
"segments",
"[",
"'sign'",
"]",
")",
"&&",
"$",
"segments",
"[",
"'sign'",
"]",
"===",
"'+'",
")",
"?",
"'-'",
":",
"'+'",
";",
"$",
"position",
"=",
"isset",
"(",
"$",
"segments",
"[",
"'pos'",
"]",
")",
"?",
"$",
"segments",
"[",
"'pos'",
"]",
":",
"0",
";",
"return",
"sprintf",
"(",
"'(position() %s %d) mod %d = 0 and position() >= %d'",
",",
"$",
"sign",
",",
"$",
"position",
",",
"$",
"multiplier",
",",
"$",
"position",
")",
";",
"}",
"}",
"throw",
"new",
"InvalidSelectorException",
"(",
"sprintf",
"(",
"'Invalid nth-child expression \"%s\"'",
",",
"$",
"expression",
")",
")",
";",
"}"
] | Converts nth-expression into an XPath expression.
@param string $expression nth-expression
@return string
@throws InvalidSelectorException if passed nth-child is empty
@throws InvalidSelectorException if passed an unknown nth-child expression | [
"Converts",
"nth",
"-",
"expression",
"into",
"an",
"XPath",
"expression",
"."
] | a8389cc26897f6bb8843363b4ea16e7ef16fb3c3 | https://github.com/Imangazaliev/DiDOM/blob/a8389cc26897f6bb8843363b4ea16e7ef16fb3c3/src/DiDom/Query.php#L389-L418 | train |
dg/rss-php | src/Feed.php | Feed.load | public static function load($url, $user = null, $pass = null)
{
$xml = self::loadXml($url, $user, $pass);
if ($xml->channel) {
return self::fromRss($xml);
} else {
return self::fromAtom($xml);
}
} | php | public static function load($url, $user = null, $pass = null)
{
$xml = self::loadXml($url, $user, $pass);
if ($xml->channel) {
return self::fromRss($xml);
} else {
return self::fromAtom($xml);
}
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"url",
",",
"$",
"user",
"=",
"null",
",",
"$",
"pass",
"=",
"null",
")",
"{",
"$",
"xml",
"=",
"self",
"::",
"loadXml",
"(",
"$",
"url",
",",
"$",
"user",
",",
"$",
"pass",
")",
";",
"if",
"(",
"$",
"xml",
"->",
"channel",
")",
"{",
"return",
"self",
"::",
"fromRss",
"(",
"$",
"xml",
")",
";",
"}",
"else",
"{",
"return",
"self",
"::",
"fromAtom",
"(",
"$",
"xml",
")",
";",
"}",
"}"
] | Loads RSS or Atom feed.
@param string
@param string
@param string
@return Feed
@throws FeedException | [
"Loads",
"RSS",
"or",
"Atom",
"feed",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L30-L38 | train |
dg/rss-php | src/Feed.php | Feed.loadRss | public static function loadRss($url, $user = null, $pass = null)
{
return self::fromRss(self::loadXml($url, $user, $pass));
} | php | public static function loadRss($url, $user = null, $pass = null)
{
return self::fromRss(self::loadXml($url, $user, $pass));
} | [
"public",
"static",
"function",
"loadRss",
"(",
"$",
"url",
",",
"$",
"user",
"=",
"null",
",",
"$",
"pass",
"=",
"null",
")",
"{",
"return",
"self",
"::",
"fromRss",
"(",
"self",
"::",
"loadXml",
"(",
"$",
"url",
",",
"$",
"user",
",",
"$",
"pass",
")",
")",
";",
"}"
] | Loads RSS feed.
@param string RSS feed URL
@param string optional user name
@param string optional password
@return Feed
@throws FeedException | [
"Loads",
"RSS",
"feed",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L49-L52 | train |
dg/rss-php | src/Feed.php | Feed.loadAtom | public static function loadAtom($url, $user = null, $pass = null)
{
return self::fromAtom(self::loadXml($url, $user, $pass));
} | php | public static function loadAtom($url, $user = null, $pass = null)
{
return self::fromAtom(self::loadXml($url, $user, $pass));
} | [
"public",
"static",
"function",
"loadAtom",
"(",
"$",
"url",
",",
"$",
"user",
"=",
"null",
",",
"$",
"pass",
"=",
"null",
")",
"{",
"return",
"self",
"::",
"fromAtom",
"(",
"self",
"::",
"loadXml",
"(",
"$",
"url",
",",
"$",
"user",
",",
"$",
"pass",
")",
")",
";",
"}"
] | Loads Atom feed.
@param string Atom feed URL
@param string optional user name
@param string optional password
@return Feed
@throws FeedException | [
"Loads",
"Atom",
"feed",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L63-L66 | train |
dg/rss-php | src/Feed.php | Feed.toArray | public function toArray(SimpleXMLElement $xml = null)
{
if ($xml === null) {
$xml = $this->xml;
}
if (!$xml->children()) {
return (string) $xml;
}
$arr = array();
foreach ($xml->children() as $tag => $child) {
if (count($xml->$tag) === 1) {
$arr[$tag] = $this->toArray($child);
} else {
$arr[$tag][] = $this->toArray($child);
}
}
return $arr;
} | php | public function toArray(SimpleXMLElement $xml = null)
{
if ($xml === null) {
$xml = $this->xml;
}
if (!$xml->children()) {
return (string) $xml;
}
$arr = array();
foreach ($xml->children() as $tag => $child) {
if (count($xml->$tag) === 1) {
$arr[$tag] = $this->toArray($child);
} else {
$arr[$tag][] = $this->toArray($child);
}
}
return $arr;
} | [
"public",
"function",
"toArray",
"(",
"SimpleXMLElement",
"$",
"xml",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"xml",
"===",
"null",
")",
"{",
"$",
"xml",
"=",
"$",
"this",
"->",
"xml",
";",
"}",
"if",
"(",
"!",
"$",
"xml",
"->",
"children",
"(",
")",
")",
"{",
"return",
"(",
"string",
")",
"$",
"xml",
";",
"}",
"$",
"arr",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"xml",
"->",
"children",
"(",
")",
"as",
"$",
"tag",
"=>",
"$",
"child",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"xml",
"->",
"$",
"tag",
")",
"===",
"1",
")",
"{",
"$",
"arr",
"[",
"$",
"tag",
"]",
"=",
"$",
"this",
"->",
"toArray",
"(",
"$",
"child",
")",
";",
"}",
"else",
"{",
"$",
"arr",
"[",
"$",
"tag",
"]",
"[",
"]",
"=",
"$",
"this",
"->",
"toArray",
"(",
"$",
"child",
")",
";",
"}",
"}",
"return",
"$",
"arr",
";",
"}"
] | Converts a SimpleXMLElement into an array.
@param SimpleXMLElement
@return array | [
"Converts",
"a",
"SimpleXMLElement",
"into",
"an",
"array",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L140-L160 | train |
dg/rss-php | src/Feed.php | Feed.loadXml | private static function loadXml($url, $user, $pass)
{
$e = self::$cacheExpire;
$cacheFile = self::$cacheDir . '/feed.' . md5(serialize(func_get_args())) . '.xml';
if (self::$cacheDir
&& (time() - @filemtime($cacheFile) <= (is_string($e) ? strtotime($e) - time() : $e))
&& $data = @file_get_contents($cacheFile)
) {
// ok
} elseif ($data = trim(self::httpRequest($url, $user, $pass))) {
if (self::$cacheDir) {
file_put_contents($cacheFile, $data);
}
} elseif (self::$cacheDir && $data = @file_get_contents($cacheFile)) {
// ok
} else {
throw new FeedException('Cannot load feed.');
}
return new SimpleXMLElement($data, LIBXML_NOWARNING | LIBXML_NOERROR);
} | php | private static function loadXml($url, $user, $pass)
{
$e = self::$cacheExpire;
$cacheFile = self::$cacheDir . '/feed.' . md5(serialize(func_get_args())) . '.xml';
if (self::$cacheDir
&& (time() - @filemtime($cacheFile) <= (is_string($e) ? strtotime($e) - time() : $e))
&& $data = @file_get_contents($cacheFile)
) {
// ok
} elseif ($data = trim(self::httpRequest($url, $user, $pass))) {
if (self::$cacheDir) {
file_put_contents($cacheFile, $data);
}
} elseif (self::$cacheDir && $data = @file_get_contents($cacheFile)) {
// ok
} else {
throw new FeedException('Cannot load feed.');
}
return new SimpleXMLElement($data, LIBXML_NOWARNING | LIBXML_NOERROR);
} | [
"private",
"static",
"function",
"loadXml",
"(",
"$",
"url",
",",
"$",
"user",
",",
"$",
"pass",
")",
"{",
"$",
"e",
"=",
"self",
"::",
"$",
"cacheExpire",
";",
"$",
"cacheFile",
"=",
"self",
"::",
"$",
"cacheDir",
".",
"'/feed.'",
".",
"md5",
"(",
"serialize",
"(",
"func_get_args",
"(",
")",
")",
")",
".",
"'.xml'",
";",
"if",
"(",
"self",
"::",
"$",
"cacheDir",
"&&",
"(",
"time",
"(",
")",
"-",
"@",
"filemtime",
"(",
"$",
"cacheFile",
")",
"<=",
"(",
"is_string",
"(",
"$",
"e",
")",
"?",
"strtotime",
"(",
"$",
"e",
")",
"-",
"time",
"(",
")",
":",
"$",
"e",
")",
")",
"&&",
"$",
"data",
"=",
"@",
"file_get_contents",
"(",
"$",
"cacheFile",
")",
")",
"{",
"// ok",
"}",
"elseif",
"(",
"$",
"data",
"=",
"trim",
"(",
"self",
"::",
"httpRequest",
"(",
"$",
"url",
",",
"$",
"user",
",",
"$",
"pass",
")",
")",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"cacheDir",
")",
"{",
"file_put_contents",
"(",
"$",
"cacheFile",
",",
"$",
"data",
")",
";",
"}",
"}",
"elseif",
"(",
"self",
"::",
"$",
"cacheDir",
"&&",
"$",
"data",
"=",
"@",
"file_get_contents",
"(",
"$",
"cacheFile",
")",
")",
"{",
"// ok",
"}",
"else",
"{",
"throw",
"new",
"FeedException",
"(",
"'Cannot load feed.'",
")",
";",
"}",
"return",
"new",
"SimpleXMLElement",
"(",
"$",
"data",
",",
"LIBXML_NOWARNING",
"|",
"LIBXML_NOERROR",
")",
";",
"}"
] | Load XML from cache or HTTP.
@param string
@param string
@param string
@return SimpleXMLElement
@throws FeedException | [
"Load",
"XML",
"from",
"cache",
"or",
"HTTP",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L171-L192 | train |
dg/rss-php | src/Feed.php | Feed.adjustNamespaces | private static function adjustNamespaces($el)
{
foreach ($el->getNamespaces(true) as $prefix => $ns) {
$children = $el->children($ns);
foreach ($children as $tag => $content) {
$el->{$prefix . ':' . $tag} = $content;
}
}
} | php | private static function adjustNamespaces($el)
{
foreach ($el->getNamespaces(true) as $prefix => $ns) {
$children = $el->children($ns);
foreach ($children as $tag => $content) {
$el->{$prefix . ':' . $tag} = $content;
}
}
} | [
"private",
"static",
"function",
"adjustNamespaces",
"(",
"$",
"el",
")",
"{",
"foreach",
"(",
"$",
"el",
"->",
"getNamespaces",
"(",
"true",
")",
"as",
"$",
"prefix",
"=>",
"$",
"ns",
")",
"{",
"$",
"children",
"=",
"$",
"el",
"->",
"children",
"(",
"$",
"ns",
")",
";",
"foreach",
"(",
"$",
"children",
"as",
"$",
"tag",
"=>",
"$",
"content",
")",
"{",
"$",
"el",
"->",
"{",
"$",
"prefix",
".",
"':'",
".",
"$",
"tag",
"}",
"=",
"$",
"content",
";",
"}",
"}",
"}"
] | Generates better accessible namespaced tags.
@param SimpleXMLElement
@return void | [
"Generates",
"better",
"accessible",
"namespaced",
"tags",
"."
] | 08622f48dc249961f3d5af90932240c17608190e | https://github.com/dg/rss-php/blob/08622f48dc249961f3d5af90932240c17608190e/src/Feed.php#L237-L245 | train |
reactphp/http | src/Io/IniUtil.php | IniUtil.iniSizeToBytes | public static function iniSizeToBytes($size)
{
if (\is_numeric($size)) {
return (int)$size;
}
$suffix = \strtoupper(\substr($size, -1));
$strippedSize = \substr($size, 0, -1);
if (!\is_numeric($strippedSize)) {
throw new \InvalidArgumentException("$size is not a valid ini size");
}
if ($strippedSize <= 0) {
throw new \InvalidArgumentException("Expect $size to be higher isn't zero or lower");
}
if ($suffix === 'K') {
return $strippedSize * 1024;
}
if ($suffix === 'M') {
return $strippedSize * 1024 * 1024;
}
if ($suffix === 'G') {
return $strippedSize * 1024 * 1024 * 1024;
}
if ($suffix === 'T') {
return $strippedSize * 1024 * 1024 * 1024 * 1024;
}
return (int)$size;
} | php | public static function iniSizeToBytes($size)
{
if (\is_numeric($size)) {
return (int)$size;
}
$suffix = \strtoupper(\substr($size, -1));
$strippedSize = \substr($size, 0, -1);
if (!\is_numeric($strippedSize)) {
throw new \InvalidArgumentException("$size is not a valid ini size");
}
if ($strippedSize <= 0) {
throw new \InvalidArgumentException("Expect $size to be higher isn't zero or lower");
}
if ($suffix === 'K') {
return $strippedSize * 1024;
}
if ($suffix === 'M') {
return $strippedSize * 1024 * 1024;
}
if ($suffix === 'G') {
return $strippedSize * 1024 * 1024 * 1024;
}
if ($suffix === 'T') {
return $strippedSize * 1024 * 1024 * 1024 * 1024;
}
return (int)$size;
} | [
"public",
"static",
"function",
"iniSizeToBytes",
"(",
"$",
"size",
")",
"{",
"if",
"(",
"\\",
"is_numeric",
"(",
"$",
"size",
")",
")",
"{",
"return",
"(",
"int",
")",
"$",
"size",
";",
"}",
"$",
"suffix",
"=",
"\\",
"strtoupper",
"(",
"\\",
"substr",
"(",
"$",
"size",
",",
"-",
"1",
")",
")",
";",
"$",
"strippedSize",
"=",
"\\",
"substr",
"(",
"$",
"size",
",",
"0",
",",
"-",
"1",
")",
";",
"if",
"(",
"!",
"\\",
"is_numeric",
"(",
"$",
"strippedSize",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"$size is not a valid ini size\"",
")",
";",
"}",
"if",
"(",
"$",
"strippedSize",
"<=",
"0",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Expect $size to be higher isn't zero or lower\"",
")",
";",
"}",
"if",
"(",
"$",
"suffix",
"===",
"'K'",
")",
"{",
"return",
"$",
"strippedSize",
"*",
"1024",
";",
"}",
"if",
"(",
"$",
"suffix",
"===",
"'M'",
")",
"{",
"return",
"$",
"strippedSize",
"*",
"1024",
"*",
"1024",
";",
"}",
"if",
"(",
"$",
"suffix",
"===",
"'G'",
")",
"{",
"return",
"$",
"strippedSize",
"*",
"1024",
"*",
"1024",
"*",
"1024",
";",
"}",
"if",
"(",
"$",
"suffix",
"===",
"'T'",
")",
"{",
"return",
"$",
"strippedSize",
"*",
"1024",
"*",
"1024",
"*",
"1024",
"*",
"1024",
";",
"}",
"return",
"(",
"int",
")",
"$",
"size",
";",
"}"
] | Convert a ini like size to a numeric size in bytes.
@param string $size
@return int | [
"Convert",
"a",
"ini",
"like",
"size",
"to",
"a",
"numeric",
"size",
"in",
"bytes",
"."
] | c02fc4bf7b0541130176a669c5e76b4f4e8eb2a9 | https://github.com/reactphp/http/blob/c02fc4bf7b0541130176a669c5e76b4f4e8eb2a9/src/Io/IniUtil.php#L16-L47 | train |
barryvdh/laravel-snappy | src/ImageWrapper.php | ImageWrapper.save | public function save($filename, $overwrite = false)
{
if ($this->html)
{
$this->snappy->generateFromHtml($this->html, $filename, $this->options, $overwrite);
}
elseif ($this->file)
{
$this->snappy->generate($this->file, $filename, $this->options, $overwrite);
}
return $this;
} | php | public function save($filename, $overwrite = false)
{
if ($this->html)
{
$this->snappy->generateFromHtml($this->html, $filename, $this->options, $overwrite);
}
elseif ($this->file)
{
$this->snappy->generate($this->file, $filename, $this->options, $overwrite);
}
return $this;
} | [
"public",
"function",
"save",
"(",
"$",
"filename",
",",
"$",
"overwrite",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"html",
")",
"{",
"$",
"this",
"->",
"snappy",
"->",
"generateFromHtml",
"(",
"$",
"this",
"->",
"html",
",",
"$",
"filename",
",",
"$",
"this",
"->",
"options",
",",
"$",
"overwrite",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"file",
")",
"{",
"$",
"this",
"->",
"snappy",
"->",
"generate",
"(",
"$",
"this",
"->",
"file",
",",
"$",
"filename",
",",
"$",
"this",
"->",
"options",
",",
"$",
"overwrite",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Save the image to a file
@param $filename
@return static | [
"Save",
"the",
"image",
"to",
"a",
"file"
] | 02345b4d362c8a50e42953ccadd626dd3dbff24a | https://github.com/barryvdh/laravel-snappy/blob/02345b4d362c8a50e42953ccadd626dd3dbff24a/src/ImageWrapper.php#L117-L130 | train |
barryvdh/laravel-snappy | src/PdfFaker.php | PdfFaker.ensureResponseHasView | protected function ensureResponseHasView()
{
if (! isset($this->view) || ! $this->view instanceof View) {
return PHPUnit::fail('The response is not a view.');
}
return $this;
} | php | protected function ensureResponseHasView()
{
if (! isset($this->view) || ! $this->view instanceof View) {
return PHPUnit::fail('The response is not a view.');
}
return $this;
} | [
"protected",
"function",
"ensureResponseHasView",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"view",
")",
"||",
"!",
"$",
"this",
"->",
"view",
"instanceof",
"View",
")",
"{",
"return",
"PHPUnit",
"::",
"fail",
"(",
"'The response is not a view.'",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Ensure that the response has a view as its original content.
@return $this | [
"Ensure",
"that",
"the",
"response",
"has",
"a",
"view",
"as",
"its",
"original",
"content",
"."
] | 02345b4d362c8a50e42953ccadd626dd3dbff24a | https://github.com/barryvdh/laravel-snappy/blob/02345b4d362c8a50e42953ccadd626dd3dbff24a/src/PdfFaker.php#L30-L37 | train |
barryvdh/laravel-snappy | src/PdfFaker.php | PdfFaker.assertViewHasAll | public function assertViewHasAll(array $bindings)
{
foreach ($bindings as $key => $value) {
if (is_int($key)) {
$this->assertViewHas($value);
} else {
$this->assertViewHas($key, $value);
}
}
return $this;
} | php | public function assertViewHasAll(array $bindings)
{
foreach ($bindings as $key => $value) {
if (is_int($key)) {
$this->assertViewHas($value);
} else {
$this->assertViewHas($key, $value);
}
}
return $this;
} | [
"public",
"function",
"assertViewHasAll",
"(",
"array",
"$",
"bindings",
")",
"{",
"foreach",
"(",
"$",
"bindings",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"key",
")",
")",
"{",
"$",
"this",
"->",
"assertViewHas",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"assertViewHas",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Assert that the response view has a given list of bound data.
@param array $bindings
@return $this | [
"Assert",
"that",
"the",
"response",
"view",
"has",
"a",
"given",
"list",
"of",
"bound",
"data",
"."
] | 02345b4d362c8a50e42953ccadd626dd3dbff24a | https://github.com/barryvdh/laravel-snappy/blob/02345b4d362c8a50e42953ccadd626dd3dbff24a/src/PdfFaker.php#L78-L89 | train |
barryvdh/laravel-snappy | src/PdfWrapper.php | PdfWrapper.output | public function output()
{
if ($this->html)
{
return $this->snappy->getOutputFromHtml($this->html, $this->options);
}
if ($this->file)
{
return $this->snappy->getOutput($this->file, $this->options);
}
throw new \InvalidArgumentException('PDF Generator requires a html or file in order to produce output.');
} | php | public function output()
{
if ($this->html)
{
return $this->snappy->getOutputFromHtml($this->html, $this->options);
}
if ($this->file)
{
return $this->snappy->getOutput($this->file, $this->options);
}
throw new \InvalidArgumentException('PDF Generator requires a html or file in order to produce output.');
} | [
"public",
"function",
"output",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"html",
")",
"{",
"return",
"$",
"this",
"->",
"snappy",
"->",
"getOutputFromHtml",
"(",
"$",
"this",
"->",
"html",
",",
"$",
"this",
"->",
"options",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"file",
")",
"{",
"return",
"$",
"this",
"->",
"snappy",
"->",
"getOutput",
"(",
"$",
"this",
"->",
"file",
",",
"$",
"this",
"->",
"options",
")",
";",
"}",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'PDF Generator requires a html or file in order to produce output.'",
")",
";",
"}"
] | Output the PDF as a string.
@return string The rendered PDF as string
@throws \InvalidArgumentException | [
"Output",
"the",
"PDF",
"as",
"a",
"string",
"."
] | 02345b4d362c8a50e42953ccadd626dd3dbff24a | https://github.com/barryvdh/laravel-snappy/blob/02345b4d362c8a50e42953ccadd626dd3dbff24a/src/PdfWrapper.php#L172-L185 | train |
yidas/codeigniter-model | src/Model.php | Model.validate | public function validate($attributes=[], $returnData=false)
{
// Data fetched by ORM or input
$data = ($attributes) ? $attributes : $this->_writeProperties;
// Filter first
$data = $this->filter($data);
// ORM re-assign properties
$this->_writeProperties = (!$attributes) ? $data : $this->_writeProperties;
// Get validation rules from function setting
$rules = $this->rules();
// The ORM update will only collect rules with corresponding modified attributes.
if ($this->_selfCondition) {
$newRules = [];
foreach ((array) $rules as $key => $rule) {
if (isset($this->_writeProperties[$rule['field']])) {
// Add into new rules for updating
$newRules[] = $rule;
}
}
// Replace with mapping rules
$rules = $newRules;
}
// Check if has rules
if (empty($rules))
return ($returnData) ? $data : true;
// CodeIgniter form_validation doesn't work with empty array data
if (empty($data))
return false;
// Load CodeIgniter form_validation library for yidas/model namespace, which has no effect on common one
get_instance()->load->library('form_validation', null, 'yidas_model_form_validation');
// Get CodeIgniter validator
$validator = get_instance()->yidas_model_form_validation;
$validator->reset_validation();
$validator->set_data($data);
$validator->set_rules($rules);
// Run Validate
$result = $validator->run();
// Result handle
if ($result===false) {
$this->_errors = $validator->error_array();
return false;
} else {
return ($returnData) ? $data : true;
}
} | php | public function validate($attributes=[], $returnData=false)
{
// Data fetched by ORM or input
$data = ($attributes) ? $attributes : $this->_writeProperties;
// Filter first
$data = $this->filter($data);
// ORM re-assign properties
$this->_writeProperties = (!$attributes) ? $data : $this->_writeProperties;
// Get validation rules from function setting
$rules = $this->rules();
// The ORM update will only collect rules with corresponding modified attributes.
if ($this->_selfCondition) {
$newRules = [];
foreach ((array) $rules as $key => $rule) {
if (isset($this->_writeProperties[$rule['field']])) {
// Add into new rules for updating
$newRules[] = $rule;
}
}
// Replace with mapping rules
$rules = $newRules;
}
// Check if has rules
if (empty($rules))
return ($returnData) ? $data : true;
// CodeIgniter form_validation doesn't work with empty array data
if (empty($data))
return false;
// Load CodeIgniter form_validation library for yidas/model namespace, which has no effect on common one
get_instance()->load->library('form_validation', null, 'yidas_model_form_validation');
// Get CodeIgniter validator
$validator = get_instance()->yidas_model_form_validation;
$validator->reset_validation();
$validator->set_data($data);
$validator->set_rules($rules);
// Run Validate
$result = $validator->run();
// Result handle
if ($result===false) {
$this->_errors = $validator->error_array();
return false;
} else {
return ($returnData) ? $data : true;
}
} | [
"public",
"function",
"validate",
"(",
"$",
"attributes",
"=",
"[",
"]",
",",
"$",
"returnData",
"=",
"false",
")",
"{",
"// Data fetched by ORM or input",
"$",
"data",
"=",
"(",
"$",
"attributes",
")",
"?",
"$",
"attributes",
":",
"$",
"this",
"->",
"_writeProperties",
";",
"// Filter first",
"$",
"data",
"=",
"$",
"this",
"->",
"filter",
"(",
"$",
"data",
")",
";",
"// ORM re-assign properties",
"$",
"this",
"->",
"_writeProperties",
"=",
"(",
"!",
"$",
"attributes",
")",
"?",
"$",
"data",
":",
"$",
"this",
"->",
"_writeProperties",
";",
"// Get validation rules from function setting",
"$",
"rules",
"=",
"$",
"this",
"->",
"rules",
"(",
")",
";",
"// The ORM update will only collect rules with corresponding modified attributes.",
"if",
"(",
"$",
"this",
"->",
"_selfCondition",
")",
"{",
"$",
"newRules",
"=",
"[",
"]",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"rules",
"as",
"$",
"key",
"=>",
"$",
"rule",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_writeProperties",
"[",
"$",
"rule",
"[",
"'field'",
"]",
"]",
")",
")",
"{",
"// Add into new rules for updating",
"$",
"newRules",
"[",
"]",
"=",
"$",
"rule",
";",
"}",
"}",
"// Replace with mapping rules",
"$",
"rules",
"=",
"$",
"newRules",
";",
"}",
"// Check if has rules",
"if",
"(",
"empty",
"(",
"$",
"rules",
")",
")",
"return",
"(",
"$",
"returnData",
")",
"?",
"$",
"data",
":",
"true",
";",
"// CodeIgniter form_validation doesn't work with empty array data",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"return",
"false",
";",
"// Load CodeIgniter form_validation library for yidas/model namespace, which has no effect on common one",
"get_instance",
"(",
")",
"->",
"load",
"->",
"library",
"(",
"'form_validation'",
",",
"null",
",",
"'yidas_model_form_validation'",
")",
";",
"// Get CodeIgniter validator",
"$",
"validator",
"=",
"get_instance",
"(",
")",
"->",
"yidas_model_form_validation",
";",
"$",
"validator",
"->",
"reset_validation",
"(",
")",
";",
"$",
"validator",
"->",
"set_data",
"(",
"$",
"data",
")",
";",
"$",
"validator",
"->",
"set_rules",
"(",
"$",
"rules",
")",
";",
"// Run Validate",
"$",
"result",
"=",
"$",
"validator",
"->",
"run",
"(",
")",
";",
"// Result handle",
"if",
"(",
"$",
"result",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"_errors",
"=",
"$",
"validator",
"->",
"error_array",
"(",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"(",
"$",
"returnData",
")",
"?",
"$",
"data",
":",
"true",
";",
"}",
"}"
] | Performs the data validation with filters
ORM only performs validation for assigned properties.
@param array Data of attributes
@param boolean Return filtered data
@return boolean Result
@return mixed Data after filter ($returnData is true) | [
"Performs",
"the",
"data",
"validation",
"with",
"filters"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L330-L383 | train |
yidas/codeigniter-model | src/Model.php | Model.find | public function find($withAll=false)
{
$instance = (isset($this)) ? $this : new static;
// One time setting reset mechanism
if ($instance->_cleanNextFind === true) {
// Reset alias
$instance->setAlias(null);
} else {
// Turn on clean for next find
$instance->_cleanNextFind = true;
}
// Alias option for FROM
$sqlFrom = ($instance->alias) ? "{$instance->table} AS {$instance->alias}" : $instance->table;
$instance->_dbr->from($sqlFrom);
// WithAll helper
if ($withAll===true) {
$instance->withAll();
}
// Scope condition
$instance->_addGlobalScopeCondition();
// Soft Deleted condition
$instance->_addSoftDeletedCondition();
return $instance->_dbr;
} | php | public function find($withAll=false)
{
$instance = (isset($this)) ? $this : new static;
// One time setting reset mechanism
if ($instance->_cleanNextFind === true) {
// Reset alias
$instance->setAlias(null);
} else {
// Turn on clean for next find
$instance->_cleanNextFind = true;
}
// Alias option for FROM
$sqlFrom = ($instance->alias) ? "{$instance->table} AS {$instance->alias}" : $instance->table;
$instance->_dbr->from($sqlFrom);
// WithAll helper
if ($withAll===true) {
$instance->withAll();
}
// Scope condition
$instance->_addGlobalScopeCondition();
// Soft Deleted condition
$instance->_addSoftDeletedCondition();
return $instance->_dbr;
} | [
"public",
"function",
"find",
"(",
"$",
"withAll",
"=",
"false",
")",
"{",
"$",
"instance",
"=",
"(",
"isset",
"(",
"$",
"this",
")",
")",
"?",
"$",
"this",
":",
"new",
"static",
";",
"// One time setting reset mechanism",
"if",
"(",
"$",
"instance",
"->",
"_cleanNextFind",
"===",
"true",
")",
"{",
"// Reset alias",
"$",
"instance",
"->",
"setAlias",
"(",
"null",
")",
";",
"}",
"else",
"{",
"// Turn on clean for next find",
"$",
"instance",
"->",
"_cleanNextFind",
"=",
"true",
";",
"}",
"// Alias option for FROM",
"$",
"sqlFrom",
"=",
"(",
"$",
"instance",
"->",
"alias",
")",
"?",
"\"{$instance->table} AS {$instance->alias}\"",
":",
"$",
"instance",
"->",
"table",
";",
"$",
"instance",
"->",
"_dbr",
"->",
"from",
"(",
"$",
"sqlFrom",
")",
";",
"// WithAll helper",
"if",
"(",
"$",
"withAll",
"===",
"true",
")",
"{",
"$",
"instance",
"->",
"withAll",
"(",
")",
";",
"}",
"// Scope condition",
"$",
"instance",
"->",
"_addGlobalScopeCondition",
"(",
")",
";",
"// Soft Deleted condition",
"$",
"instance",
"->",
"_addSoftDeletedCondition",
"(",
")",
";",
"return",
"$",
"instance",
"->",
"_dbr",
";",
"}"
] | Create an existent CI Query Builder instance with Model features for query purpose.
@param boolean $withAll withAll() switch helper
@return object CI_DB_query_builder
@example
$posts = $this->PostModel->find()
->where('is_public', '1')
->limit(0,25)
->order_by('id')
->get()
->result_array();
@example
// Without all featured conditions for next find()
$posts = $this->PostModel->find(true)
->where('is_deleted', '1')
->get()
->result_array();
// This is equal to withAll() method
$this->PostModel->withAll()->find(); | [
"Create",
"an",
"existent",
"CI",
"Query",
"Builder",
"instance",
"with",
"Model",
"features",
"for",
"query",
"purpose",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L485-L515 | train |
yidas/codeigniter-model | src/Model.php | Model.findOne | public static function findOne($condition=[])
{
$instance = (isset($this)) ? $this : new static;
$record = $instance->_findByCondition($condition)
->limit(1)
->get()->row_array();
// Record check
if (!$record) {
return $record;
}
return $instance->createActiveRecord($record, $record[$instance->primaryKey]);
} | php | public static function findOne($condition=[])
{
$instance = (isset($this)) ? $this : new static;
$record = $instance->_findByCondition($condition)
->limit(1)
->get()->row_array();
// Record check
if (!$record) {
return $record;
}
return $instance->createActiveRecord($record, $record[$instance->primaryKey]);
} | [
"public",
"static",
"function",
"findOne",
"(",
"$",
"condition",
"=",
"[",
"]",
")",
"{",
"$",
"instance",
"=",
"(",
"isset",
"(",
"$",
"this",
")",
")",
"?",
"$",
"this",
":",
"new",
"static",
";",
"$",
"record",
"=",
"$",
"instance",
"->",
"_findByCondition",
"(",
"$",
"condition",
")",
"->",
"limit",
"(",
"1",
")",
"->",
"get",
"(",
")",
"->",
"row_array",
"(",
")",
";",
"// Record check",
"if",
"(",
"!",
"$",
"record",
")",
"{",
"return",
"$",
"record",
";",
"}",
"return",
"$",
"instance",
"->",
"createActiveRecord",
"(",
"$",
"record",
",",
"$",
"record",
"[",
"$",
"instance",
"->",
"primaryKey",
"]",
")",
";",
"}"
] | Return a single active record model instance by a primary key or an array of column values.
@param mixed $condition Refer to _findByCondition() for the explanation of this parameter
@return object ActiveRecord(Model)
@example
$post = $this->Model->findOne(123);
@example
// Query builder ORM usage
$this->Model->find()->where('id', 123);
$this->Model->findOne(); | [
"Return",
"a",
"single",
"active",
"record",
"model",
"instance",
"by",
"a",
"primary",
"key",
"or",
"an",
"array",
"of",
"column",
"values",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L539-L553 | train |
yidas/codeigniter-model | src/Model.php | Model.batchInsert | public function batchInsert($data, $runValidation=true)
{
foreach ($data as $key => &$attributes) {
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
return false;
$this->_attrEventBeforeInsert($attributes);
}
return $this->_db->insert_batch($this->table, $data);
} | php | public function batchInsert($data, $runValidation=true)
{
foreach ($data as $key => &$attributes) {
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
return false;
$this->_attrEventBeforeInsert($attributes);
}
return $this->_db->insert_batch($this->table, $data);
} | [
"public",
"function",
"batchInsert",
"(",
"$",
"data",
",",
"$",
"runValidation",
"=",
"true",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"&",
"$",
"attributes",
")",
"{",
"// Validation",
"if",
"(",
"$",
"runValidation",
"&&",
"false",
"===",
"$",
"attributes",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributes",
",",
"true",
")",
")",
"return",
"false",
";",
"$",
"this",
"->",
"_attrEventBeforeInsert",
"(",
"$",
"attributes",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_db",
"->",
"insert_batch",
"(",
"$",
"this",
"->",
"table",
",",
"$",
"data",
")",
";",
"}"
] | Insert a batch of rows with Timestamps feature into the associated database table using the attribute values of this record.
@param array $data The rows to be batch inserted
@param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record.
@return int Number of rows inserted or FALSE on failure
@example
$result = $this->Model->batchInsert([
['name' => 'Nick Tsai', 'email' => 'myintaer@gmail.com'],
['name' => 'Yidas', 'email' => 'service@yidas.com']
]); | [
"Insert",
"a",
"batch",
"of",
"rows",
"with",
"Timestamps",
"feature",
"into",
"the",
"associated",
"database",
"table",
"using",
"the",
"attribute",
"values",
"of",
"this",
"record",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L661-L673 | train |
yidas/codeigniter-model | src/Model.php | Model.replace | public function replace($attributes, $runValidation=true)
{
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
return false;
$this->_attrEventBeforeInsert($attributes);
return $this->_db->replace($this->table, $attributes);
} | php | public function replace($attributes, $runValidation=true)
{
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
return false;
$this->_attrEventBeforeInsert($attributes);
return $this->_db->replace($this->table, $attributes);
} | [
"public",
"function",
"replace",
"(",
"$",
"attributes",
",",
"$",
"runValidation",
"=",
"true",
")",
"{",
"// Validation",
"if",
"(",
"$",
"runValidation",
"&&",
"false",
"===",
"$",
"attributes",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributes",
",",
"true",
")",
")",
"return",
"false",
";",
"$",
"this",
"->",
"_attrEventBeforeInsert",
"(",
"$",
"attributes",
")",
";",
"return",
"$",
"this",
"->",
"_db",
"->",
"replace",
"(",
"$",
"this",
"->",
"table",
",",
"$",
"attributes",
")",
";",
"}"
] | Replace a row with Timestamps feature into the associated database table using the attribute values of this record.
@param array $attributes
@param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record.
@return bool Result
@example
$result = $this->Model->replace([
'id' => 1,
'name' => 'Nick Tsai',
'email' => 'myintaer@gmail.com',
]); | [
"Replace",
"a",
"row",
"with",
"Timestamps",
"feature",
"into",
"the",
"associated",
"database",
"table",
"using",
"the",
"attribute",
"values",
"of",
"this",
"record",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L698-L707 | train |
yidas/codeigniter-model | src/Model.php | Model.batchUpdate | public function batchUpdate(Array $dataSet, $withAll=false, $maxLength=4*1024*1024, $runValidation=true)
{
$count = 0;
$sqlBatch = '';
foreach ($dataSet as $key => &$each) {
// Data format
list($attributes, $condition) = $each;
// Check attributes
if (!is_array($attributes) || !$attributes)
continue;
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
continue;
// WithAll helper
if ($withAll===true) {
$this->withAll();
}
// Model Condition
$query = $this->_findByCondition($condition);
$attributes = $this->_attrEventBeforeUpdate($attributes);
// Pack query then move it to write DB from read DB
$sql = $this->_dbr->set($attributes)->get_compiled_update();
$this->_dbr->reset_query();
// Last batch check: First single query & Max length
// The first single query needs to be sent ahead to prevent the limitation that PDO transaction could not
// use multiple SQL line in one query, but allows if the multi-line query is behind a single query.
if (($count==0 && $sqlBatch) || strlen($sqlBatch)>=$maxLength) {
// Each batch of query
$result = $this->_db->query($sqlBatch);
$sqlBatch = "";
$count = ($result) ? $count + 1 : $count;
}
// Keep Combining query
$sqlBatch .= "{$sql};\n";
}
// Last batch of query
$result = $this->_db->query($sqlBatch);
return ($result) ? $count + 1 : $count;
} | php | public function batchUpdate(Array $dataSet, $withAll=false, $maxLength=4*1024*1024, $runValidation=true)
{
$count = 0;
$sqlBatch = '';
foreach ($dataSet as $key => &$each) {
// Data format
list($attributes, $condition) = $each;
// Check attributes
if (!is_array($attributes) || !$attributes)
continue;
// Validation
if ($runValidation && false===$attributes=$this->validate($attributes, true))
continue;
// WithAll helper
if ($withAll===true) {
$this->withAll();
}
// Model Condition
$query = $this->_findByCondition($condition);
$attributes = $this->_attrEventBeforeUpdate($attributes);
// Pack query then move it to write DB from read DB
$sql = $this->_dbr->set($attributes)->get_compiled_update();
$this->_dbr->reset_query();
// Last batch check: First single query & Max length
// The first single query needs to be sent ahead to prevent the limitation that PDO transaction could not
// use multiple SQL line in one query, but allows if the multi-line query is behind a single query.
if (($count==0 && $sqlBatch) || strlen($sqlBatch)>=$maxLength) {
// Each batch of query
$result = $this->_db->query($sqlBatch);
$sqlBatch = "";
$count = ($result) ? $count + 1 : $count;
}
// Keep Combining query
$sqlBatch .= "{$sql};\n";
}
// Last batch of query
$result = $this->_db->query($sqlBatch);
return ($result) ? $count + 1 : $count;
} | [
"public",
"function",
"batchUpdate",
"(",
"Array",
"$",
"dataSet",
",",
"$",
"withAll",
"=",
"false",
",",
"$",
"maxLength",
"=",
"4",
"*",
"1024",
"*",
"1024",
",",
"$",
"runValidation",
"=",
"true",
")",
"{",
"$",
"count",
"=",
"0",
";",
"$",
"sqlBatch",
"=",
"''",
";",
"foreach",
"(",
"$",
"dataSet",
"as",
"$",
"key",
"=>",
"&",
"$",
"each",
")",
"{",
"// Data format",
"list",
"(",
"$",
"attributes",
",",
"$",
"condition",
")",
"=",
"$",
"each",
";",
"// Check attributes",
"if",
"(",
"!",
"is_array",
"(",
"$",
"attributes",
")",
"||",
"!",
"$",
"attributes",
")",
"continue",
";",
"// Validation",
"if",
"(",
"$",
"runValidation",
"&&",
"false",
"===",
"$",
"attributes",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributes",
",",
"true",
")",
")",
"continue",
";",
"// WithAll helper",
"if",
"(",
"$",
"withAll",
"===",
"true",
")",
"{",
"$",
"this",
"->",
"withAll",
"(",
")",
";",
"}",
"// Model Condition",
"$",
"query",
"=",
"$",
"this",
"->",
"_findByCondition",
"(",
"$",
"condition",
")",
";",
"$",
"attributes",
"=",
"$",
"this",
"->",
"_attrEventBeforeUpdate",
"(",
"$",
"attributes",
")",
";",
"// Pack query then move it to write DB from read DB",
"$",
"sql",
"=",
"$",
"this",
"->",
"_dbr",
"->",
"set",
"(",
"$",
"attributes",
")",
"->",
"get_compiled_update",
"(",
")",
";",
"$",
"this",
"->",
"_dbr",
"->",
"reset_query",
"(",
")",
";",
"// Last batch check: First single query & Max length",
"// The first single query needs to be sent ahead to prevent the limitation that PDO transaction could not ",
"// use multiple SQL line in one query, but allows if the multi-line query is behind a single query. ",
"if",
"(",
"(",
"$",
"count",
"==",
"0",
"&&",
"$",
"sqlBatch",
")",
"||",
"strlen",
"(",
"$",
"sqlBatch",
")",
">=",
"$",
"maxLength",
")",
"{",
"// Each batch of query",
"$",
"result",
"=",
"$",
"this",
"->",
"_db",
"->",
"query",
"(",
"$",
"sqlBatch",
")",
";",
"$",
"sqlBatch",
"=",
"\"\"",
";",
"$",
"count",
"=",
"(",
"$",
"result",
")",
"?",
"$",
"count",
"+",
"1",
":",
"$",
"count",
";",
"}",
"// Keep Combining query",
"$",
"sqlBatch",
".=",
"\"{$sql};\\n\"",
";",
"}",
"// Last batch of query",
"$",
"result",
"=",
"$",
"this",
"->",
"_db",
"->",
"query",
"(",
"$",
"sqlBatch",
")",
";",
"return",
"(",
"$",
"result",
")",
"?",
"$",
"count",
"+",
"1",
":",
"$",
"count",
";",
"}"
] | Update a batch of update queries into combined query strings.
@param array $dataSet [[[Attributes], [Condition]], ]
@param boolean $withAll withAll() switch helper
@param integer $maxLenth MySQL max_allowed_packet
@param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record.
@return integer Count of successful query pack(s)
@example
$result = $this->Model->batchUpdate([
[['title'=>'A1', 'modified'=>'1'], ['id'=>1]],
[['title'=>'A2', 'modified'=>'1'], ['id'=>2]],
];); | [
"Update",
"a",
"batch",
"of",
"update",
"queries",
"into",
"combined",
"query",
"strings",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L756-L806 | train |
yidas/codeigniter-model | src/Model.php | Model.lockForUpdate | public function lockForUpdate()
{
// Pack query then move it to write DB from read DB for transaction
$sql = $this->_dbr->get_compiled_select();
$this->_dbr->reset_query();
return $this->_db->query("{$sql} FOR UPDATE");
} | php | public function lockForUpdate()
{
// Pack query then move it to write DB from read DB for transaction
$sql = $this->_dbr->get_compiled_select();
$this->_dbr->reset_query();
return $this->_db->query("{$sql} FOR UPDATE");
} | [
"public",
"function",
"lockForUpdate",
"(",
")",
"{",
"// Pack query then move it to write DB from read DB for transaction",
"$",
"sql",
"=",
"$",
"this",
"->",
"_dbr",
"->",
"get_compiled_select",
"(",
")",
";",
"$",
"this",
"->",
"_dbr",
"->",
"reset_query",
"(",
")",
";",
"return",
"$",
"this",
"->",
"_db",
"->",
"query",
"(",
"\"{$sql} FOR UPDATE\"",
")",
";",
"}"
] | Lock the selected rows in the table for updating.
sharedLock locks only for write, lockForUpdate also prevents them from being selected
@example
$this->Model->find()->where('id', 123)
$result = $this->Model->lockForUpdate()->row_array();
@example
// This transaction block will lock selected rows for next same selected
// rows with `FOR UPDATE` lock:
$this->Model->getDB()->trans_start();
$this->Model->find()->where('id', 123)
$result = $this->Model->lockForUpdate()->row_array();
$this->Model->getDB()->trans_complete();
@return object CI_DB_result | [
"Lock",
"the",
"selected",
"rows",
"in",
"the",
"table",
"for",
"updating",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L955-L962 | train |
yidas/codeigniter-model | src/Model.php | Model.sharedLock | public function sharedLock()
{
// Pack query then move it to write DB from read DB for transaction
$sql = $this->_dbr->get_compiled_select();
$this->_dbr->reset_query();
return $this->_db->query("{$sql} LOCK IN SHARE MODE");
} | php | public function sharedLock()
{
// Pack query then move it to write DB from read DB for transaction
$sql = $this->_dbr->get_compiled_select();
$this->_dbr->reset_query();
return $this->_db->query("{$sql} LOCK IN SHARE MODE");
} | [
"public",
"function",
"sharedLock",
"(",
")",
"{",
"// Pack query then move it to write DB from read DB for transaction",
"$",
"sql",
"=",
"$",
"this",
"->",
"_dbr",
"->",
"get_compiled_select",
"(",
")",
";",
"$",
"this",
"->",
"_dbr",
"->",
"reset_query",
"(",
")",
";",
"return",
"$",
"this",
"->",
"_db",
"->",
"query",
"(",
"\"{$sql} LOCK IN SHARE MODE\"",
")",
";",
"}"
] | Share lock the selected rows in the table.
@example
$this->Model->find()->where('id', 123)
$result = $this->Model->sharedLock()->row_array();'
@return object CI_DB_result | [
"Share",
"lock",
"the",
"selected",
"rows",
"in",
"the",
"table",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L973-L980 | train |
yidas/codeigniter-model | src/Model.php | Model.createActiveRecord | public function createActiveRecord($readProperties, $selfCondition)
{
$activeRecord = new static();
// ORM handling
$activeRecord->_readProperties = $readProperties;
// Primary key condition to ensure single query result
$activeRecord->_selfCondition = $selfCondition;
return $activeRecord;
} | php | public function createActiveRecord($readProperties, $selfCondition)
{
$activeRecord = new static();
// ORM handling
$activeRecord->_readProperties = $readProperties;
// Primary key condition to ensure single query result
$activeRecord->_selfCondition = $selfCondition;
return $activeRecord;
} | [
"public",
"function",
"createActiveRecord",
"(",
"$",
"readProperties",
",",
"$",
"selfCondition",
")",
"{",
"$",
"activeRecord",
"=",
"new",
"static",
"(",
")",
";",
"// ORM handling",
"$",
"activeRecord",
"->",
"_readProperties",
"=",
"$",
"readProperties",
";",
"// Primary key condition to ensure single query result ",
"$",
"activeRecord",
"->",
"_selfCondition",
"=",
"$",
"selfCondition",
";",
"return",
"$",
"activeRecord",
";",
"}"
] | New a Active Record from Model by data
@param array $readProperties
@param array $selfCondition
@return object ActiveRecord(Model) | [
"New",
"a",
"Active",
"Record",
"from",
"Model",
"by",
"data"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1034-L1043 | train |
yidas/codeigniter-model | src/Model.php | Model._relationship | protected function _relationship($modelName, $relationship, $foreignKey=null, $localKey=null)
{
/**
* PSR-4 support check
*
* @see https://github.com/yidas/codeigniter-psr4-autoload
*/
if (strpos($modelName, "\\") !== false ) {
$model = new $modelName;
} else {
// Original CodeIgniter 3 model loader
get_instance()->load->model($modelName);
$model = $this->$modelName;
}
$libClass = __CLASS__;
// Check if is using same library
if (!is_subclass_of($model, $libClass)) {
throw new Exception("Model `{$modelName}` does not extend {$libClass}", 500);
}
// Keys
$foreignKey = ($foreignKey) ? $foreignKey : $this->primaryKey;
$localKey = ($localKey) ? $localKey : $this->primaryKey;
$query = $model->find()
->where($foreignKey, $this->$localKey);
// Inject Model name into query builder for ORM relationships
$query->modelName = $modelName;
// Inject relationship type into query builder for ORM relationships
$query->relationship = $relationship;
return $query;
} | php | protected function _relationship($modelName, $relationship, $foreignKey=null, $localKey=null)
{
/**
* PSR-4 support check
*
* @see https://github.com/yidas/codeigniter-psr4-autoload
*/
if (strpos($modelName, "\\") !== false ) {
$model = new $modelName;
} else {
// Original CodeIgniter 3 model loader
get_instance()->load->model($modelName);
$model = $this->$modelName;
}
$libClass = __CLASS__;
// Check if is using same library
if (!is_subclass_of($model, $libClass)) {
throw new Exception("Model `{$modelName}` does not extend {$libClass}", 500);
}
// Keys
$foreignKey = ($foreignKey) ? $foreignKey : $this->primaryKey;
$localKey = ($localKey) ? $localKey : $this->primaryKey;
$query = $model->find()
->where($foreignKey, $this->$localKey);
// Inject Model name into query builder for ORM relationships
$query->modelName = $modelName;
// Inject relationship type into query builder for ORM relationships
$query->relationship = $relationship;
return $query;
} | [
"protected",
"function",
"_relationship",
"(",
"$",
"modelName",
",",
"$",
"relationship",
",",
"$",
"foreignKey",
"=",
"null",
",",
"$",
"localKey",
"=",
"null",
")",
"{",
"/**\n * PSR-4 support check\n * \n * @see https://github.com/yidas/codeigniter-psr4-autoload\n */",
"if",
"(",
"strpos",
"(",
"$",
"modelName",
",",
"\"\\\\\"",
")",
"!==",
"false",
")",
"{",
"$",
"model",
"=",
"new",
"$",
"modelName",
";",
"}",
"else",
"{",
"// Original CodeIgniter 3 model loader",
"get_instance",
"(",
")",
"->",
"load",
"->",
"model",
"(",
"$",
"modelName",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"$",
"modelName",
";",
"}",
"$",
"libClass",
"=",
"__CLASS__",
";",
"// Check if is using same library",
"if",
"(",
"!",
"is_subclass_of",
"(",
"$",
"model",
",",
"$",
"libClass",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Model `{$modelName}` does not extend {$libClass}\"",
",",
"500",
")",
";",
"}",
"// Keys",
"$",
"foreignKey",
"=",
"(",
"$",
"foreignKey",
")",
"?",
"$",
"foreignKey",
":",
"$",
"this",
"->",
"primaryKey",
";",
"$",
"localKey",
"=",
"(",
"$",
"localKey",
")",
"?",
"$",
"localKey",
":",
"$",
"this",
"->",
"primaryKey",
";",
"$",
"query",
"=",
"$",
"model",
"->",
"find",
"(",
")",
"->",
"where",
"(",
"$",
"foreignKey",
",",
"$",
"this",
"->",
"$",
"localKey",
")",
";",
"// Inject Model name into query builder for ORM relationships",
"$",
"query",
"->",
"modelName",
"=",
"$",
"modelName",
";",
"// Inject relationship type into query builder for ORM relationships",
"$",
"query",
"->",
"relationship",
"=",
"$",
"relationship",
";",
"return",
"$",
"query",
";",
"}"
] | Base relationship.
@param string $modelName The model class name of the related record
@param string $relationship
@param string $foreignKey
@param string $localKey
@return object CI_DB_query_builder | [
"Base",
"relationship",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1169-L1206 | train |
yidas/codeigniter-model | src/Model.php | Model.indexBy | public static function indexBy(Array &$array, $key=null, $obj2Array=false)
{
// Use model instance's primary key while no given key
$key = ($key) ?: (new static())->primaryKey;
$tmp = [];
foreach ($array as $row) {
// Array & Object types support
if (is_object($row) && isset($row->$key)) {
$tmp[$row->$key] = ($obj2Array) ? (array)$row : $row;
}
elseif (is_array($row) && isset($row[$key])) {
$tmp[$row[$key]] = $row;
}
}
return $array = $tmp;
} | php | public static function indexBy(Array &$array, $key=null, $obj2Array=false)
{
// Use model instance's primary key while no given key
$key = ($key) ?: (new static())->primaryKey;
$tmp = [];
foreach ($array as $row) {
// Array & Object types support
if (is_object($row) && isset($row->$key)) {
$tmp[$row->$key] = ($obj2Array) ? (array)$row : $row;
}
elseif (is_array($row) && isset($row[$key])) {
$tmp[$row[$key]] = $row;
}
}
return $array = $tmp;
} | [
"public",
"static",
"function",
"indexBy",
"(",
"Array",
"&",
"$",
"array",
",",
"$",
"key",
"=",
"null",
",",
"$",
"obj2Array",
"=",
"false",
")",
"{",
"// Use model instance's primary key while no given key",
"$",
"key",
"=",
"(",
"$",
"key",
")",
"?",
":",
"(",
"new",
"static",
"(",
")",
")",
"->",
"primaryKey",
";",
"$",
"tmp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"row",
")",
"{",
"// Array & Object types support ",
"if",
"(",
"is_object",
"(",
"$",
"row",
")",
"&&",
"isset",
"(",
"$",
"row",
"->",
"$",
"key",
")",
")",
"{",
"$",
"tmp",
"[",
"$",
"row",
"->",
"$",
"key",
"]",
"=",
"(",
"$",
"obj2Array",
")",
"?",
"(",
"array",
")",
"$",
"row",
":",
"$",
"row",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"row",
")",
"&&",
"isset",
"(",
"$",
"row",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"tmp",
"[",
"$",
"row",
"[",
"$",
"key",
"]",
"]",
"=",
"$",
"row",
";",
"}",
"}",
"return",
"$",
"array",
"=",
"$",
"tmp",
";",
"}"
] | Index by Key
@param array $array Array data for handling
@param string $key Array key for index key
@param bool $obj2Array Object converts to array if is object
@return array Result with indexBy Key
@example
$records = $this->Model->findAll();
$this->Model->indexBy($records, 'sn'); | [
"Index",
"by",
"Key"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1230-L1248 | train |
yidas/codeigniter-model | src/Model.php | Model.htmlEncode | public static function htmlEncode($content, $doubleEncode = true)
{
$ci = & get_instance();
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $ci->config->item('charset') ? $ci->config->item('charset') : 'UTF-8', $doubleEncode);
} | php | public static function htmlEncode($content, $doubleEncode = true)
{
$ci = & get_instance();
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $ci->config->item('charset') ? $ci->config->item('charset') : 'UTF-8', $doubleEncode);
} | [
"public",
"static",
"function",
"htmlEncode",
"(",
"$",
"content",
",",
"$",
"doubleEncode",
"=",
"true",
")",
"{",
"$",
"ci",
"=",
"&",
"get_instance",
"(",
")",
";",
"return",
"htmlspecialchars",
"(",
"$",
"content",
",",
"ENT_QUOTES",
"|",
"ENT_SUBSTITUTE",
",",
"$",
"ci",
"->",
"config",
"->",
"item",
"(",
"'charset'",
")",
"?",
"$",
"ci",
"->",
"config",
"->",
"item",
"(",
"'charset'",
")",
":",
"'UTF-8'",
",",
"$",
"doubleEncode",
")",
";",
"}"
] | Encodes special characters into HTML entities.
The [[$this->config->item('charset')]] will be used for encoding.
@param string $content the content to be encoded
@param bool $doubleEncode whether to encode HTML entities in `$content`. If false,
HTML entities in `$content` will not be further encoded.
@return string the encoded content
@see http://www.php.net/manual/en/function.htmlspecialchars.php
@see https://www.yiiframework.com/doc/api/2.0/yii-helpers-basehtml#encode()-detail | [
"Encodes",
"special",
"characters",
"into",
"HTML",
"entities",
"."
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1263-L1268 | train |
yidas/codeigniter-model | src/Model.php | Model._attrEventBeforeInsert | protected function _attrEventBeforeInsert(&$attributes)
{
$this->_formatDate(static::CREATED_AT, $attributes);
// Trigger UPDATED_AT
if ($this->createdWithUpdated) {
$this->_formatDate(static::UPDATED_AT, $attributes);
}
return $attributes;
} | php | protected function _attrEventBeforeInsert(&$attributes)
{
$this->_formatDate(static::CREATED_AT, $attributes);
// Trigger UPDATED_AT
if ($this->createdWithUpdated) {
$this->_formatDate(static::UPDATED_AT, $attributes);
}
return $attributes;
} | [
"protected",
"function",
"_attrEventBeforeInsert",
"(",
"&",
"$",
"attributes",
")",
"{",
"$",
"this",
"->",
"_formatDate",
"(",
"static",
"::",
"CREATED_AT",
",",
"$",
"attributes",
")",
";",
"// Trigger UPDATED_AT",
"if",
"(",
"$",
"this",
"->",
"createdWithUpdated",
")",
"{",
"$",
"this",
"->",
"_formatDate",
"(",
"static",
"::",
"UPDATED_AT",
",",
"$",
"attributes",
")",
";",
"}",
"return",
"$",
"attributes",
";",
"}"
] | Attributes handle function for each Insert
@param array $attributes
@return array Addon $attributes of pointer | [
"Attributes",
"handle",
"function",
"for",
"each",
"Insert"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1304-L1315 | train |
yidas/codeigniter-model | src/Model.php | Model._formatDate | protected function _formatDate($field, &$attributes)
{
if ($this->timestamps && $field) {
switch ($this->dateFormat) {
case 'datetime':
$dateFormat = date("Y-m-d H:i:s");
break;
case 'unixtime':
default:
$dateFormat = time();
break;
}
$attributes[$field] = $dateFormat;
}
return $attributes;
} | php | protected function _formatDate($field, &$attributes)
{
if ($this->timestamps && $field) {
switch ($this->dateFormat) {
case 'datetime':
$dateFormat = date("Y-m-d H:i:s");
break;
case 'unixtime':
default:
$dateFormat = time();
break;
}
$attributes[$field] = $dateFormat;
}
return $attributes;
} | [
"protected",
"function",
"_formatDate",
"(",
"$",
"field",
",",
"&",
"$",
"attributes",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"timestamps",
"&&",
"$",
"field",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"dateFormat",
")",
"{",
"case",
"'datetime'",
":",
"$",
"dateFormat",
"=",
"date",
"(",
"\"Y-m-d H:i:s\"",
")",
";",
"break",
";",
"case",
"'unixtime'",
":",
"default",
":",
"$",
"dateFormat",
"=",
"time",
"(",
")",
";",
"break",
";",
"}",
"$",
"attributes",
"[",
"$",
"field",
"]",
"=",
"$",
"dateFormat",
";",
"}",
"return",
"$",
"attributes",
";",
"}"
] | Format a date for timestamps
@param string Field name
@param array Attributes
@return array Addon $attributes of pointer | [
"Format",
"a",
"date",
"for",
"timestamps"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1419-L1438 | train |
yidas/codeigniter-model | src/Model.php | Model._addSoftDeletedCondition | protected function _addSoftDeletedCondition()
{
if ($this->_withoutSoftDeletedScope) {
// Reset SOFT_DELETED switch
$this->_withoutSoftDeletedScope = false;
}
elseif (static::SOFT_DELETED && isset($this->softDeletedFalseValue)) {
// Add condition
$this->_dbr->where($this->_field(static::SOFT_DELETED),
$this->softDeletedFalseValue);
}
return true;
} | php | protected function _addSoftDeletedCondition()
{
if ($this->_withoutSoftDeletedScope) {
// Reset SOFT_DELETED switch
$this->_withoutSoftDeletedScope = false;
}
elseif (static::SOFT_DELETED && isset($this->softDeletedFalseValue)) {
// Add condition
$this->_dbr->where($this->_field(static::SOFT_DELETED),
$this->softDeletedFalseValue);
}
return true;
} | [
"protected",
"function",
"_addSoftDeletedCondition",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_withoutSoftDeletedScope",
")",
"{",
"// Reset SOFT_DELETED switch",
"$",
"this",
"->",
"_withoutSoftDeletedScope",
"=",
"false",
";",
"}",
"elseif",
"(",
"static",
"::",
"SOFT_DELETED",
"&&",
"isset",
"(",
"$",
"this",
"->",
"softDeletedFalseValue",
")",
")",
"{",
"// Add condition",
"$",
"this",
"->",
"_dbr",
"->",
"where",
"(",
"$",
"this",
"->",
"_field",
"(",
"static",
"::",
"SOFT_DELETED",
")",
",",
"$",
"this",
"->",
"softDeletedFalseValue",
")",
";",
"}",
"return",
"true",
";",
"}"
] | The scope which not been soft deleted
@param bool $skip Skip
@return bool Result | [
"The",
"scope",
"which",
"not",
"been",
"soft",
"deleted"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1446-L1459 | train |
yidas/codeigniter-model | src/Model.php | Model.__isset | public function __isset($name) {
if (isset($this->_writeProperties[$name])) {
return true;
}
return isset($this->_readProperties[$name]);
} | php | public function __isset($name) {
if (isset($this->_writeProperties[$name])) {
return true;
}
return isset($this->_readProperties[$name]);
} | [
"public",
"function",
"__isset",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_writeProperties",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"isset",
"(",
"$",
"this",
"->",
"_readProperties",
"[",
"$",
"name",
"]",
")",
";",
"}"
] | ORM isset property
@param string $name
@return void | [
"ORM",
"isset",
"property"
] | 14cd273bb0620dc0e2993fe924ee37f00301992f | https://github.com/yidas/codeigniter-model/blob/14cd273bb0620dc0e2993fe924ee37f00301992f/src/Model.php#L1627-L1635 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Descriptor/DescriptorAbstract.php | DescriptorAbstract.setLocation | public function setLocation(FileDescriptor $file, $line = 0)
{
$this->setFile($file);
$this->line = $line;
} | php | public function setLocation(FileDescriptor $file, $line = 0)
{
$this->setFile($file);
$this->line = $line;
} | [
"public",
"function",
"setLocation",
"(",
"FileDescriptor",
"$",
"file",
",",
"$",
"line",
"=",
"0",
")",
"{",
"$",
"this",
"->",
"setFile",
"(",
"$",
"file",
")",
";",
"$",
"this",
"->",
"line",
"=",
"$",
"line",
";",
"}"
] | Sets the file and linenumber where this element is at.
@param int $line | [
"Sets",
"the",
"file",
"and",
"linenumber",
"where",
"this",
"element",
"is",
"at",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L200-L204 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Descriptor/DescriptorAbstract.php | DescriptorAbstract.getVersion | public function getVersion()
{
/** @var Collection $version */
$version = $this->getTags()->get('version', new Collection());
if ($version->count() !== 0) {
return $version;
}
$inheritedElement = $this->getInheritedElement();
if ($inheritedElement) {
return $inheritedElement->getVersion();
}
return new Collection();
} | php | public function getVersion()
{
/** @var Collection $version */
$version = $this->getTags()->get('version', new Collection());
if ($version->count() !== 0) {
return $version;
}
$inheritedElement = $this->getInheritedElement();
if ($inheritedElement) {
return $inheritedElement->getVersion();
}
return new Collection();
} | [
"public",
"function",
"getVersion",
"(",
")",
"{",
"/** @var Collection $version */",
"$",
"version",
"=",
"$",
"this",
"->",
"getTags",
"(",
")",
"->",
"get",
"(",
"'version'",
",",
"new",
"Collection",
"(",
")",
")",
";",
"if",
"(",
"$",
"version",
"->",
"count",
"(",
")",
"!==",
"0",
")",
"{",
"return",
"$",
"version",
";",
"}",
"$",
"inheritedElement",
"=",
"$",
"this",
"->",
"getInheritedElement",
"(",
")",
";",
"if",
"(",
"$",
"inheritedElement",
")",
"{",
"return",
"$",
"inheritedElement",
"->",
"getVersion",
"(",
")",
";",
"}",
"return",
"new",
"Collection",
"(",
")",
";",
"}"
] | Returns the versions for this element.
@return Collection | [
"Returns",
"the",
"versions",
"for",
"this",
"element",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L328-L342 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Descriptor/DescriptorAbstract.php | DescriptorAbstract.getCopyright | public function getCopyright()
{
/** @var Collection $copyright */
$copyright = $this->getTags()->get('copyright', new Collection());
if ($copyright->count() !== 0) {
return $copyright;
}
$inheritedElement = $this->getInheritedElement();
if ($inheritedElement) {
return $inheritedElement->getCopyright();
}
return new Collection();
} | php | public function getCopyright()
{
/** @var Collection $copyright */
$copyright = $this->getTags()->get('copyright', new Collection());
if ($copyright->count() !== 0) {
return $copyright;
}
$inheritedElement = $this->getInheritedElement();
if ($inheritedElement) {
return $inheritedElement->getCopyright();
}
return new Collection();
} | [
"public",
"function",
"getCopyright",
"(",
")",
"{",
"/** @var Collection $copyright */",
"$",
"copyright",
"=",
"$",
"this",
"->",
"getTags",
"(",
")",
"->",
"get",
"(",
"'copyright'",
",",
"new",
"Collection",
"(",
")",
")",
";",
"if",
"(",
"$",
"copyright",
"->",
"count",
"(",
")",
"!==",
"0",
")",
"{",
"return",
"$",
"copyright",
";",
"}",
"$",
"inheritedElement",
"=",
"$",
"this",
"->",
"getInheritedElement",
"(",
")",
";",
"if",
"(",
"$",
"inheritedElement",
")",
"{",
"return",
"$",
"inheritedElement",
"->",
"getCopyright",
"(",
")",
";",
"}",
"return",
"new",
"Collection",
"(",
")",
";",
"}"
] | Returns the copyrights for this element.
@return Collection | [
"Returns",
"the",
"copyrights",
"for",
"this",
"element",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L349-L363 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/InternalTag.php | InternalTag.process | public function process(\DOMDocument $xml)
{
$ignoreQry = '//long-description[contains(., "{@internal")]';
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query($ignoreQry);
// either replace it with nothing or with the 'stored' value
$replacement = $this->internalAllowed ? '$1' : '';
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$node->nodeValue = preg_replace('/\{@internal\s(.+?)\}\}/', $replacement, $node->nodeValue);
}
return $xml;
} | php | public function process(\DOMDocument $xml)
{
$ignoreQry = '//long-description[contains(., "{@internal")]';
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query($ignoreQry);
// either replace it with nothing or with the 'stored' value
$replacement = $this->internalAllowed ? '$1' : '';
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$node->nodeValue = preg_replace('/\{@internal\s(.+?)\}\}/', $replacement, $node->nodeValue);
}
return $xml;
} | [
"public",
"function",
"process",
"(",
"\\",
"DOMDocument",
"$",
"xml",
")",
"{",
"$",
"ignoreQry",
"=",
"'//long-description[contains(., \"{@internal\")]'",
";",
"$",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"xml",
")",
";",
"$",
"nodes",
"=",
"$",
"xpath",
"->",
"query",
"(",
"$",
"ignoreQry",
")",
";",
"// either replace it with nothing or with the 'stored' value",
"$",
"replacement",
"=",
"$",
"this",
"->",
"internalAllowed",
"?",
"'$1'",
":",
"''",
";",
"/** @var \\DOMElement $node */",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"nodeValue",
"=",
"preg_replace",
"(",
"'/\\{@internal\\s(.+?)\\}\\}/'",
",",
"$",
"replacement",
",",
"$",
"node",
"->",
"nodeValue",
")",
";",
"}",
"return",
"$",
"xml",
";",
"}"
] | Converts the 'internal' tags in Long Descriptions.
@param \DOMDocument $xml Structure source to apply behaviour onto.
@todo This behaviours actions should be moved to the parser / Reflector builder so that it can be cached
and is available to all writers.
@return \DOMDocument | [
"Converts",
"the",
"internal",
"tags",
"in",
"Long",
"Descriptions",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/InternalTag.php#L46-L62 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Plugin/Scrybe/Converter/Metadata/TableOfContents.php | TableOfContents.offsetSet | public function offsetSet($index, $newval)
{
if (!$newval instanceof TableOfContents\File) {
throw new \InvalidArgumentException('A table of contents may only be filled with File objects');
}
$basename = basename($newval->getFilename());
if (strpos($basename, '.') !== false) {
$basename = substr($basename, 0, strpos($basename, '.'));
}
if (strtolower($basename) === 'index') {
$this->modules[] = $newval;
}
parent::offsetSet($newval->getFilename(), $newval);
} | php | public function offsetSet($index, $newval)
{
if (!$newval instanceof TableOfContents\File) {
throw new \InvalidArgumentException('A table of contents may only be filled with File objects');
}
$basename = basename($newval->getFilename());
if (strpos($basename, '.') !== false) {
$basename = substr($basename, 0, strpos($basename, '.'));
}
if (strtolower($basename) === 'index') {
$this->modules[] = $newval;
}
parent::offsetSet($newval->getFilename(), $newval);
} | [
"public",
"function",
"offsetSet",
"(",
"$",
"index",
",",
"$",
"newval",
")",
"{",
"if",
"(",
"!",
"$",
"newval",
"instanceof",
"TableOfContents",
"\\",
"File",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'A table of contents may only be filled with File objects'",
")",
";",
"}",
"$",
"basename",
"=",
"basename",
"(",
"$",
"newval",
"->",
"getFilename",
"(",
")",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"basename",
",",
"'.'",
")",
"!==",
"false",
")",
"{",
"$",
"basename",
"=",
"substr",
"(",
"$",
"basename",
",",
"0",
",",
"strpos",
"(",
"$",
"basename",
",",
"'.'",
")",
")",
";",
"}",
"if",
"(",
"strtolower",
"(",
"$",
"basename",
")",
"===",
"'index'",
")",
"{",
"$",
"this",
"->",
"modules",
"[",
"]",
"=",
"$",
"newval",
";",
"}",
"parent",
"::",
"offsetSet",
"(",
"$",
"newval",
"->",
"getFilename",
"(",
")",
",",
"$",
"newval",
")",
";",
"}"
] | Override offsetSet to force the use of the relative filename.
@param void $index
@param TableOfContents\File $newval
@throws \InvalidArgumentException if something other than a file is provided. | [
"Override",
"offsetSet",
"to",
"force",
"the",
"use",
"of",
"the",
"relative",
"filename",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Plugin/Scrybe/Converter/Metadata/TableOfContents.php#L49-L65 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Plugin/Scrybe/Template/Twig.php | Twig.setExtension | public function setExtension(string $extension): void
{
if (!preg_match('/^[a-zA-Z0-9]{2,4}$/', $extension)) {
throw new InvalidArgumentException(
'Extension should be only be composed of alphanumeric characters'
. ' and should be at least 2 but no more than 4 characters'
);
}
$this->extension = $extension;
} | php | public function setExtension(string $extension): void
{
if (!preg_match('/^[a-zA-Z0-9]{2,4}$/', $extension)) {
throw new InvalidArgumentException(
'Extension should be only be composed of alphanumeric characters'
. ' and should be at least 2 but no more than 4 characters'
);
}
$this->extension = $extension;
} | [
"public",
"function",
"setExtension",
"(",
"string",
"$",
"extension",
")",
":",
"void",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/^[a-zA-Z0-9]{2,4}$/'",
",",
"$",
"extension",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Extension should be only be composed of alphanumeric characters'",
".",
"' and should be at least 2 but no more than 4 characters'",
")",
";",
"}",
"$",
"this",
"->",
"extension",
"=",
"$",
"extension",
";",
"}"
] | Sets the file extension used to determine the template filename.
The file extension of the destination format needs to be set. This is used to retrieve the correct template.
@param string $extension an extension (thus only containing alphanumeric characters and be between 2 and 4
characters in size).
@throws InvalidArgumentException if the extension does not match the validation restrictions mentioned above. | [
"Sets",
"the",
"file",
"extension",
"used",
"to",
"determine",
"the",
"template",
"filename",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Plugin/Scrybe/Template/Twig.php#L104-L114 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Plugin/Scrybe/Template/Twig.php | Twig.getTemplateFilename | protected function getTemplateFilename()
{
$filename = $this->name . '/layout.' . $this->extension . '.twig';
$template_path = $this->path . DIRECTORY_SEPARATOR . $filename;
if (!file_exists($template_path)) {
throw new \DomainException('Template file "' . $template_path . '" could not be found');
}
return $filename;
} | php | protected function getTemplateFilename()
{
$filename = $this->name . '/layout.' . $this->extension . '.twig';
$template_path = $this->path . DIRECTORY_SEPARATOR . $filename;
if (!file_exists($template_path)) {
throw new \DomainException('Template file "' . $template_path . '" could not be found');
}
return $filename;
} | [
"protected",
"function",
"getTemplateFilename",
"(",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"name",
".",
"'/layout.'",
".",
"$",
"this",
"->",
"extension",
".",
"'.twig'",
";",
"$",
"template_path",
"=",
"$",
"this",
"->",
"path",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"filename",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"template_path",
")",
")",
"{",
"throw",
"new",
"\\",
"DomainException",
"(",
"'Template file \"'",
".",
"$",
"template_path",
".",
"'\" could not be found'",
")",
";",
"}",
"return",
"$",
"filename",
";",
"}"
] | Returns the filename for the template.
The filename is composed of the following components:
- the template base folder
- the template's name
- a path separator
- the literal 'layout' combined with the extension
- and as final extension the literal '.twig'
@throws \DomainException if the template does not exist.
@return string | [
"Returns",
"the",
"filename",
"for",
"the",
"template",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Plugin/Scrybe/Template/Twig.php#L191-L201 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/IgnoreTag.php | IgnoreTag.process | public function process(\DOMDocument $xml)
{
$ignoreQry = '//tag[@name=\'' . $this->tag . '\']';
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query($ignoreQry);
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$remove = $node->parentNode->parentNode;
// sometimes the parent node of the entity-to-be-removed is already
// gone; for instance when a File docblock contains an @internal and
// the underlying class also contains an @internal.
// Because the File Docblock is found sooner, it is removed first.
// Without the following check the application would fatal since
// it cannot find, and then remove, this node from the parent.
if (!isset($remove->parentNode)) {
continue;
}
$remove->parentNode->removeChild($remove);
}
return $xml;
} | php | public function process(\DOMDocument $xml)
{
$ignoreQry = '//tag[@name=\'' . $this->tag . '\']';
$xpath = new \DOMXPath($xml);
$nodes = $xpath->query($ignoreQry);
/** @var \DOMElement $node */
foreach ($nodes as $node) {
$remove = $node->parentNode->parentNode;
// sometimes the parent node of the entity-to-be-removed is already
// gone; for instance when a File docblock contains an @internal and
// the underlying class also contains an @internal.
// Because the File Docblock is found sooner, it is removed first.
// Without the following check the application would fatal since
// it cannot find, and then remove, this node from the parent.
if (!isset($remove->parentNode)) {
continue;
}
$remove->parentNode->removeChild($remove);
}
return $xml;
} | [
"public",
"function",
"process",
"(",
"\\",
"DOMDocument",
"$",
"xml",
")",
"{",
"$",
"ignoreQry",
"=",
"'//tag[@name=\\''",
".",
"$",
"this",
"->",
"tag",
".",
"'\\']'",
";",
"$",
"xpath",
"=",
"new",
"\\",
"DOMXPath",
"(",
"$",
"xml",
")",
";",
"$",
"nodes",
"=",
"$",
"xpath",
"->",
"query",
"(",
"$",
"ignoreQry",
")",
";",
"/** @var \\DOMElement $node */",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"remove",
"=",
"$",
"node",
"->",
"parentNode",
"->",
"parentNode",
";",
"// sometimes the parent node of the entity-to-be-removed is already",
"// gone; for instance when a File docblock contains an @internal and",
"// the underlying class also contains an @internal.",
"// Because the File Docblock is found sooner, it is removed first.",
"// Without the following check the application would fatal since",
"// it cannot find, and then remove, this node from the parent.",
"if",
"(",
"!",
"isset",
"(",
"$",
"remove",
"->",
"parentNode",
")",
")",
"{",
"continue",
";",
"}",
"$",
"remove",
"->",
"parentNode",
"->",
"removeChild",
"(",
"$",
"remove",
")",
";",
"}",
"return",
"$",
"xml",
";",
"}"
] | Removes DocBlocks marked with 'ignore' tag from the structure.
@param \DOMDocument $xml Structure source to apply behaviour onto.
@return \DOMDocument | [
"Removes",
"DocBlocks",
"marked",
"with",
"ignore",
"tag",
"from",
"the",
"structure",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/Plugin/Core/Transformer/Behaviour/Tag/IgnoreTag.php#L32-L57 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/DomainModel/Dsn.php | Dsn.parse | private function parse(string $dsn): void
{
$dsnParts = explode(';', $dsn);
$location = $dsnParts[0];
unset($dsnParts[0]);
$locationParts = parse_url($location);
if ($locationParts === false ||
(array_key_exists('scheme', $locationParts) && \strlen($locationParts['scheme']) === 1)
) {
preg_match(static::WINDOWS_DSN, $dsn, $locationParts);
}
if (! array_key_exists('scheme', $locationParts) ||
($locationParts['scheme'] === '' && array_key_exists('path', $locationParts))
) {
$locationParts['scheme'] = 'file';
$location = 'file://' . $location;
}
if (!filter_var($location, FILTER_VALIDATE_URL) && !preg_match(static::WINDOWS_DSN, $location)) {
throw new InvalidArgumentException(
sprintf('"%s" is not a valid DSN.', $dsn)
);
}
$this->parseDsn($location, $dsnParts);
$this->parseScheme($locationParts);
$this->parseHostAndPath($locationParts);
$this->parsePort($locationParts);
$this->user = $locationParts['user'] ?? '';
$this->password = $locationParts['pass'] ?? '';
$this->parseQuery($locationParts);
$this->parseParameters($dsnParts);
} | php | private function parse(string $dsn): void
{
$dsnParts = explode(';', $dsn);
$location = $dsnParts[0];
unset($dsnParts[0]);
$locationParts = parse_url($location);
if ($locationParts === false ||
(array_key_exists('scheme', $locationParts) && \strlen($locationParts['scheme']) === 1)
) {
preg_match(static::WINDOWS_DSN, $dsn, $locationParts);
}
if (! array_key_exists('scheme', $locationParts) ||
($locationParts['scheme'] === '' && array_key_exists('path', $locationParts))
) {
$locationParts['scheme'] = 'file';
$location = 'file://' . $location;
}
if (!filter_var($location, FILTER_VALIDATE_URL) && !preg_match(static::WINDOWS_DSN, $location)) {
throw new InvalidArgumentException(
sprintf('"%s" is not a valid DSN.', $dsn)
);
}
$this->parseDsn($location, $dsnParts);
$this->parseScheme($locationParts);
$this->parseHostAndPath($locationParts);
$this->parsePort($locationParts);
$this->user = $locationParts['user'] ?? '';
$this->password = $locationParts['pass'] ?? '';
$this->parseQuery($locationParts);
$this->parseParameters($dsnParts);
} | [
"private",
"function",
"parse",
"(",
"string",
"$",
"dsn",
")",
":",
"void",
"{",
"$",
"dsnParts",
"=",
"explode",
"(",
"';'",
",",
"$",
"dsn",
")",
";",
"$",
"location",
"=",
"$",
"dsnParts",
"[",
"0",
"]",
";",
"unset",
"(",
"$",
"dsnParts",
"[",
"0",
"]",
")",
";",
"$",
"locationParts",
"=",
"parse_url",
"(",
"$",
"location",
")",
";",
"if",
"(",
"$",
"locationParts",
"===",
"false",
"||",
"(",
"array_key_exists",
"(",
"'scheme'",
",",
"$",
"locationParts",
")",
"&&",
"\\",
"strlen",
"(",
"$",
"locationParts",
"[",
"'scheme'",
"]",
")",
"===",
"1",
")",
")",
"{",
"preg_match",
"(",
"static",
"::",
"WINDOWS_DSN",
",",
"$",
"dsn",
",",
"$",
"locationParts",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"'scheme'",
",",
"$",
"locationParts",
")",
"||",
"(",
"$",
"locationParts",
"[",
"'scheme'",
"]",
"===",
"''",
"&&",
"array_key_exists",
"(",
"'path'",
",",
"$",
"locationParts",
")",
")",
")",
"{",
"$",
"locationParts",
"[",
"'scheme'",
"]",
"=",
"'file'",
";",
"$",
"location",
"=",
"'file://'",
".",
"$",
"location",
";",
"}",
"if",
"(",
"!",
"filter_var",
"(",
"$",
"location",
",",
"FILTER_VALIDATE_URL",
")",
"&&",
"!",
"preg_match",
"(",
"static",
"::",
"WINDOWS_DSN",
",",
"$",
"location",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"%s\" is not a valid DSN.'",
",",
"$",
"dsn",
")",
")",
";",
"}",
"$",
"this",
"->",
"parseDsn",
"(",
"$",
"location",
",",
"$",
"dsnParts",
")",
";",
"$",
"this",
"->",
"parseScheme",
"(",
"$",
"locationParts",
")",
";",
"$",
"this",
"->",
"parseHostAndPath",
"(",
"$",
"locationParts",
")",
";",
"$",
"this",
"->",
"parsePort",
"(",
"$",
"locationParts",
")",
";",
"$",
"this",
"->",
"user",
"=",
"$",
"locationParts",
"[",
"'user'",
"]",
"??",
"''",
";",
"$",
"this",
"->",
"password",
"=",
"$",
"locationParts",
"[",
"'pass'",
"]",
"??",
"''",
";",
"$",
"this",
"->",
"parseQuery",
"(",
"$",
"locationParts",
")",
";",
"$",
"this",
"->",
"parseParameters",
"(",
"$",
"dsnParts",
")",
";",
"}"
] | Parses the given DSN | [
"Parses",
"the",
"given",
"DSN"
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/DomainModel/Dsn.php#L144-L185 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/DomainModel/Dsn.php | Dsn.parseScheme | private function parseScheme(array $locationParts): void
{
if (! $this->isValidScheme($locationParts['scheme'])) {
throw new InvalidArgumentException(
sprintf('"%s" is not a valid scheme.', $locationParts['scheme'])
);
}
$this->scheme = strtolower($locationParts['scheme']);
} | php | private function parseScheme(array $locationParts): void
{
if (! $this->isValidScheme($locationParts['scheme'])) {
throw new InvalidArgumentException(
sprintf('"%s" is not a valid scheme.', $locationParts['scheme'])
);
}
$this->scheme = strtolower($locationParts['scheme']);
} | [
"private",
"function",
"parseScheme",
"(",
"array",
"$",
"locationParts",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isValidScheme",
"(",
"$",
"locationParts",
"[",
"'scheme'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"%s\" is not a valid scheme.'",
",",
"$",
"locationParts",
"[",
"'scheme'",
"]",
")",
")",
";",
"}",
"$",
"this",
"->",
"scheme",
"=",
"strtolower",
"(",
"$",
"locationParts",
"[",
"'scheme'",
"]",
")",
";",
"}"
] | validates and sets the scheme property
@param string[] $locationParts
@throws InvalidArgumentException | [
"validates",
"and",
"sets",
"the",
"scheme",
"property"
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/DomainModel/Dsn.php#L205-L214 | train |
phpDocumentor/phpDocumentor2 | src/phpDocumentor/DomainModel/Dsn.php | Dsn.isValidScheme | private function isValidScheme(string $scheme): bool
{
$validSchemes = ['file', 'git+http', 'git+https'];
return \in_array(\strtolower($scheme), $validSchemes, true);
} | php | private function isValidScheme(string $scheme): bool
{
$validSchemes = ['file', 'git+http', 'git+https'];
return \in_array(\strtolower($scheme), $validSchemes, true);
} | [
"private",
"function",
"isValidScheme",
"(",
"string",
"$",
"scheme",
")",
":",
"bool",
"{",
"$",
"validSchemes",
"=",
"[",
"'file'",
",",
"'git+http'",
",",
"'git+https'",
"]",
";",
"return",
"\\",
"in_array",
"(",
"\\",
"strtolower",
"(",
"$",
"scheme",
")",
",",
"$",
"validSchemes",
",",
"true",
")",
";",
"}"
] | Validated provided scheme. | [
"Validated",
"provided",
"scheme",
"."
] | 7a835fd03ff40244ff557c3e0ce32239e478def0 | https://github.com/phpDocumentor/phpDocumentor2/blob/7a835fd03ff40244ff557c3e0ce32239e478def0/src/phpDocumentor/DomainModel/Dsn.php#L219-L223 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.