repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.once
|
public function once(string $name, callable $handler, int $priority = 50, array $extraArguments = []): self
{
$this->on($name, $handler, $priority, $extraArguments);
$handlerId = $this->handler->getKey($handler);
$this->listeners[$name][$priority][$handlerId]['once'] = true;
return $this;
}
|
php
|
public function once(string $name, callable $handler, int $priority = 50, array $extraArguments = []): self
{
$this->on($name, $handler, $priority, $extraArguments);
$handlerId = $this->handler->getKey($handler);
$this->listeners[$name][$priority][$handlerId]['once'] = true;
return $this;
}
|
@param string $name
@param callable $handler
@param int $priority
@param array $extraArguments
@return $this
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L64-L71
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.offAll
|
protected function offAll(string $eventName): self
{
$hasEvent = $this->listeners[$eventName] ?? false;
if ($hasEvent) {
unset($this->listeners[$eventName], $this->sorted[$eventName]);
}
return $this;
}
|
php
|
protected function offAll(string $eventName): self
{
$hasEvent = $this->listeners[$eventName] ?? false;
if ($hasEvent) {
unset($this->listeners[$eventName], $this->sorted[$eventName]);
}
return $this;
}
|
@param string $eventName
@return $this
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L78-L86
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.off
|
public function off(string $eventName, callable $handler = null, int $priority = null): self
{
if ($handler === null) {
return $this->offAll($eventName);
}
$priority === null
? $this->offHandlerWithoutPriority($eventName, $handler)
: $this->offHandlerWithPriority($eventName, $handler, $priority);
if (empty($this->listeners[$eventName])) {
unset($this->listeners[$eventName], $this->sorted[$eventName]);
}
return $this;
}
|
php
|
public function off(string $eventName, callable $handler = null, int $priority = null): self
{
if ($handler === null) {
return $this->offAll($eventName);
}
$priority === null
? $this->offHandlerWithoutPriority($eventName, $handler)
: $this->offHandlerWithPriority($eventName, $handler, $priority);
if (empty($this->listeners[$eventName])) {
unset($this->listeners[$eventName], $this->sorted[$eventName]);
}
return $this;
}
|
@param string $eventName
@param callable|null $handler
@param int|null $priority
@return $this
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L95-L110
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.offHandlerWithPriority
|
protected function offHandlerWithPriority(string $eventName, callable $handler, int $priority = 50): self
{
$handlerId = $this->handler->getKey($handler);
if (isset($this->listeners[$eventName][$priority][$handlerId])) {
unset($this->listeners[$eventName][$priority][$handlerId]);
$this->cleanEmptyEvent($eventName, $priority);
}
return $this;
}
|
php
|
protected function offHandlerWithPriority(string $eventName, callable $handler, int $priority = 50): self
{
$handlerId = $this->handler->getKey($handler);
if (isset($this->listeners[$eventName][$priority][$handlerId])) {
unset($this->listeners[$eventName][$priority][$handlerId]);
$this->cleanEmptyEvent($eventName, $priority);
}
return $this;
}
|
@param string $eventName
@param callable $handler
@param int $priority
@return $this
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L119-L129
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.offHandlerWithoutPriority
|
protected function offHandlerWithoutPriority(string $eventName, callable $handler): self
{
$handlerId = $this->handler->getKey($handler);
foreach ($this->listeners[$eventName] as $currentPriority => $handlers) {
foreach ($handlers as $currentHandlerId => $paramsHandler) {
if ($handlerId === $currentHandlerId) {
unset($this->listeners[$eventName][$currentPriority][$handlerId]);
$this->cleanEmptyEvent($eventName, $currentPriority);
}
}
}
return $this;
}
|
php
|
protected function offHandlerWithoutPriority(string $eventName, callable $handler): self
{
$handlerId = $this->handler->getKey($handler);
foreach ($this->listeners[$eventName] as $currentPriority => $handlers) {
foreach ($handlers as $currentHandlerId => $paramsHandler) {
if ($handlerId === $currentHandlerId) {
unset($this->listeners[$eventName][$currentPriority][$handlerId]);
$this->cleanEmptyEvent($eventName, $currentPriority);
}
}
}
return $this;
}
|
@param string $eventName
@param callable $handler
@return $this
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L137-L151
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.trigger
|
protected function trigger(string $name, array $arguments = [], $value = null)
{
$event = $this->listeners[$name] ?? false;
if ($event) {
$this->sortListeners($name);
foreach ($this->listeners[$name] as $handlers) {
foreach ($handlers as $paramsHandler) {
$callArgs = $this->getCallArgs($arguments, $paramsHandler['extraArguments'], $value);
$value = $paramsHandler['handler'](...$callArgs);
$this->offOnce($paramsHandler, $name);
}
}
}
return $value;
}
|
php
|
protected function trigger(string $name, array $arguments = [], $value = null)
{
$event = $this->listeners[$name] ?? false;
if ($event) {
$this->sortListeners($name);
foreach ($this->listeners[$name] as $handlers) {
foreach ($handlers as $paramsHandler) {
$callArgs = $this->getCallArgs($arguments, $paramsHandler['extraArguments'], $value);
$value = $paramsHandler['handler'](...$callArgs);
$this->offOnce($paramsHandler, $name);
}
}
}
return $value;
}
|
@param string $name
@param array $arguments
@param mixed $value
@return mixed
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L171-L186
|
alexpts/php-simple-events
|
src/BaseEvents.php
|
BaseEvents.getCallArgs
|
protected function getCallArgs(array $arguments, array $extraArguments, $value = null): array
{
foreach ($extraArguments as $name => $val) {
$arguments[] = $val;
}
return $arguments;
}
|
php
|
protected function getCallArgs(array $arguments, array $extraArguments, $value = null): array
{
foreach ($extraArguments as $name => $val) {
$arguments[] = $val;
}
return $arguments;
}
|
@param array $arguments
@param array $extraArguments
@param mixed $value
@return array
|
https://github.com/alexpts/php-simple-events/blob/215e47bdd3d8236c230ae96c1ac7ebdd7e569d87/src/BaseEvents.php#L206-L213
|
brick/validation
|
src/Validator/SimValidator.php
|
SimValidator.validate
|
protected function validate(string $value) : void
{
$length = strlen($value);
$minLength = ($this->hasCheckDigit === true) ? 19 : 18;
$maxLength = ($this->hasCheckDigit === false) ? 19 : 20;
if ($length < $minLength || $length > $maxLength) {
$this->addFailureMessage('validator.sim.invalid');
return;
}
if ($this->hasCheckDigit === true || $length === 20) {
if (Luhn::isValid($value)) {
return;
}
} else {
if (ctype_digit($value)) {
return;
}
}
$this->addFailureMessage('validator.sim.invalid');
}
|
php
|
protected function validate(string $value) : void
{
$length = strlen($value);
$minLength = ($this->hasCheckDigit === true) ? 19 : 18;
$maxLength = ($this->hasCheckDigit === false) ? 19 : 20;
if ($length < $minLength || $length > $maxLength) {
$this->addFailureMessage('validator.sim.invalid');
return;
}
if ($this->hasCheckDigit === true || $length === 20) {
if (Luhn::isValid($value)) {
return;
}
} else {
if (ctype_digit($value)) {
return;
}
}
$this->addFailureMessage('validator.sim.invalid');
}
|
{@inheritdoc}
|
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/SimValidator.php#L63-L87
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.getUserSession
|
private function getUserSession(Request $req)
{
// check for a session hijacking attempt via the stored user agent
$session = $this->getSession();
if ($session->get(self::SESSION_USER_AGENT_KEY) !== $req->agent()) {
return false;
}
$userId = $session->get(self::SESSION_USER_ID_KEY);
if ($userId === null) {
return false;
}
// if this is a guest user then just return it now
$userClass = $this->auth->getUserClass();
if ($userId <= 0) {
return new $userClass($userId);
}
// look up the registered user
$user = $userClass::where('id', $userId)->first();
if (!$user) {
return false;
}
// refresh the active session
if ($session->isStarted()) {
// check if the session valid
$sid = $session->getId();
if (!$this->sessionIsValid($sid)) {
return false;
}
$this->refreshSession($sid);
}
// check if the user is 2FA verified
if ($session->get(self::SESSION_2FA_VERIFIED_KEY)) {
$user->markTwoFactorVerified();
}
return $user->markSignedIn();
}
|
php
|
private function getUserSession(Request $req)
{
// check for a session hijacking attempt via the stored user agent
$session = $this->getSession();
if ($session->get(self::SESSION_USER_AGENT_KEY) !== $req->agent()) {
return false;
}
$userId = $session->get(self::SESSION_USER_ID_KEY);
if ($userId === null) {
return false;
}
// if this is a guest user then just return it now
$userClass = $this->auth->getUserClass();
if ($userId <= 0) {
return new $userClass($userId);
}
// look up the registered user
$user = $userClass::where('id', $userId)->first();
if (!$user) {
return false;
}
// refresh the active session
if ($session->isStarted()) {
// check if the session valid
$sid = $session->getId();
if (!$this->sessionIsValid($sid)) {
return false;
}
$this->refreshSession($sid);
}
// check if the user is 2FA verified
if ($session->get(self::SESSION_2FA_VERIFIED_KEY)) {
$user->markTwoFactorVerified();
}
return $user->markSignedIn();
}
|
Tries to get an authenticated user via the current session.
@param Request $req
@return UserInterface|false
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L165-L207
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.createSession
|
private function createSession($sid, $userId, Request $req)
{
$sessionCookie = session_get_cookie_params();
$expires = time() + $sessionCookie['lifetime'];
$session = new ActiveSession();
$session->id = $sid;
$session->user_id = $userId;
$session->ip = $req->ip();
$session->user_agent = $req->agent();
$session->expires = $expires;
$session->save();
return $session;
}
|
php
|
private function createSession($sid, $userId, Request $req)
{
$sessionCookie = session_get_cookie_params();
$expires = time() + $sessionCookie['lifetime'];
$session = new ActiveSession();
$session->id = $sid;
$session->user_id = $userId;
$session->ip = $req->ip();
$session->user_agent = $req->agent();
$session->expires = $expires;
$session->save();
return $session;
}
|
Creates an active session for a user.
@param string $sid session ID
@param int $userId
@param Request $req
@return ActiveSession
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L218-L232
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.refreshSession
|
private function refreshSession($sid)
{
$sessionCookie = session_get_cookie_params();
$expires = time() + $sessionCookie['lifetime'];
$this->getDatabase()
->update('ActiveSessions')
->where('id', $sid)
->values([
'expires' => $expires,
'updated_at' => Utility::unixToDb(time())
])
->execute();
return true;
}
|
php
|
private function refreshSession($sid)
{
$sessionCookie = session_get_cookie_params();
$expires = time() + $sessionCookie['lifetime'];
$this->getDatabase()
->update('ActiveSessions')
->where('id', $sid)
->values([
'expires' => $expires,
'updated_at' => Utility::unixToDb(time())
])
->execute();
return true;
}
|
Refreshes the expiration on an active session.
@param string $sid session ID
@return bool
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L255-L270
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.getUserRememberMe
|
private function getUserRememberMe(Request $req, Response $res)
{
// retrieve and verify the remember me cookie
$cookie = $this->getRememberMeCookie($req);
if (!$cookie) {
return false;
}
$user = $cookie->verify($req, $this->auth);
if (!$user) {
$this->destroyRememberMeCookie($req, $res);
return false;
}
$signedInUser = $this->auth->signInUser($user, 'remember_me');
// generate a new remember me cookie for the next time, using
// the same series
$new = new RememberMeCookie($user->email(),
$req->agent(),
$cookie->getSeries());
$this->sendRememberMeCookie($user, $new, $res);
// mark this session as remembered (could be useful to know)
$this->getSession()->set(self::SESSION_REMEMBERED_KEY, true);
$req->setSession(self::SESSION_REMEMBERED_KEY, true);
return $signedInUser;
}
|
php
|
private function getUserRememberMe(Request $req, Response $res)
{
// retrieve and verify the remember me cookie
$cookie = $this->getRememberMeCookie($req);
if (!$cookie) {
return false;
}
$user = $cookie->verify($req, $this->auth);
if (!$user) {
$this->destroyRememberMeCookie($req, $res);
return false;
}
$signedInUser = $this->auth->signInUser($user, 'remember_me');
// generate a new remember me cookie for the next time, using
// the same series
$new = new RememberMeCookie($user->email(),
$req->agent(),
$cookie->getSeries());
$this->sendRememberMeCookie($user, $new, $res);
// mark this session as remembered (could be useful to know)
$this->getSession()->set(self::SESSION_REMEMBERED_KEY, true);
$req->setSession(self::SESSION_REMEMBERED_KEY, true);
return $signedInUser;
}
|
Tries to get an authenticated user via remember me.
@param Request $req
@param Response $res
@return UserInterface|false
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L313-L342
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.getRememberMeCookie
|
private function getRememberMeCookie(Request $req)
{
$encoded = $req->cookies($this->rememberMeCookieName());
if (!$encoded) {
return false;
}
return RememberMeCookie::decode($encoded);
}
|
php
|
private function getRememberMeCookie(Request $req)
{
$encoded = $req->cookies($this->rememberMeCookieName());
if (!$encoded) {
return false;
}
return RememberMeCookie::decode($encoded);
}
|
Gets the decoded remember me cookie from the request.
@param Request $req
@return RememberMeCookie|false
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L351-L359
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.sendRememberMeCookie
|
private function sendRememberMeCookie(UserInterface $user, RememberMeCookie $cookie, Response $res)
{
// send the cookie with the same properties as the session cookie
$sessionCookie = session_get_cookie_params();
$res->setCookie($this->rememberMeCookieName(),
$cookie->encode(),
$cookie->getExpires(time()),
$sessionCookie['path'],
$sessionCookie['domain'],
$sessionCookie['secure'],
true);
// save the cookie in the DB
$cookie->persist($user);
}
|
php
|
private function sendRememberMeCookie(UserInterface $user, RememberMeCookie $cookie, Response $res)
{
// send the cookie with the same properties as the session cookie
$sessionCookie = session_get_cookie_params();
$res->setCookie($this->rememberMeCookieName(),
$cookie->encode(),
$cookie->getExpires(time()),
$sessionCookie['path'],
$sessionCookie['domain'],
$sessionCookie['secure'],
true);
// save the cookie in the DB
$cookie->persist($user);
}
|
Stores a remember me session cookie on the response.
@param UserInterface $user
@param RememberMeCookie $cookie
@param Response $res
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L368-L382
|
infusephp/auth
|
src/Libs/Storage/SymfonySessionStorage.php
|
SymfonySessionStorage.destroyRememberMeCookie
|
private function destroyRememberMeCookie(Request $req, Response $res)
{
$cookie = $this->getRememberMeCookie($req);
if ($cookie) {
$cookie->destroy();
}
$sessionCookie = session_get_cookie_params();
$res->setCookie($this->rememberMeCookieName(),
'',
time() - 86400,
$sessionCookie['path'],
$sessionCookie['domain'],
$sessionCookie['secure'],
true);
return $this;
}
|
php
|
private function destroyRememberMeCookie(Request $req, Response $res)
{
$cookie = $this->getRememberMeCookie($req);
if ($cookie) {
$cookie->destroy();
}
$sessionCookie = session_get_cookie_params();
$res->setCookie($this->rememberMeCookieName(),
'',
time() - 86400,
$sessionCookie['path'],
$sessionCookie['domain'],
$sessionCookie['secure'],
true);
return $this;
}
|
Destroys the remember me cookie.
@param Request $req
@param Response $res
@return self
|
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L392-L409
|
luoxiaojun1992/lb_framework
|
components/traits/lb/Cookie.php
|
Cookie.setCookie
|
public function setCookie($cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null)
{
if ($this->isSingle()) {
ResponseKit::setCookie($cookie_key, $cookie_value, $expire, $path, $domain, $secure, $httpOnly);
}
}
|
php
|
public function setCookie($cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null)
{
if ($this->isSingle()) {
ResponseKit::setCookie($cookie_key, $cookie_value, $expire, $path, $domain, $secure, $httpOnly);
}
}
|
Set Cookie Value
@param $cookie_key
@param $cookie_value
@param null $expire
@param null $path
@param null $domain
@param null $secure
@param null $httpOnly
|
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Cookie.php#L35-L40
|
luoxiaojun1992/lb_framework
|
components/traits/lb/Cookie.php
|
Cookie.delCookie
|
public function delCookie($cookie_key)
{
if ($this->isSingle()) {
if ($this->getCookie($cookie_key)) {
$this->setCookie($cookie_key, null);
}
}
}
|
php
|
public function delCookie($cookie_key)
{
if ($this->isSingle()) {
if ($this->getCookie($cookie_key)) {
$this->setCookie($cookie_key, null);
}
}
}
|
Delete Cookie
@param $cookie_key
|
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Cookie.php#L47-L54
|
luoxiaojun1992/lb_framework
|
components/traits/lb/Cookie.php
|
Cookie.delCookies
|
public function delCookies($cookie_keys)
{
if ($this->isSingle()) {
foreach ($cookie_keys as $cookie_key) {
$this->delCookie($cookie_key);
}
}
}
|
php
|
public function delCookies($cookie_keys)
{
if ($this->isSingle()) {
foreach ($cookie_keys as $cookie_key) {
$this->delCookie($cookie_key);
}
}
}
|
Delete Multi Cookies
@param $cookie_keys
|
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Cookie.php#L61-L68
|
bennybi/yii2-cza-base
|
widgets/ui/common/grid/GridView.php
|
GridView.initExport
|
protected function initExport() {
if ($this->export === false) {
return;
}
$this->exportConversions = array_replace_recursive(
[
['from' => self::ICON_ACTIVE, 'to' => Yii::t('cza', 'Active')],
['from' => self::ICON_INACTIVE, 'to' => Yii::t('cza', 'Inactive')],
], $this->exportConversions
);
if (!isset($this->export['fontAwesome'])) {
$this->export['fontAwesome'] = false;
}
$isFa = $this->export['fontAwesome'];
$this->export = array_replace_recursive(
[
'label' => '',
'icon' => $isFa ? 'share-square-o' : 'export',
'messages' => [
'allowPopups' => Yii::t(
'cza', 'Disable any popup blockers in your browser to ensure proper download.'
),
'confirmDownload' => Yii::t('cza', 'Ok to proceed?'),
'downloadProgress' => Yii::t('cza', 'Generating the export file. Please wait...'),
'downloadComplete' => Yii::t(
'cza', 'Request submitted! You may safely close this dialog after saving your downloaded file.'
),
],
'options' => ['class' => 'btn btn-default', 'title' => Yii::t('cza', 'Export')],
'menuOptions' => ['class' => 'dropdown-menu dropdown-menu-right '],
], $this->export
);
if (!isset($this->export['header'])) {
$this->export['header'] = '<li role="presentation" class="dropdown-header">' .
Yii::t('cza', 'Export Page Data') . '</li>';
}
if (!isset($this->export['headerAll'])) {
$this->export['headerAll'] = '<li role="presentation" class="dropdown-header">' .
Yii::t('cza', 'Export All Data') . '</li>';
}
$title = empty($this->caption) ? Yii::t('cza', 'Grid Export') : $this->caption;
$pdfHeader = [
'L' => [
'content' => Yii::t('cza', 'Grid Export (PDF)'),
'font-size' => 8,
'color' => '#333333',
],
'C' => [
'content' => $title,
'font-size' => 16,
'color' => '#333333',
],
'R' => [
'content' => Yii::t('cza', 'Generated') . ': ' . date("D, d-M-Y g:i a T"),
'font-size' => 8,
'color' => '#333333',
],
];
$pdfFooter = [
'L' => [
'content' => Yii::t('cza', "© CZA Yii2 Extensions"),
'font-size' => 8,
'font-style' => 'B',
'color' => '#999999',
],
'R' => [
'content' => '[ {PAGENO} ]',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color' => '#333333',
],
'line' => true,
];
$defaultExportConfig = [
self::HTML => [
'label' => Yii::t('cza', 'HTML'),
'icon' => $isFa ? 'file-text' : 'floppy-saved',
'iconOptions' => ['class' => 'text-info'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The HTML export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Hyper Text Markup Language')],
'mime' => 'text/html',
'config' => [
'cssFile' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css',
],
],
self::CSV => [
'label' => Yii::t('cza', 'CSV'),
'icon' => $isFa ? 'file-code-o' : 'floppy-open',
'iconOptions' => ['class' => 'text-primary'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The CSV export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Comma Separated Values')],
'mime' => 'application/csv',
'config' => [
'colDelimiter' => ",",
'rowDelimiter' => "\r\n",
],
],
self::TEXT => [
'label' => Yii::t('cza', 'Text'),
'icon' => $isFa ? 'file-text-o' : 'floppy-save',
'iconOptions' => ['class' => 'text-muted'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The TEXT export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Tab Delimited Text')],
'mime' => 'text/plain',
'config' => [
'colDelimiter' => "\t",
'rowDelimiter' => "\r\n",
],
],
self::EXCEL => [
'label' => Yii::t('cza', 'Excel'),
'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
'iconOptions' => ['class' => 'text-success'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The EXCEL export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Microsoft Excel 95+')],
'mime' => 'application/vnd.ms-excel',
'config' => [
'worksheet' => Yii::t('cza', 'ExportWorksheet'),
'cssFile' => '',
],
],
self::PDF => [
'label' => Yii::t('cza', 'PDF'),
'icon' => $isFa ? 'file-pdf-o' : 'floppy-disk',
'iconOptions' => ['class' => 'text-danger'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The PDF export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Portable Document Format')],
'mime' => 'application/pdf',
'config' => [
'mode' => 'UTF-8',
'format' => 'A4-L',
'destination' => 'D',
'marginTop' => 20,
'marginBottom' => 20,
'cssInline' => '.kv-wrap{padding:20px;}' .
'.kv-align-center{text-align:center;}' .
'.kv-align-left{text-align:left;}' .
'.kv-align-right{text-align:right;}' .
'.kv-align-top{vertical-align:top!important;}' .
'.kv-align-bottom{vertical-align:bottom!important;}' .
'.kv-align-middle{vertical-align:middle!important;}' .
'.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
'.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
'.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
'methods' => [
'SetHeader' => [
['odd' => $pdfHeader, 'even' => $pdfHeader],
],
'SetFooter' => [
['odd' => $pdfFooter, 'even' => $pdfFooter],
],
],
'options' => [
'title' => $title,
'subject' => Yii::t('cza', 'PDF export generated by kartik-v/yii2-grid extension'),
'keywords' => Yii::t('cza', 'grid, export, yii2-grid, pdf'),
],
'contentBefore' => '',
'contentAfter' => '',
],
],
self::JSON => [
'label' => Yii::t('cza', 'JSON'),
'icon' => $isFa ? 'file-code-o' : 'floppy-open',
'iconOptions' => ['class' => 'text-warning'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The JSON export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'JavaScript Object Notation')],
'mime' => 'application/json',
'config' => [
'colHeads' => [],
'slugColHeads' => false,
'jsonReplacer' => new JsExpression("function(k,v){return typeof(v)==='string'?$.trim(v):v}"),
'indentSpace' => 4,
],
],
];
// Remove PDF if dependency is not loaded.
if (!class_exists("\\kartik\\mpdf\\Pdf")) {
unset($defaultExportConfig[self::PDF]);
}
$this->exportConfig = self::parseExportConfig($this->exportConfig, $defaultExportConfig);
}
|
php
|
protected function initExport() {
if ($this->export === false) {
return;
}
$this->exportConversions = array_replace_recursive(
[
['from' => self::ICON_ACTIVE, 'to' => Yii::t('cza', 'Active')],
['from' => self::ICON_INACTIVE, 'to' => Yii::t('cza', 'Inactive')],
], $this->exportConversions
);
if (!isset($this->export['fontAwesome'])) {
$this->export['fontAwesome'] = false;
}
$isFa = $this->export['fontAwesome'];
$this->export = array_replace_recursive(
[
'label' => '',
'icon' => $isFa ? 'share-square-o' : 'export',
'messages' => [
'allowPopups' => Yii::t(
'cza', 'Disable any popup blockers in your browser to ensure proper download.'
),
'confirmDownload' => Yii::t('cza', 'Ok to proceed?'),
'downloadProgress' => Yii::t('cza', 'Generating the export file. Please wait...'),
'downloadComplete' => Yii::t(
'cza', 'Request submitted! You may safely close this dialog after saving your downloaded file.'
),
],
'options' => ['class' => 'btn btn-default', 'title' => Yii::t('cza', 'Export')],
'menuOptions' => ['class' => 'dropdown-menu dropdown-menu-right '],
], $this->export
);
if (!isset($this->export['header'])) {
$this->export['header'] = '<li role="presentation" class="dropdown-header">' .
Yii::t('cza', 'Export Page Data') . '</li>';
}
if (!isset($this->export['headerAll'])) {
$this->export['headerAll'] = '<li role="presentation" class="dropdown-header">' .
Yii::t('cza', 'Export All Data') . '</li>';
}
$title = empty($this->caption) ? Yii::t('cza', 'Grid Export') : $this->caption;
$pdfHeader = [
'L' => [
'content' => Yii::t('cza', 'Grid Export (PDF)'),
'font-size' => 8,
'color' => '#333333',
],
'C' => [
'content' => $title,
'font-size' => 16,
'color' => '#333333',
],
'R' => [
'content' => Yii::t('cza', 'Generated') . ': ' . date("D, d-M-Y g:i a T"),
'font-size' => 8,
'color' => '#333333',
],
];
$pdfFooter = [
'L' => [
'content' => Yii::t('cza', "© CZA Yii2 Extensions"),
'font-size' => 8,
'font-style' => 'B',
'color' => '#999999',
],
'R' => [
'content' => '[ {PAGENO} ]',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color' => '#333333',
],
'line' => true,
];
$defaultExportConfig = [
self::HTML => [
'label' => Yii::t('cza', 'HTML'),
'icon' => $isFa ? 'file-text' : 'floppy-saved',
'iconOptions' => ['class' => 'text-info'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The HTML export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Hyper Text Markup Language')],
'mime' => 'text/html',
'config' => [
'cssFile' => 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css',
],
],
self::CSV => [
'label' => Yii::t('cza', 'CSV'),
'icon' => $isFa ? 'file-code-o' : 'floppy-open',
'iconOptions' => ['class' => 'text-primary'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The CSV export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Comma Separated Values')],
'mime' => 'application/csv',
'config' => [
'colDelimiter' => ",",
'rowDelimiter' => "\r\n",
],
],
self::TEXT => [
'label' => Yii::t('cza', 'Text'),
'icon' => $isFa ? 'file-text-o' : 'floppy-save',
'iconOptions' => ['class' => 'text-muted'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The TEXT export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Tab Delimited Text')],
'mime' => 'text/plain',
'config' => [
'colDelimiter' => "\t",
'rowDelimiter' => "\r\n",
],
],
self::EXCEL => [
'label' => Yii::t('cza', 'Excel'),
'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
'iconOptions' => ['class' => 'text-success'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The EXCEL export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Microsoft Excel 95+')],
'mime' => 'application/vnd.ms-excel',
'config' => [
'worksheet' => Yii::t('cza', 'ExportWorksheet'),
'cssFile' => '',
],
],
self::PDF => [
'label' => Yii::t('cza', 'PDF'),
'icon' => $isFa ? 'file-pdf-o' : 'floppy-disk',
'iconOptions' => ['class' => 'text-danger'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The PDF export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'Portable Document Format')],
'mime' => 'application/pdf',
'config' => [
'mode' => 'UTF-8',
'format' => 'A4-L',
'destination' => 'D',
'marginTop' => 20,
'marginBottom' => 20,
'cssInline' => '.kv-wrap{padding:20px;}' .
'.kv-align-center{text-align:center;}' .
'.kv-align-left{text-align:left;}' .
'.kv-align-right{text-align:right;}' .
'.kv-align-top{vertical-align:top!important;}' .
'.kv-align-bottom{vertical-align:bottom!important;}' .
'.kv-align-middle{vertical-align:middle!important;}' .
'.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
'.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
'.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
'methods' => [
'SetHeader' => [
['odd' => $pdfHeader, 'even' => $pdfHeader],
],
'SetFooter' => [
['odd' => $pdfFooter, 'even' => $pdfFooter],
],
],
'options' => [
'title' => $title,
'subject' => Yii::t('cza', 'PDF export generated by kartik-v/yii2-grid extension'),
'keywords' => Yii::t('cza', 'grid, export, yii2-grid, pdf'),
],
'contentBefore' => '',
'contentAfter' => '',
],
],
self::JSON => [
'label' => Yii::t('cza', 'JSON'),
'icon' => $isFa ? 'file-code-o' : 'floppy-open',
'iconOptions' => ['class' => 'text-warning'],
'showHeader' => true,
'showPageSummary' => true,
'showFooter' => true,
'showCaption' => true,
'filename' => Yii::t('cza', 'grid-export'),
'alertMsg' => Yii::t('cza', 'The JSON export file will be generated for download.'),
'options' => ['title' => Yii::t('cza', 'JavaScript Object Notation')],
'mime' => 'application/json',
'config' => [
'colHeads' => [],
'slugColHeads' => false,
'jsonReplacer' => new JsExpression("function(k,v){return typeof(v)==='string'?$.trim(v):v}"),
'indentSpace' => 4,
],
],
];
// Remove PDF if dependency is not loaded.
if (!class_exists("\\kartik\\mpdf\\Pdf")) {
unset($defaultExportConfig[self::PDF]);
}
$this->exportConfig = self::parseExportConfig($this->exportConfig, $defaultExportConfig);
}
|
Initialize grid export.
|
https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/widgets/ui/common/grid/GridView.php#L87-L301
|
tidal/phpspec-console
|
spec/Command/InlineConfiguratorSpec.php
|
InlineConfiguratorSpec.createCommandProphecy
|
private function createCommandProphecy()
{
$prophet = new Prophet;
$prophecy = $prophet->prophesize()->willImplement(InlineConfigCommandInterface::class);
$prophecy
->setName('foo')
->shouldBeCalled();
$prophecy
->getConfig()
->willReturn(['name'=>'foo']);
return $prophecy;
}
|
php
|
private function createCommandProphecy()
{
$prophet = new Prophet;
$prophecy = $prophet->prophesize()->willImplement(InlineConfigCommandInterface::class);
$prophecy
->setName('foo')
->shouldBeCalled();
$prophecy
->getConfig()
->willReturn(['name'=>'foo']);
return $prophecy;
}
|
override prophecy creation
@return ObjectProphecy
|
https://github.com/tidal/phpspec-console/blob/5946f1dfdc30c4af5605a889a407b6113ee16d59/spec/Command/InlineConfiguratorSpec.php#L35-L47
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
|
Configuration.validateComponentKeys
|
private function validateComponentKeys(array $v)
{
$diff = array_diff_key($v, array_flip($this->enabledComponentTypes));
if (!empty($diff)) {
throw new InvalidConfigurationException(sprintf(
'Only "%s" component types are supported for configuration, "%s" more given.',
implode('", "', $this->enabledComponentTypes),
implode('", "', array_keys($diff))
));
}
return $v;
}
|
php
|
private function validateComponentKeys(array $v)
{
$diff = array_diff_key($v, array_flip($this->enabledComponentTypes));
if (!empty($diff)) {
throw new InvalidConfigurationException(sprintf(
'Only "%s" component types are supported for configuration, "%s" more given.',
implode('", "', $this->enabledComponentTypes),
implode('", "', array_keys($diff))
));
}
return $v;
}
|
Validate given array keys are all registered components.
@param array $v
@return array
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L44-L56
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
|
Configuration.getConfigTreeBuilder
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('synapse')
->info('Define themes structure, templates, zones and components. You have to define at least one.')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->arrayNode('structure')
->isRequired()
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array') // templates
->useAttributeAsKey('name')
->prototype('array') // zones
->useAttributeAsKey('name')
->prototype('array') // components
->end()
->validate()
->always()
->then(function ($v) {
return $this->validateComponentKeys($v);
})
->end()
->end()
->end()
->end()
->append($this
->createVariableNode('templates', 'hydrateTemplatesNode')
->requiresAtLeastOneElement()
)
->append($this
->createVariableNode('zones', 'hydrateZonesNode')
)
->append($this
->createVariableNode('components', 'hydrateComponentsNode')
->validate()
->always()
->then(function ($v) {
return $this->validateComponentKeys($v);
})
->end()
)
->arrayNode('image_formats')
->useAttributeAsKey('name')
->prototype('array') // formats
->addDefaultsIfNotSet()
->children()
->enumNode('strategy')
->defaultValue('crop')
->values(array('resize', 'crop'))
->end()
->integerNode('width')
->isRequired()
->min(1)
->end()
->integerNode('height')
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
|
php
|
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('synapse')
->info('Define themes structure, templates, zones and components. You have to define at least one.')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->arrayNode('structure')
->isRequired()
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array') // templates
->useAttributeAsKey('name')
->prototype('array') // zones
->useAttributeAsKey('name')
->prototype('array') // components
->end()
->validate()
->always()
->then(function ($v) {
return $this->validateComponentKeys($v);
})
->end()
->end()
->end()
->end()
->append($this
->createVariableNode('templates', 'hydrateTemplatesNode')
->requiresAtLeastOneElement()
)
->append($this
->createVariableNode('zones', 'hydrateZonesNode')
)
->append($this
->createVariableNode('components', 'hydrateComponentsNode')
->validate()
->always()
->then(function ($v) {
return $this->validateComponentKeys($v);
})
->end()
)
->arrayNode('image_formats')
->useAttributeAsKey('name')
->prototype('array') // formats
->addDefaultsIfNotSet()
->children()
->enumNode('strategy')
->defaultValue('crop')
->values(array('resize', 'crop'))
->end()
->integerNode('width')
->isRequired()
->min(1)
->end()
->integerNode('height')
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
|
{@inheritdoc}
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L61-L128
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
|
Configuration.hydrateTemplatesNode
|
private function hydrateTemplatesNode(NodeBuilder $node)
{
$node
->booleanNode('default')
->defaultFalse()
->end()
->scalarNode('path')
->cannotBeEmpty()
->end()
->arrayNode('contents')
->prototype('scalar')
->cannotBeEmpty()
->end()
->end()
;
return $node;
}
|
php
|
private function hydrateTemplatesNode(NodeBuilder $node)
{
$node
->booleanNode('default')
->defaultFalse()
->end()
->scalarNode('path')
->cannotBeEmpty()
->end()
->arrayNode('contents')
->prototype('scalar')
->cannotBeEmpty()
->end()
->end()
;
return $node;
}
|
Hydrate given node with templates configuration nodes.
@param NodeBuilder $node
@return NodeBuilder
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L188-L205
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
|
Configuration.hydrateZonesNode
|
private function hydrateZonesNode(NodeBuilder $node)
{
$node
->booleanNode('main')
->defaultFalse()
->end()
->booleanNode('virtual')
->defaultFalse()
->end()
->arrayNode('aggregation')
->addDefaultsIfNotSet()
->beforeNormalization()
->always(function ($v) {
if (is_string($v)) { // shortcut case
$v = array('type' => $v);
}
if (is_array($v) && !empty($v['path'])) { // path shortcut case
$v['type'] = 'template';
}
return $v;
})
->end()
->children()
->scalarNode('type')
->defaultValue('inline')
->cannotBeEmpty()
->end()
->scalarNode('path')->end()
->end()
->end()
;
return $node;
}
|
php
|
private function hydrateZonesNode(NodeBuilder $node)
{
$node
->booleanNode('main')
->defaultFalse()
->end()
->booleanNode('virtual')
->defaultFalse()
->end()
->arrayNode('aggregation')
->addDefaultsIfNotSet()
->beforeNormalization()
->always(function ($v) {
if (is_string($v)) { // shortcut case
$v = array('type' => $v);
}
if (is_array($v) && !empty($v['path'])) { // path shortcut case
$v['type'] = 'template';
}
return $v;
})
->end()
->children()
->scalarNode('type')
->defaultValue('inline')
->cannotBeEmpty()
->end()
->scalarNode('path')->end()
->end()
->end()
;
return $node;
}
|
Hydrate given node with zones configuration nodes.
@param NodeBuilder $node
@return NodeBuilder
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L214-L248
|
Synapse-Cmf/synapse-cmf
|
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
|
Configuration.hydrateComponentsNode
|
private function hydrateComponentsNode(NodeBuilder $node)
{
$node
->scalarNode('path')->end()
->scalarNode('controller')->end()
->arrayNode('config')
->useAttributeAsKey('name')
->prototype('array')
->useAttributeAsKey('name')
->beforeNormalization()
->always(function ($v) {
if (is_bool($v)) {
return array('enabled' => $v);
}
return $v;
})
->end()
->prototype('scalar')->end()
->end()
->end()
;
return $node;
}
|
php
|
private function hydrateComponentsNode(NodeBuilder $node)
{
$node
->scalarNode('path')->end()
->scalarNode('controller')->end()
->arrayNode('config')
->useAttributeAsKey('name')
->prototype('array')
->useAttributeAsKey('name')
->beforeNormalization()
->always(function ($v) {
if (is_bool($v)) {
return array('enabled' => $v);
}
return $v;
})
->end()
->prototype('scalar')->end()
->end()
->end()
;
return $node;
}
|
Hydrate given node with components configuration nodes.
@param NodeBuilder $node
@return NodeBuilder
|
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L257-L281
|
temp/media-converter
|
src/Binary/MP4Box.php
|
MP4Box.process
|
public function process($inputFile, $outputFile = null)
{
if (!file_exists($inputFile) || !is_readable($inputFile)) {
throw new InvalidFileArgumentException(sprintf('File %s does not exist or is not readable', $inputFile));
}
$arguments = array(
'-quiet',
'-inter',
'0.5',
'-tmp',
dirname($inputFile),
$inputFile,
);
if ($outputFile) {
$arguments[] = '-out';
$arguments[] = $outputFile;
}
try {
$this->command($arguments);
} catch (ExecutionFailureException $e) {
throw new RuntimeException(sprintf(
'MP4Box failed to process %s', $inputFile
), $e->getCode(), $e);
}
return $this;
}
|
php
|
public function process($inputFile, $outputFile = null)
{
if (!file_exists($inputFile) || !is_readable($inputFile)) {
throw new InvalidFileArgumentException(sprintf('File %s does not exist or is not readable', $inputFile));
}
$arguments = array(
'-quiet',
'-inter',
'0.5',
'-tmp',
dirname($inputFile),
$inputFile,
);
if ($outputFile) {
$arguments[] = '-out';
$arguments[] = $outputFile;
}
try {
$this->command($arguments);
} catch (ExecutionFailureException $e) {
throw new RuntimeException(sprintf(
'MP4Box failed to process %s', $inputFile
), $e->getCode(), $e);
}
return $this;
}
|
Processes a file
@param string $inputFile The file to process.
@param null|string $outputFile The output file to write. If not provided, processes the file in place.
@return MP4Box
@throws InvalidFileArgumentException In case the input file is not readable
@throws RuntimeException In case the process failed
|
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Binary/MP4Box.php#L43-L72
|
temp/media-converter
|
src/Binary/MP4Box.php
|
MP4Box.create
|
public static function create($conf = array(), LoggerInterface $logger = null)
{
if (!$conf instanceof ConfigurationInterface) {
$conf = new Configuration($conf);
}
$binaries = $conf->get('mp4box.binaries', array('MP4Box'));
return static::load($binaries, $logger, $conf);
}
|
php
|
public static function create($conf = array(), LoggerInterface $logger = null)
{
if (!$conf instanceof ConfigurationInterface) {
$conf = new Configuration($conf);
}
$binaries = $conf->get('mp4box.binaries', array('MP4Box'));
return static::load($binaries, $logger, $conf);
}
|
Creates an MP4Box binary adapter.
@param null|LoggerInterface $logger
@param array|ConfigurationInterface $conf
@return MP4Box
|
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Binary/MP4Box.php#L82-L91
|
zhengb302/LumengPHP
|
src/LumengPHP/Kernel/Annotation/Parser/Parser.php
|
Parser.propertyInjectorTag
|
private function propertyInjectorTag() {
$this->match(Token::T_PROPERTY_INJECTOR);
$this->metadata->addMetadata('source', ltrim($this->lastToken->getText(), '@'));
if ($this->lookahead->getType() == Token::T_LEFT_PARENTHESIS) {
$this->match(Token::T_LEFT_PARENTHESIS);
$this->match(Token::T_ID);
$this->metadata->addMetadata('paramName', $this->lastToken->getText());
$this->match(Token::T_RIGHT_PARENTHESIS);
}
if (!$this->lookahead->isAnnotation()) {
$this->lexer->gotoNextAnnotation();
$this->consume();
}
}
|
php
|
private function propertyInjectorTag() {
$this->match(Token::T_PROPERTY_INJECTOR);
$this->metadata->addMetadata('source', ltrim($this->lastToken->getText(), '@'));
if ($this->lookahead->getType() == Token::T_LEFT_PARENTHESIS) {
$this->match(Token::T_LEFT_PARENTHESIS);
$this->match(Token::T_ID);
$this->metadata->addMetadata('paramName', $this->lastToken->getText());
$this->match(Token::T_RIGHT_PARENTHESIS);
}
if (!$this->lookahead->isAnnotation()) {
$this->lexer->gotoNextAnnotation();
$this->consume();
}
}
|
属性注入注解:"@get"、"@post"、"@request"、"@session"、"@config"、"@service"、"@currentEvent"
|
https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Annotation/Parser/Parser.php#L75-L89
|
zhengb302/LumengPHP
|
src/LumengPHP/Kernel/Annotation/Parser/Parser.php
|
Parser.actionTag
|
private function actionTag() {
switch ($this->lookahead->getText()) {
case '@keepDefault':
$this->actionKeepDefault();
break;
case '@queued':
$this->actionQueued();
break;
case '@queue':
$this->actionQueue();
break;
}
}
|
php
|
private function actionTag() {
switch ($this->lookahead->getText()) {
case '@keepDefault':
$this->actionKeepDefault();
break;
case '@queued':
$this->actionQueued();
break;
case '@queue':
$this->actionQueue();
break;
}
}
|
动作注解:“@keepDefault”、“@queued”、“@queue”
|
https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Annotation/Parser/Parser.php#L94-L106
|
zhengb302/LumengPHP
|
src/LumengPHP/Kernel/Annotation/Parser/Parser.php
|
Parser.actionKeepDefault
|
private function actionKeepDefault() {
$this->match(Token::T_ACTION, true);
$action = ltrim($this->lastToken->getText(), '@');
$this->metadata->addMetadata($action, true);
}
|
php
|
private function actionKeepDefault() {
$this->match(Token::T_ACTION, true);
$action = ltrim($this->lastToken->getText(), '@');
$this->metadata->addMetadata($action, true);
}
|
注解“@keepDefault”后不能有参数
|
https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Annotation/Parser/Parser.php#L111-L116
|
zhengb302/LumengPHP
|
src/LumengPHP/Kernel/Annotation/Parser/Parser.php
|
Parser.actionQueue
|
private function actionQueue() {
$this->match(Token::T_ACTION);
$action = ltrim($this->lastToken->getText(), '@');
$this->match(Token::T_LEFT_PARENTHESIS);
$this->match(Token::T_ID);
$value = $this->lastToken->getText();
$this->match(Token::T_RIGHT_PARENTHESIS);
$this->metadata->addMetadata($action, $value);
if (!$this->lookahead->isAnnotation()) {
$this->lexer->gotoNextAnnotation();
$this->consume();
}
}
|
php
|
private function actionQueue() {
$this->match(Token::T_ACTION);
$action = ltrim($this->lastToken->getText(), '@');
$this->match(Token::T_LEFT_PARENTHESIS);
$this->match(Token::T_ID);
$value = $this->lastToken->getText();
$this->match(Token::T_RIGHT_PARENTHESIS);
$this->metadata->addMetadata($action, $value);
if (!$this->lookahead->isAnnotation()) {
$this->lexer->gotoNextAnnotation();
$this->consume();
}
}
|
注解“@queue”必须带有一个参数
|
https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Annotation/Parser/Parser.php#L145-L161
|
YiMAproject/yimaWidgetator
|
src/yimaWidgetator/Service/WidgetManager.php
|
WidgetManager.validatePlugin
|
public function validatePlugin($plugin)
{
if ($plugin instanceof WidgetInterface)
return true;
throw new \Exception(sprintf(
'yimaWidgetator of type %s is invalid; must implement yimaWidgetator\Widget\WidgetInterface',
(is_object($plugin) ? get_class($plugin) : gettype($plugin))
));
}
|
php
|
public function validatePlugin($plugin)
{
if ($plugin instanceof WidgetInterface)
return true;
throw new \Exception(sprintf(
'yimaWidgetator of type %s is invalid; must implement yimaWidgetator\Widget\WidgetInterface',
(is_object($plugin) ? get_class($plugin) : gettype($plugin))
));
}
|
Validate the plugin
Ensure we have a widget.
@param mixed $plugin
@return true
@throws \Exception
|
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Service/WidgetManager.php#L78-L87
|
YiMAproject/yimaWidgetator
|
src/yimaWidgetator/Service/WidgetManager.php
|
WidgetManager.injectWidgetDependencies
|
public function injectWidgetDependencies(WidgetInterface $widget, ServiceLocatorInterface $serviceLocator)
{
/** @var $serviceLocator \yimaWidgetator\Service\WidgetManager */
$sm = $serviceLocator->getServiceLocator();
if (!$sm)
throw new \Exception('Service Manager can`t found.');
/**
* MVC Widget
*/
if ($widget instanceof ViewRendererPlugInterface) {
if (! $sm->has('ViewRenderer'))
throw new \Exception('ViewRenderer service not found on Service Manager.');
$widget->setView($sm->get('ViewRenderer'));
}
if ($widget instanceof iInitableWidgetFeature) {
// widget initialize himself after all
$widget->init();
}
/*if ($widget instanceof AbstractWidget) {
// register widget in service locator with own unique id
$sl = $this->getServiceLocator();
$sl->setService($widget->getID(), $widget);
}*/
}
|
php
|
public function injectWidgetDependencies(WidgetInterface $widget, ServiceLocatorInterface $serviceLocator)
{
/** @var $serviceLocator \yimaWidgetator\Service\WidgetManager */
$sm = $serviceLocator->getServiceLocator();
if (!$sm)
throw new \Exception('Service Manager can`t found.');
/**
* MVC Widget
*/
if ($widget instanceof ViewRendererPlugInterface) {
if (! $sm->has('ViewRenderer'))
throw new \Exception('ViewRenderer service not found on Service Manager.');
$widget->setView($sm->get('ViewRenderer'));
}
if ($widget instanceof iInitableWidgetFeature) {
// widget initialize himself after all
$widget->init();
}
/*if ($widget instanceof AbstractWidget) {
// register widget in service locator with own unique id
$sl = $this->getServiceLocator();
$sl->setService($widget->getID(), $widget);
}*/
}
|
Inject required dependencies into the widget.
@param WidgetInterface $widget
@param ServiceLocatorInterface $serviceLocator
@throws \Exception
@return void
|
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Service/WidgetManager.php#L98-L125
|
flipbox/pipeline
|
src/Processors/SelectableStageProcessor.php
|
SelectableStageProcessor.processStages
|
protected function processStages(array $stages, $payload, array $extra = [])
{
foreach ($stages as $key => $stage) {
if ($this->isStageSelectable($key)) {
$payload = $this->processStage($stage, $payload, $extra);
}
}
return $payload;
}
|
php
|
protected function processStages(array $stages, $payload, array $extra = [])
{
foreach ($stages as $key => $stage) {
if ($this->isStageSelectable($key)) {
$payload = $this->processStage($stage, $payload, $extra);
}
}
return $payload;
}
|
@param array $stages
@param mixed $payload
@param array $extra
@return mixed
|
https://github.com/flipbox/pipeline/blob/bbfd3093019d04e9b612961d8e93c3d44a0a169e/src/Processors/SelectableStageProcessor.php#L55-L64
|
bluetree-service/data
|
src/Data/Xml.php
|
Xml.loadXmlFile
|
public function loadXmlFile($path, $parse = false)
{
$this->preserveWhiteSpace = false;
$bool = file_exists($path);
if (!$bool) {
$this->error = 'file_not_exists';
return false;
}
$bool = @$this->load($path);
if (!$bool) {
$this->error = 'loading_file_error';
return false;
}
if ($parse && !@$this->validate()) {
$this->error = 'parse_file_error';
return false;
}
return true;
}
|
php
|
public function loadXmlFile($path, $parse = false)
{
$this->preserveWhiteSpace = false;
$bool = file_exists($path);
if (!$bool) {
$this->error = 'file_not_exists';
return false;
}
$bool = @$this->load($path);
if (!$bool) {
$this->error = 'loading_file_error';
return false;
}
if ($parse && !@$this->validate()) {
$this->error = 'parse_file_error';
return false;
}
return true;
}
|
load xml file, optionally check file DTD
@param string $path xml file path
@param boolean $parse if true will check file DTD
@return boolean
@example loadXmlFile('cfg/config.xml', true)
|
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L78-L100
|
bluetree-service/data
|
src/Data/Xml.php
|
Xml.saveXmlFile
|
public function saveXmlFile($path = '')
{
$this->formatOutput = true;
if ($path) {
$bool = @$this->save($path);
if (!$bool) {
$this->error = 'save_file_error';
return false;
}
return true;
}
return $this->saveXML();
}
|
php
|
public function saveXmlFile($path = '')
{
$this->formatOutput = true;
if ($path) {
$bool = @$this->save($path);
if (!$bool) {
$this->error = 'save_file_error';
return false;
}
return true;
}
return $this->saveXML();
}
|
save xml file, optionally will return as string
@param string $path xml file path
@return string|boolean
@example saveXmlFile('path/filename.xml'); save to file
@example saveXmlFile() will return as simple text
|
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L111-L126
|
bluetree-service/data
|
src/Data/Xml.php
|
Xml.searchByAttributeRecurrent
|
protected function searchByAttributeRecurrent(
DOMNodeList $node,
$value,
array $list = []
) {
/** @var DomElement $child */
foreach ($node as $child) {
if ($child->nodeType === 1) {
if ($child->hasChildNodes()) {
$list = $this->searchByAttributeRecurrent(
$child->childNodes,
$value,
$list
);
}
$attribute = $child->getAttribute($value);
if ($attribute) {
$list[$attribute] = $child;
}
}
}
return $list;
}
|
php
|
protected function searchByAttributeRecurrent(
DOMNodeList $node,
$value,
array $list = []
) {
/** @var DomElement $child */
foreach ($node as $child) {
if ($child->nodeType === 1) {
if ($child->hasChildNodes()) {
$list = $this->searchByAttributeRecurrent(
$child->childNodes,
$value,
$list
);
}
$attribute = $child->getAttribute($value);
if ($attribute) {
$list[$attribute] = $child;
}
}
}
return $list;
}
|
search for all nodes with given attribute
return list of nodes with attribute value as key
@param DOMNodeList $node
@param string $value attribute value to search
@param array|boolean $list list of find nodes for recurrence
@return array
|
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L137-L161
|
iron-bound-designs/wp-notifications
|
src/Notification.php
|
Notification.generate_rendered_tags
|
final protected function generate_rendered_tags() {
$data_sources = $this->data_sources;
$data_sources[] = $this->recipient;
$tags = $this->manager->render_tags( $data_sources );
$rendered = array();
foreach ( $tags as $tag => $value ) {
$rendered[ '{' . $tag . '}' ] = $value;
}
$this->regenerate = false;
return $rendered;
}
|
php
|
final protected function generate_rendered_tags() {
$data_sources = $this->data_sources;
$data_sources[] = $this->recipient;
$tags = $this->manager->render_tags( $data_sources );
$rendered = array();
foreach ( $tags as $tag => $value ) {
$rendered[ '{' . $tag . '}' ] = $value;
}
$this->regenerate = false;
return $rendered;
}
|
Generate the rendered forms of the tags.
@since 1.0
@return array
|
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L88-L103
|
iron-bound-designs/wp-notifications
|
src/Notification.php
|
Notification.add_data_source
|
public function add_data_source( \Serializable $source, $name = '' ) {
if ( $name ) {
$this->data_sources[ $name ] = $source;
} else {
$this->data_sources[] = $source;
}
$this->regenerate();
return $this;
}
|
php
|
public function add_data_source( \Serializable $source, $name = '' ) {
if ( $name ) {
$this->data_sources[ $name ] = $source;
} else {
$this->data_sources[] = $source;
}
$this->regenerate();
return $this;
}
|
Add a data source.
@since 1.0
@param \Serializable $source
@param string $name If passed, listeners specifying that function
argument name will receive this data source.
@return self
|
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L125-L136
|
iron-bound-designs/wp-notifications
|
src/Notification.php
|
Notification.send
|
public function send() {
if ( is_null( $this->strategy ) ) {
throw new \LogicException( "No strategy has been set." );
}
return $this->strategy->send( $this->get_recipient(), $this->get_message(), $this->get_subject(), $this->get_tags() );
}
|
php
|
public function send() {
if ( is_null( $this->strategy ) ) {
throw new \LogicException( "No strategy has been set." );
}
return $this->strategy->send( $this->get_recipient(), $this->get_message(), $this->get_subject(), $this->get_tags() );
}
|
Send the notification.
@since 1.0
@return bool
@throws \Exception
|
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L162-L169
|
iron-bound-designs/wp-notifications
|
src/Notification.php
|
Notification.get_data_to_serialize
|
protected function get_data_to_serialize() {
return array(
'recipient' => $this->recipient->ID,
'message' => $this->message,
'subject' => $this->subject,
'strategy' => $this->strategy,
'manager' => $this->manager->get_type(),
'data_sources' => $this->data_sources
);
}
|
php
|
protected function get_data_to_serialize() {
return array(
'recipient' => $this->recipient->ID,
'message' => $this->message,
'subject' => $this->subject,
'strategy' => $this->strategy,
'manager' => $this->manager->get_type(),
'data_sources' => $this->data_sources
);
}
|
Get the data to serialize.
Child classes should override this method, and add their own data.
This can be exploited to override the base class's data - don't.
@since 1.0
@return array
|
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L263-L272
|
iron-bound-designs/wp-notifications
|
src/Notification.php
|
Notification.do_unserialize
|
protected function do_unserialize( array $data ) {
$this->recipient = get_user_by( 'id', $data['recipient'] );
$this->message = $data['message'];
$this->subject = $data['subject'];
$this->manager = Factory::make( $data['manager'] );
$this->strategy = $data['strategy'];
$this->data_sources = $data['data_sources'];
$this->tags = $this->generate_rendered_tags();
}
|
php
|
protected function do_unserialize( array $data ) {
$this->recipient = get_user_by( 'id', $data['recipient'] );
$this->message = $data['message'];
$this->subject = $data['subject'];
$this->manager = Factory::make( $data['manager'] );
$this->strategy = $data['strategy'];
$this->data_sources = $data['data_sources'];
$this->tags = $this->generate_rendered_tags();
}
|
Do the actual unserialization.
Assign the data to class properties.
@since 1.0
@param array $data
|
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L301-L310
|
luoxiaojun1992/lb_framework
|
controllers/console/ConsoleController.php
|
ConsoleController.getOptions
|
protected function getOptions($config)
{
$options = [];
$argv = \Console_Getopt::readPHPArgv();
$opts = \Console_Getopt::getopt(array_slice($argv, 2, count($argv) - 2), $config, null, true);
if (!empty($opts[0]) && is_array($opts[0])) {
foreach ($opts[0] as $val) {
if (!empty($val[0]) && !empty($val[1]) && is_string($val[0]) && is_string($val[1])) {
$options[$val[0]] = $val[1];
}
}
}
return $options;
}
|
php
|
protected function getOptions($config)
{
$options = [];
$argv = \Console_Getopt::readPHPArgv();
$opts = \Console_Getopt::getopt(array_slice($argv, 2, count($argv) - 2), $config, null, true);
if (!empty($opts[0]) && is_array($opts[0])) {
foreach ($opts[0] as $val) {
if (!empty($val[0]) && !empty($val[1]) && is_string($val[0]) && is_string($val[1])) {
$options[$val[0]] = $val[1];
}
}
}
return $options;
}
|
Get Options
|
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/ConsoleController.php#L79-L92
|
umbrella-code/umbrella
|
src/Umbrella/Validation/Validator.php
|
Validator.validate
|
public function validate($value, $groups = null, $traverse = false, $deep = false)
{
$violations = $this->sValidator->validate($value, $groups, $traverse, $deep);
if(count($violations) >= 1)
{
$this->hasFailed();
foreach($violations as $key => $val)
{
$this->errors[] = $violations[$key]->getMessage();
}
}
else
{
$this->hasPassed();
}
}
|
php
|
public function validate($value, $groups = null, $traverse = false, $deep = false)
{
$violations = $this->sValidator->validate($value, $groups, $traverse, $deep);
if(count($violations) >= 1)
{
$this->hasFailed();
foreach($violations as $key => $val)
{
$this->errors[] = $violations[$key]->getMessage();
}
}
else
{
$this->hasPassed();
}
}
|
Validate the entity
@return void
|
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Validation/Validator.php#L49-L66
|
umbrella-code/umbrella
|
src/Umbrella/Validation/Validator.php
|
Validator.hasFailed
|
public function hasFailed()
{
if($this->failed == false || $this->passed == true)
{
$this->failed = true;
$this->passed = false;
}
}
|
php
|
public function hasFailed()
{
if($this->failed == false || $this->passed == true)
{
$this->failed = true;
$this->passed = false;
}
}
|
Set booleans if validator failed
@return void
|
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Validation/Validator.php#L73-L80
|
umbrella-code/umbrella
|
src/Umbrella/Validation/Validator.php
|
Validator.hasPassed
|
public function hasPassed()
{
if($this->passed == false || $this->failed == true)
{
$this->passed = true;
$this->failed = false;
}
}
|
php
|
public function hasPassed()
{
if($this->passed == false || $this->failed == true)
{
$this->passed = true;
$this->failed = false;
}
}
|
Set booleans if validator passed
@return void
|
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Validation/Validator.php#L87-L94
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php
|
Form.renderElements
|
public function renderElements(Traversable $elements, $groupActions = false)
{
$rowPlugin = $this->getRowPlugin();
foreach ($elements as $element) {
if ($element instanceof Fieldset) {
$this->getElement()->addChild($this->renderFieldset($element, $groupActions));
} elseif ($element instanceof ElementInterface) {
$type = $element->getAttribute('type');
$conditions = array(
$element instanceof Element\Submit,
$element instanceof Element\Button,
'submit' === $type,
'reset' === $type,
);
if ($groupActions && (in_array(true, $conditions))) {
$this->formActionElements[] = $element;
continue;
}
$this->getElement()->addChild($rowPlugin($element)->getElement());
} else {
throw new Exception\RuntimeException('Unexpected element.');
}
}
return $this;
}
|
php
|
public function renderElements(Traversable $elements, $groupActions = false)
{
$rowPlugin = $this->getRowPlugin();
foreach ($elements as $element) {
if ($element instanceof Fieldset) {
$this->getElement()->addChild($this->renderFieldset($element, $groupActions));
} elseif ($element instanceof ElementInterface) {
$type = $element->getAttribute('type');
$conditions = array(
$element instanceof Element\Submit,
$element instanceof Element\Button,
'submit' === $type,
'reset' === $type,
);
if ($groupActions && (in_array(true, $conditions))) {
$this->formActionElements[] = $element;
continue;
}
$this->getElement()->addChild($rowPlugin($element)->getElement());
} else {
throw new Exception\RuntimeException('Unexpected element.');
}
}
return $this;
}
|
@param Traversable $elements
@param boolean $groupActions
@return $this
@throws \SxBootstrap\Exception\RuntimeException
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php#L72-L103
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php
|
Form.renderFieldset
|
protected function renderFieldset(Fieldset $fieldset, $groupActions = false)
{
$fieldsetElement = new HtmlElement('fieldset');
$id = $fieldset->getAttribute('id') ? : $fieldset->getName();
$parent = $this->getElement();
$fieldsetElement->addAttribute('id', $id);
/**
* This changes the scope of the current element,
* so that the child elements (the ones that are about to be rendered),
* will be set on the fieldset.
* Then change it back again so that the fieldset will be added to the form.
*/
$this
->setElement($fieldsetElement)
->renderElements($fieldset, $groupActions)
->setElement($parent);
return $fieldsetElement;
}
|
php
|
protected function renderFieldset(Fieldset $fieldset, $groupActions = false)
{
$fieldsetElement = new HtmlElement('fieldset');
$id = $fieldset->getAttribute('id') ? : $fieldset->getName();
$parent = $this->getElement();
$fieldsetElement->addAttribute('id', $id);
/**
* This changes the scope of the current element,
* so that the child elements (the ones that are about to be rendered),
* will be set on the fieldset.
* Then change it back again so that the fieldset will be added to the form.
*/
$this
->setElement($fieldsetElement)
->renderElements($fieldset, $groupActions)
->setElement($parent);
return $fieldsetElement;
}
|
@param Fieldset $fieldset
@param boolean $groupActions
@return HtmlElement
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php#L119-L139
|
SpoonX/SxBootstrap
|
src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php
|
Form.renderFormActions
|
protected function renderFormActions()
{
$rowPlugin = $this->getRowPlugin();
if (!empty($this->formActionElements)) {
$this->getElement()->addChild($rowPlugin($this->formActionElements, true)->getElement());
}
return $this;
}
|
php
|
protected function renderFormActions()
{
$rowPlugin = $this->getRowPlugin();
if (!empty($this->formActionElements)) {
$this->getElement()->addChild($rowPlugin($this->formActionElements, true)->getElement());
}
return $this;
}
|
Render the form action elements, when needed.
@return $this
|
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php#L146-L155
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.get
|
public function get($varname)
{
$value = $this->getPhp($varname);
return $value === false ? null : $value;
}
|
php
|
public function get($varname)
{
$value = $this->getPhp($varname);
return $value === false ? null : $value;
}
|
Simple wrapper around ini_get()
See http://php.net/manual/en/function.ini-get.php
@param string $varname The configuration option name.
@return null|string Null if configuration option does not exist.
The configuration option value (string) otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L27-L31
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.getString
|
public function getString($varname)
{
$value = $this->get($varname);
return $value === null ? null : trim($value);
}
|
php
|
public function getString($varname)
{
$value = $this->get($varname);
return $value === null ? null : trim($value);
}
|
Gets the configuration option value as a trimmed string.
@param string $varname The configuration option name.
@return null|string Null if configuration option does not exist.
The configuration option value (string) otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L40-L44
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.getBool
|
public function getBool($varname)
{
$value = $this->getString($varname);
return $value === null ? null : $value && strtolower($value) !== 'off';
}
|
php
|
public function getBool($varname)
{
$value = $this->getString($varname);
return $value === null ? null : $value && strtolower($value) !== 'off';
}
|
Gets configuration option value as a boolean.
Interprets the string value 'off' as false.
@param string $varname The configuration option name.
@return null|bool Null if configuration option does not exist.
False if configuration option is disabled.
True otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L55-L59
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.getNumeric
|
public function getNumeric($varname)
{
$value = $this->getString($varname);
return is_numeric($value) ? $value + 0 : null;
}
|
php
|
public function getNumeric($varname)
{
$value = $this->getString($varname);
return is_numeric($value) ? $value + 0 : null;
}
|
Gets configuration option value as an integer.
@param string $varname The configuration option name.
@return null|int|float Null if configuration option does not exist or is not numeric.
The configuration option value (integer or float) otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L68-L72
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.getBytes
|
public function getBytes($varname)
{
$value = $this->getString($varname);
if ($value === null) {
return null;
}
if (is_numeric($value)) {
// Already in bytes.
return $value + 0;
}
return $this->convertBytes($value);
}
|
php
|
public function getBytes($varname)
{
$value = $this->getString($varname);
if ($value === null) {
return null;
}
if (is_numeric($value)) {
// Already in bytes.
return $value + 0;
}
return $this->convertBytes($value);
}
|
Gets configuration option value in bytes.
Converts strings like '128M' to bytes (integer or float).
@param string $varname The configuration option name.
@return null|int|float Null if configuration option does not exist or is not well-formed.
The configuration option value as bytes (integer or float) otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L82-L96
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.getList
|
public function getList($varname)
{
$value = $this->getString($varname);
return $value === null ? null : array_map('trim', explode(',', $value));
}
|
php
|
public function getList($varname)
{
$value = $this->getString($varname);
return $value === null ? null : array_map('trim', explode(',', $value));
}
|
Gets configuration option value as a list (array).
Converts comma-separated string into list (array).
@param string $varname The configuration option name.
@return null|array Null if configuration option does not exist.
The configuration option value as a list (array) otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L106-L110
|
bantuXorg/php-ini-get-wrapper
|
src/IniGetWrapper.php
|
IniGetWrapper.listContains
|
public function listContains($varname, $needle)
{
$list = $this->getList($varname);
return $list === null ? null : in_array($needle, $list, true);
}
|
php
|
public function listContains($varname, $needle)
{
$list = $this->getList($varname);
return $list === null ? null : in_array($needle, $list, true);
}
|
Checks whether a list contains a given element (string).
@param string $varname The configuration option name.
@param string $needle The element to check whether it is contained in the list.
@return null|bool Null if configuration option does not exist.
Whether $needle is contained in the list otherwise.
|
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L120-L124
|
RowlandOti/ooglee-blogmodule
|
src/OoGlee/Application/Entities/Post/PostResolver.php
|
PostResolver.resolve
|
public function resolve()
{
$url = $this->request->url();
$tmp = explode('/', $url);
$last_seg = end($tmp);
return $this->repository->findBySlug($last_seg);
}
|
php
|
public function resolve()
{
$url = $this->request->url();
$tmp = explode('/', $url);
$last_seg = end($tmp);
return $this->repository->findBySlug($last_seg);
}
|
Resolve the post.
@return PostInterface|null
|
https://github.com/RowlandOti/ooglee-blogmodule/blob/d9c0fe4745bb09f8b94047b0cda4fd7438cde16a/src/OoGlee/Application/Entities/Post/PostResolver.php#L51-L58
|
ekyna/AdminBundle
|
Form/Type/PermissionsType.php
|
PermissionsType.buildForm
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($this->registry->getConfigurations() as $config) {
$builder->add($config->getAlias(), new PermissionType($this->permissions), [
'label' => $config->getResourceLabel(true)
]);
}
}
|
php
|
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($this->registry->getConfigurations() as $config) {
$builder->add($config->getAlias(), new PermissionType($this->permissions), [
'label' => $config->getResourceLabel(true)
]);
}
}
|
{@inheritdoc}
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Form/Type/PermissionsType.php#L43-L50
|
ekyna/AdminBundle
|
Form/Type/PermissionsType.php
|
PermissionsType.buildView
|
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['permissions'] = $this->permissions;
}
|
php
|
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['permissions'] = $this->permissions;
}
|
{@inheritdoc}
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Form/Type/PermissionsType.php#L55-L58
|
g4code/mcache
|
src/G4/Mcache/Driver/Libmemcached.php
|
Libmemcached.processOptions
|
private function processOptions()
{
$options = $this->getOptions();
if(empty($options)) {
throw new \Exception('Options must be set');
}
foreach($options['servers'] as $server) {
$serverData = explode(self::DELIMITER, $server);
if (count($serverData) != 2) {
continue;
}
$this->servers[] = array(
'host' => $serverData[0],
'port' => $serverData[1],
);
if(!empty($server['weight'])) {
$this->servers['weight'] = $server['weight'];
}
}
if(isset($options['compression'])) {
$this->compression = $options['compression'];
}
return $this;
}
|
php
|
private function processOptions()
{
$options = $this->getOptions();
if(empty($options)) {
throw new \Exception('Options must be set');
}
foreach($options['servers'] as $server) {
$serverData = explode(self::DELIMITER, $server);
if (count($serverData) != 2) {
continue;
}
$this->servers[] = array(
'host' => $serverData[0],
'port' => $serverData[1],
);
if(!empty($server['weight'])) {
$this->servers['weight'] = $server['weight'];
}
}
if(isset($options['compression'])) {
$this->compression = $options['compression'];
}
return $this;
}
|
@param string $host
@param int $port
@param int $weight
@return \G4\Mcache\Driver\Libmemcached
|
https://github.com/g4code/mcache/blob/79a41506027881a03f24b5166fa6745e9736150a/src/G4/Mcache/Driver/Libmemcached.php#L29-L58
|
slickframework/form
|
src/Element/FieldSet.php
|
FieldSet.isValid
|
public function isValid()
{
$valid = true;
$this->validate();
foreach ($this->getIterator() as $element) {
if ($element instanceof ValidationAwareInterface) {
$valid = $element->isValid()
? $valid
: false;
}
}
return $valid;
}
|
php
|
public function isValid()
{
$valid = true;
$this->validate();
foreach ($this->getIterator() as $element) {
if ($element instanceof ValidationAwareInterface) {
$valid = $element->isValid()
? $valid
: false;
}
}
return $valid;
}
|
Checks if all elements are valid
@return mixed
|
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L62-L74
|
slickframework/form
|
src/Element/FieldSet.php
|
FieldSet.add
|
public function add(ElementInterface $element)
{
if (null === $element->getName()) {
$this->data[] = $element;
return $this;
}
$this->data[$element->getName()] = $element;
return $this;
}
|
php
|
public function add(ElementInterface $element)
{
if (null === $element->getName()) {
$this->data[] = $element;
return $this;
}
$this->data[$element->getName()] = $element;
return $this;
}
|
Adds an element to the container
@param ElementInterface $element
@return self|$this|ContainerInterface
|
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L83-L91
|
slickframework/form
|
src/Element/FieldSet.php
|
FieldSet.get
|
public function get($name)
{
$selected = null;
/** @var ElementInterface|ContainerInterface $element */
foreach ($this as $element) {
if ($element->getName() == $name) {
$selected = $element;
break;
}
if ($element instanceof ContainerInterface) {
$selected = $element->get($name);
if (null !== $selected) {
break;
}
}
}
return $selected;
}
|
php
|
public function get($name)
{
$selected = null;
/** @var ElementInterface|ContainerInterface $element */
foreach ($this as $element) {
if ($element->getName() == $name) {
$selected = $element;
break;
}
if ($element instanceof ContainerInterface) {
$selected = $element->get($name);
if (null !== $selected) {
break;
}
}
}
return $selected;
}
|
Gets element by name
@param string $name
@return null|ElementInterface|InputInterface
|
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L100-L119
|
slickframework/form
|
src/Element/FieldSet.php
|
FieldSet.setValues
|
public function setValues(array $values)
{
foreach ($values as $name => $value) {
if ($element = $this->get($name)) {
$element->setValue($value);
}
}
return $this;
}
|
php
|
public function setValues(array $values)
{
foreach ($values as $name => $value) {
if ($element = $this->get($name)) {
$element->setValue($value);
}
}
return $this;
}
|
Sets the values form matched elements
The passed array is a key/value array where keys are used to
match against element names. It will only assign the value to
the marched element only.
@param array $values
@return self|$this|ContainerInterface
|
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L132-L140
|
slickframework/form
|
src/Element/FieldSet.php
|
FieldSet.validate
|
public function validate()
{
foreach ($this as $element) {
if (
$element instanceof ValidationAwareInterface ||
$element instanceof ContainerInterface
) {
$element->validate();
}
}
return $this;
}
|
php
|
public function validate()
{
foreach ($this as $element) {
if (
$element instanceof ValidationAwareInterface ||
$element instanceof ContainerInterface
) {
$element->validate();
}
}
return $this;
}
|
Runs validation chain in all its elements
@return self|$this|ElementInterface
|
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L219-L231
|
jelix/file-utilities
|
lib/Path.php
|
Path.normalizePath
|
public static function normalizePath($path, $options = 0, $basePath = '')
{
list($prefix, $path, $absolute) = self::_normalizePath($path, false, $basePath);
if (!is_string($path)) {
$path = implode('/', $path);
}
$path = $prefix.($absolute ? '/' : '').$path;
if ($options & self::NORM_ADD_TRAILING_SLASH) {
$path .= '/';
}
return $path;
}
|
php
|
public static function normalizePath($path, $options = 0, $basePath = '')
{
list($prefix, $path, $absolute) = self::_normalizePath($path, false, $basePath);
if (!is_string($path)) {
$path = implode('/', $path);
}
$path = $prefix.($absolute ? '/' : '').$path;
if ($options & self::NORM_ADD_TRAILING_SLASH) {
$path .= '/';
}
return $path;
}
|
normalize a path : translate '..', '.', replace '\' by '/' and so on..
support windows path.
when $path is relative, it can be resolved against the given $basePath.
@param string $path
@param int $options see NORM_* const
@param string $basePath
@return string the normalized path
|
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Path.php#L28-L41
|
jelix/file-utilities
|
lib/Path.php
|
Path.isAbsolute
|
public static function isAbsolute($path)
{
list($prefix, $path, $absolute) = self::_startNormalize($path);
return $absolute;
}
|
php
|
public static function isAbsolute($path)
{
list($prefix, $path, $absolute) = self::_startNormalize($path);
return $absolute;
}
|
says if the given path is an absolute one or not.
@param string $path
@return bool true if the path is absolute
|
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Path.php#L50-L55
|
jelix/file-utilities
|
lib/Path.php
|
Path._normalizePath
|
protected static function _normalizePath($originalPath, $alwaysArray, $basePath = '')
{
list($prefix, $path, $absolute) = self::_startNormalize($originalPath);
if (!$absolute && $basePath) {
list($prefix, $path, $absolute) = self::_startNormalize($basePath.'/'.$originalPath);
}
if ($absolute && $path != '') {
// remove leading '/' for path
if ($path == '/') {
$path = '';
} else {
$path = substr($path, 1);
}
}
if (strpos($path, './') === false && substr($path, -1) != '.') {
// if there is no relative path component like ../ or ./, we can
// return directly the path informations
if ($alwaysArray) {
if ($path == '') {
return array($prefix, array(), $absolute);
}
return array($prefix, explode('/', rtrim($path, '/')), $absolute);
} else {
if ($path == '') {
return array($prefix, $path, $absolute);
}
return array($prefix, rtrim($path, '/'), $absolute);
}
}
$path = explode('/', $path);
$path2 = array();
$up = false;
foreach ($path as $chunk) {
if ($chunk === '..') {
if (count($path2)) {
if (end($path2) != '..') {
array_pop($path2);
} else {
$path2[] = '..';
}
} elseif (!$absolute) {
// for non absolute path, we keep leading '..'
$path2[] = '..';
}
} elseif ($chunk !== '' && $chunk != '.') {
$path2[] = $chunk;
}
}
return array($prefix, $path2, $absolute);
}
|
php
|
protected static function _normalizePath($originalPath, $alwaysArray, $basePath = '')
{
list($prefix, $path, $absolute) = self::_startNormalize($originalPath);
if (!$absolute && $basePath) {
list($prefix, $path, $absolute) = self::_startNormalize($basePath.'/'.$originalPath);
}
if ($absolute && $path != '') {
// remove leading '/' for path
if ($path == '/') {
$path = '';
} else {
$path = substr($path, 1);
}
}
if (strpos($path, './') === false && substr($path, -1) != '.') {
// if there is no relative path component like ../ or ./, we can
// return directly the path informations
if ($alwaysArray) {
if ($path == '') {
return array($prefix, array(), $absolute);
}
return array($prefix, explode('/', rtrim($path, '/')), $absolute);
} else {
if ($path == '') {
return array($prefix, $path, $absolute);
}
return array($prefix, rtrim($path, '/'), $absolute);
}
}
$path = explode('/', $path);
$path2 = array();
$up = false;
foreach ($path as $chunk) {
if ($chunk === '..') {
if (count($path2)) {
if (end($path2) != '..') {
array_pop($path2);
} else {
$path2[] = '..';
}
} elseif (!$absolute) {
// for non absolute path, we keep leading '..'
$path2[] = '..';
}
} elseif ($chunk !== '' && $chunk != '.') {
$path2[] = $chunk;
}
}
return array($prefix, $path2, $absolute);
}
|
it returns components of a path after normalization, in an array.
- first element: for windows path, the drive part "C:", "C:" etc... always in uppercase
- second element: the normalized path. as string or array depending of $alwaysArray
when as string: no trailing slash.
- third element: indicate if the given path is an absolute path (true) or not (false)
@param bool $alwaysArray if true, second element is an array
@return array
|
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Path.php#L112-L165
|
yangyao/queue
|
src/Handler/MysqlHandler.php
|
MysqlHandler.get
|
public function get($queue_name)
{
if ($this->connector->exec('UPDATE '.$this->table.' force index(PRIMARY) SET owner_thread_id=GREATEST(CONNECTION_ID() ,(@msgID:=id)*0),last_cosume_time=? WHERE queue_name=? and owner_thread_id=-1 order by id LIMIT 1;', [time(), $queue_name]))
{
$row = $this->connector->query('select id, worker, params from '.$this->table.' where id=@msgID')->fetchColumn();
return $row;
}
return false;
}
|
php
|
public function get($queue_name)
{
if ($this->connector->exec('UPDATE '.$this->table.' force index(PRIMARY) SET owner_thread_id=GREATEST(CONNECTION_ID() ,(@msgID:=id)*0),last_cosume_time=? WHERE queue_name=? and owner_thread_id=-1 order by id LIMIT 1;', [time(), $queue_name]))
{
$row = $this->connector->query('select id, worker, params from '.$this->table.' where id=@msgID')->fetchColumn();
return $row;
}
return false;
}
|
获取一个队列任务信息
@param string $queue_name 队列名称
@return array $row
|
https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Handler/MysqlHandler.php#L26-L35
|
phPoirot/Client-OAuth2
|
src/Client.php
|
Client.attainAuthorizationUrl
|
function attainAuthorizationUrl(iGrantAuthorizeRequest $grant)
{
# Build Authorize Url
$grantParams = $grant->assertAuthorizeParams();
$response = $this->call( new GetAuthorizeUrl($grantParams) );
if ( $ex = $response->hasException() )
throw $ex;
return $response->expected();
}
|
php
|
function attainAuthorizationUrl(iGrantAuthorizeRequest $grant)
{
# Build Authorize Url
$grantParams = $grant->assertAuthorizeParams();
$response = $this->call( new GetAuthorizeUrl($grantParams) );
if ( $ex = $response->hasException() )
throw $ex;
return $response->expected();
}
|
Builds the authorization URL
- look in grants available with response_type code
- make url from grant parameters
@param iGrantAuthorizeRequest $grant Using specific grant
@return string Authorization URL
@throws \Exception
|
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L65-L76
|
phPoirot/Client-OAuth2
|
src/Client.php
|
Client.attainAccessToken
|
function attainAccessToken(iGrantTokenRequest $grant)
{
// client_id, secret_key can send as Authorization Header Or Post Request Body
$grantParams = $grant->assertTokenParams();
$response = $this->call( new Token($grantParams) );
if ( $ex = $response->hasException() )
throw $ex;
/** @var DataEntity $r */
$r = $response->expected();
if (! $r->get('access_token') )
// It not fulfilled with access_token; in case of two step validation like single-signin
// return response otherwise access token
return $r;
return new AccessTokenObject($r);
}
|
php
|
function attainAccessToken(iGrantTokenRequest $grant)
{
// client_id, secret_key can send as Authorization Header Or Post Request Body
$grantParams = $grant->assertTokenParams();
$response = $this->call( new Token($grantParams) );
if ( $ex = $response->hasException() )
throw $ex;
/** @var DataEntity $r */
$r = $response->expected();
if (! $r->get('access_token') )
// It not fulfilled with access_token; in case of two step validation like single-signin
// return response otherwise access token
return $r;
return new AccessTokenObject($r);
}
|
Requests an access token using a specified grant.
@param iGrantTokenRequest $grant
@return iAccessTokenObject|DataEntity
@throws \Exception
|
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L86-L104
|
phPoirot/Client-OAuth2
|
src/Client.php
|
Client.withGrant
|
function withGrant($grantTypeName, array $overrideOptions = [])
{
$options = [
'scopes' => $this->defaultScopes,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
];
if (! empty($overrideOptions) )
$options = array_merge($options, $overrideOptions);
if ($grantTypeName instanceof ipGrantRequest) {
$grant = clone $grantTypeName;
$grant->with($grant::parseWith($options));
} else {
$grant = $this->plugins()->fresh($grantTypeName, $options);
}
return $grant;
}
|
php
|
function withGrant($grantTypeName, array $overrideOptions = [])
{
$options = [
'scopes' => $this->defaultScopes,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
];
if (! empty($overrideOptions) )
$options = array_merge($options, $overrideOptions);
if ($grantTypeName instanceof ipGrantRequest) {
$grant = clone $grantTypeName;
$grant->with($grant::parseWith($options));
} else {
$grant = $this->plugins()->fresh($grantTypeName, $options);
}
return $grant;
}
|
Retrieve Specific Grant Type
- inject default client configuration within grant object
example code:
$auth->withGrant(
GrantPlugins::AUTHORIZATION_CODE
, ['state' => 'custom_state'] )
@param string|ipGrantRequest $grantTypeName
@param array $overrideOptions
@return aGrantRequest
|
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L122-L142
|
phPoirot/Client-OAuth2
|
src/Client.php
|
Client.platform
|
protected function platform()
{
if (! $this->platform )
$this->platform = new PlatformRest;
# Default Options Overriding
$this->platform->setServerUrl( $this->serverUrl );
return $this->platform;
}
|
php
|
protected function platform()
{
if (! $this->platform )
$this->platform = new PlatformRest;
# Default Options Overriding
$this->platform->setServerUrl( $this->serverUrl );
return $this->platform;
}
|
Get Client Platform
- used by request to build params for
server execution call and response
@return iPlatform
|
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L166-L176
|
Zoddo/php-irc
|
IrcConnection.php
|
IrcConnection.run
|
public function run()
{
$this->connect();
try
{
while (!$this->feof())
{
$data = $this->irc_read(60); // We wait 60 seconds but it's arbitrary and can be safely modified...
if ($data === false)
{
continue;
}
$this->callListeners($data);
}
}
catch (SocketDisconnectedException $e)
{
return $this;
}
return $this;
}
|
php
|
public function run()
{
$this->connect();
try
{
while (!$this->feof())
{
$data = $this->irc_read(60); // We wait 60 seconds but it's arbitrary and can be safely modified...
if ($data === false)
{
continue;
}
$this->callListeners($data);
}
}
catch (SocketDisconnectedException $e)
{
return $this;
}
return $this;
}
|
Run the bot automatically (you need to use events to do actions)
@return $this when the socket is disconnected
|
https://github.com/Zoddo/php-irc/blob/373b7da57b321174e7ffa09edabf99a95db6dfc8/IrcConnection.php#L71-L94
|
digipolisgent/robo-digipolis-deploy
|
src/BackupManager/Factory/CompressorProviderFactory.php
|
CompressorProviderFactory.create
|
public static function create()
{
// Add all default compressors.
$compressorProvider = new CompressorProvider();
$compressorProvider->add(new TarCompressor());
$compressorProvider->add(new GzipCompressor());
$compressorProvider->add(new NullCompressor());
return $compressorProvider;
}
|
php
|
public static function create()
{
// Add all default compressors.
$compressorProvider = new CompressorProvider();
$compressorProvider->add(new TarCompressor());
$compressorProvider->add(new GzipCompressor());
$compressorProvider->add(new NullCompressor());
return $compressorProvider;
}
|
{@inheritdoc}
|
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/BackupManager/Factory/CompressorProviderFactory.php#L16-L25
|
3ev/wordpress-core
|
src/Tev/View/Renderer.php
|
Renderer.render
|
public function render($filename, $vars = array())
{
$localTemplate = $this->templateDir . '/' . $filename;
$themeTemplate = locate_template($filename);
if (!file_exists($localTemplate) && !file_exists($themeTemplate)) {
throw new NotFoundException("View at $localTemplate or $themeTemplate not found");
}
$this->viewData = $vars;
$template = file_exists($localTemplate) ? $localTemplate : $themeTemplate;
ob_start();
include($template);
$view = ob_get_contents();
ob_end_clean();
return $view;
}
|
php
|
public function render($filename, $vars = array())
{
$localTemplate = $this->templateDir . '/' . $filename;
$themeTemplate = locate_template($filename);
if (!file_exists($localTemplate) && !file_exists($themeTemplate)) {
throw new NotFoundException("View at $localTemplate or $themeTemplate not found");
}
$this->viewData = $vars;
$template = file_exists($localTemplate) ? $localTemplate : $themeTemplate;
ob_start();
include($template);
$view = ob_get_contents();
ob_end_clean();
return $view;
}
|
Renders a template file.
Assigns all $var keys to $this->$key for us in template.
@param string $filename Full-filename
@param array $vars View variables
@return string Rendered view
@throws \Tev\View\Exception\NotFoundException If view file not found
|
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/View/Renderer.php#L51-L70
|
apitude/user
|
src/OAuth/OauthControllerProvider.php
|
OauthControllerProvider.connect
|
public function connect(Application $app)
{
/** @var ControllerCollection $controllers */
$controllers = $app['controllers_factory'];
$controllers->get('/', 'oauth.controller::signinRedirect');
$controllers->get('/signin', 'oauth.controller::signinGet');
$controllers->post('/signin', 'oauth.controller::signinPost');
$controllers->post('/authorize', 'oauth.controller::authorize');
$controllers->get('/access_token', 'oauth.controller::accessToken');
$controllers->post('/access_token', 'oauth.controller::accessToken');
$controllers->get('/token', 'oauth.controller::tokenInfo');
return $controllers;
}
|
php
|
public function connect(Application $app)
{
/** @var ControllerCollection $controllers */
$controllers = $app['controllers_factory'];
$controllers->get('/', 'oauth.controller::signinRedirect');
$controllers->get('/signin', 'oauth.controller::signinGet');
$controllers->post('/signin', 'oauth.controller::signinPost');
$controllers->post('/authorize', 'oauth.controller::authorize');
$controllers->get('/access_token', 'oauth.controller::accessToken');
$controllers->post('/access_token', 'oauth.controller::accessToken');
$controllers->get('/token', 'oauth.controller::tokenInfo');
return $controllers;
}
|
Returns routes to connect to the given application.
@param Application $app An Application instance
@return ControllerCollection A ControllerCollection instance
|
https://github.com/apitude/user/blob/24adf733cf628d321c2bcae328c383113928d019/src/OAuth/OauthControllerProvider.php#L18-L31
|
daijulong/sms
|
src/Supports/SmsAgent.php
|
SmsAgent.register
|
public static function register($name, Agent $agent)
{
if (!is_string($name) || $name == '') {
throw new SmsException('代理器:' . $name . ' 无效!');
}
self::$agents[$name] = $agent;
}
|
php
|
public static function register($name, Agent $agent)
{
if (!is_string($name) || $name == '') {
throw new SmsException('代理器:' . $name . ' 无效!');
}
self::$agents[$name] = $agent;
}
|
注册代理器
@static
@throws SmsException
@param string $name 代理器名称
@param Agent $agent 代理器
|
https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/Supports/SmsAgent.php#L20-L26
|
daijulong/sms
|
src/Supports/SmsAgent.php
|
SmsAgent.init
|
public static function init()
{
$agents = SmsConfig::getAgents();
if (!empty($agents)) {
$ext_agent_namespace = SmsConfig::getAgentExtNamespace();
foreach ($agents as $name => $config) {
//优先注册扩展代理器
if ($ext_agent_namespace != '') {
$ext_agent_classname = $ext_agent_namespace . $name;
if (class_exists($ext_agent_classname)) {
self::register($name, new $ext_agent_classname($config));
continue;
}
}
$agent_classname = 'Daijulong\\Sms\\Agents\\' . $name;
if (class_exists($agent_classname)) {
self::register($name, new $agent_classname($config));
}
}
}
}
|
php
|
public static function init()
{
$agents = SmsConfig::getAgents();
if (!empty($agents)) {
$ext_agent_namespace = SmsConfig::getAgentExtNamespace();
foreach ($agents as $name => $config) {
//优先注册扩展代理器
if ($ext_agent_namespace != '') {
$ext_agent_classname = $ext_agent_namespace . $name;
if (class_exists($ext_agent_classname)) {
self::register($name, new $ext_agent_classname($config));
continue;
}
}
$agent_classname = 'Daijulong\\Sms\\Agents\\' . $name;
if (class_exists($agent_classname)) {
self::register($name, new $agent_classname($config));
}
}
}
}
|
初始化
注册配置中的agents所声明的代理器
@static
|
https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/Supports/SmsAgent.php#L35-L55
|
daijulong/sms
|
src/Supports/SmsAgent.php
|
SmsAgent.getAgent
|
public static function getAgent(string $agent): Agent
{
if (!isset(self::$agents[$agent])) {
throw new SmsAgentException('The agent "' . $agent . '" not registered!');
}
return self::$agents[$agent];
}
|
php
|
public static function getAgent(string $agent): Agent
{
if (!isset(self::$agents[$agent])) {
throw new SmsAgentException('The agent "' . $agent . '" not registered!');
}
return self::$agents[$agent];
}
|
获取代理器
代理器须已经被注册
@static
@param string $agent
@return Agent
@throws SmsAgentException
|
https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/Supports/SmsAgent.php#L67-L73
|
makinacorpus/drupal-calista
|
src/Portlet/AbstractPortlet.php
|
AbstractPortlet.renderPage
|
protected function renderPage($datasourceId, $template, array $baseQuery = [], $sortField = null, $sortOrder = Query::SORT_DESC, $limit = 10)
{
$datasource = $this->viewFactory->getDatasource($datasourceId);
$inputDefinition = new InputDefinition($datasource, [
'base_query' => $baseQuery,
'limit_default' => $limit,
'pager_enable' => false,
'search_enable' => false,
'sort_default_field' => $sortField ? $sortField : '',
'sort_default_order' => $sortOrder,
]);
$viewDefinition = new ViewDefinition([
'enabled_filters' => [],
'properties' => [],
'show_filters' => false,
'show_pager' => false,
'show_search' => false,
'show_sort' => false,
'templates' => ['default' => $template],
'view_type' => 'twig_page',
]);
$query = $inputDefinition->createQueryFromArray([]);
$items = $datasource->getItems($query);
return $this->viewFactory->getView('twig_page')->render($viewDefinition, $items, $query);
}
|
php
|
protected function renderPage($datasourceId, $template, array $baseQuery = [], $sortField = null, $sortOrder = Query::SORT_DESC, $limit = 10)
{
$datasource = $this->viewFactory->getDatasource($datasourceId);
$inputDefinition = new InputDefinition($datasource, [
'base_query' => $baseQuery,
'limit_default' => $limit,
'pager_enable' => false,
'search_enable' => false,
'sort_default_field' => $sortField ? $sortField : '',
'sort_default_order' => $sortOrder,
]);
$viewDefinition = new ViewDefinition([
'enabled_filters' => [],
'properties' => [],
'show_filters' => false,
'show_pager' => false,
'show_search' => false,
'show_sort' => false,
'templates' => ['default' => $template],
'view_type' => 'twig_page',
]);
$query = $inputDefinition->createQueryFromArray([]);
$items = $datasource->getItems($query);
return $this->viewFactory->getView('twig_page')->render($viewDefinition, $items, $query);
}
|
Render page
@param string $datasourceId
@param string $template
@param array $baseQuery
@param string $sortField
@param string $sortOrder
@param int $limit
@return string
|
https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/Portlet/AbstractPortlet.php#L67-L93
|
ekyna/AdminBundle
|
Helper/ResourceHelper.php
|
ResourceHelper.isGranted
|
public function isGranted($resource, $action = 'view')
{
return $this->aclOperator->isAccessGranted($resource, $this->getPermission($action));
}
|
php
|
public function isGranted($resource, $action = 'view')
{
return $this->aclOperator->isAccessGranted($resource, $this->getPermission($action));
}
|
Returns whether the user has access granted or not on the given resource for the given action.
@param mixed $resource
@param string $action
@return boolean
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L87-L90
|
ekyna/AdminBundle
|
Helper/ResourceHelper.php
|
ResourceHelper.generateResourcePath
|
public function generateResourcePath($resource, $action = 'show')
{
$configuration = $this->registry->findConfiguration($resource);
$routeName = $configuration->getRoute($action);
$route = $this->findRoute($routeName);
$requirements = $route->getRequirements();
$accessor = PropertyAccess::createPropertyAccessor();
$entities = [];
if (is_object($resource)) {
$entities[$configuration->getResourceName()] = $resource;
$current = $resource;
while (null !== $configuration->getParentId()) {
$configuration = $this->registry->findConfiguration($configuration->getParentId());
$current = $accessor->getValue($current, $configuration->getResourceName());
$entities[$configuration->getResourceName()] = $current;
}
}
$parameters = [];
foreach ($entities as $name => $resource) {
if (array_key_exists($name . 'Id', $requirements)) {
$parameters[$name . 'Id'] = $accessor->getValue($resource, 'id');
}
}
return $this->router->generate($routeName, $parameters);
}
|
php
|
public function generateResourcePath($resource, $action = 'show')
{
$configuration = $this->registry->findConfiguration($resource);
$routeName = $configuration->getRoute($action);
$route = $this->findRoute($routeName);
$requirements = $route->getRequirements();
$accessor = PropertyAccess::createPropertyAccessor();
$entities = [];
if (is_object($resource)) {
$entities[$configuration->getResourceName()] = $resource;
$current = $resource;
while (null !== $configuration->getParentId()) {
$configuration = $this->registry->findConfiguration($configuration->getParentId());
$current = $accessor->getValue($current, $configuration->getResourceName());
$entities[$configuration->getResourceName()] = $current;
}
}
$parameters = [];
foreach ($entities as $name => $resource) {
if (array_key_exists($name . 'Id', $requirements)) {
$parameters[$name . 'Id'] = $accessor->getValue($resource, 'id');
}
}
return $this->router->generate($routeName, $parameters);
}
|
Generates an admin path for the given resource and action.
@param object $resource
@param string $action
@throws \RuntimeException
@return string
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L102-L131
|
ekyna/AdminBundle
|
Helper/ResourceHelper.php
|
ResourceHelper.getPermission
|
public function getPermission($action)
{
$action = strtoupper($action);
if ($action == 'LIST') {
return 'VIEW';
} elseif ($action == 'SHOW') {
return 'VIEW';
} elseif ($action == 'NEW') {
return 'CREATE';
} elseif ($action == 'EDIT') {
return 'EDIT';
} elseif ($action == 'REMOVE') {
return 'DELETE';
}
return $action;
}
|
php
|
public function getPermission($action)
{
$action = strtoupper($action);
if ($action == 'LIST') {
return 'VIEW';
} elseif ($action == 'SHOW') {
return 'VIEW';
} elseif ($action == 'NEW') {
return 'CREATE';
} elseif ($action == 'EDIT') {
return 'EDIT';
} elseif ($action == 'REMOVE') {
return 'DELETE';
}
return $action;
}
|
Returns the permission for the given action.
@param string $action
@return string
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L140-L155
|
ekyna/AdminBundle
|
Helper/ResourceHelper.php
|
ResourceHelper.findRoute
|
public function findRoute($routeName)
{
// TODO create a route finder ? (same in CmsBundle BreadcrumbBuilder)
$i18nRouterClass = 'JMS\I18nRoutingBundle\Router\I18nRouterInterface';
if (interface_exists($i18nRouterClass) && $this->router instanceof $i18nRouterClass) {
$route = $this->router->getOriginalRouteCollection()->get($routeName);
} else {
$route = $this->router->getRouteCollection()->get($routeName);
}
if (null === $route) {
throw new \RuntimeException(sprintf('Route "%s" not found.', $routeName));
}
return $route;
}
|
php
|
public function findRoute($routeName)
{
// TODO create a route finder ? (same in CmsBundle BreadcrumbBuilder)
$i18nRouterClass = 'JMS\I18nRoutingBundle\Router\I18nRouterInterface';
if (interface_exists($i18nRouterClass) && $this->router instanceof $i18nRouterClass) {
$route = $this->router->getOriginalRouteCollection()->get($routeName);
} else {
$route = $this->router->getRouteCollection()->get($routeName);
}
if (null === $route) {
throw new \RuntimeException(sprintf('Route "%s" not found.', $routeName));
}
return $route;
}
|
Finds the route definition.
@param string $routeName
@return null|\Symfony\Component\Routing\Route
|
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L163-L176
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.setupDefaultMachine
|
protected function setupDefaultMachine(array $config)
{
// Name of inputs and outputs with properties
$io_name = isset($config['io_name']) ? (string) $config['io_name'] : 'item';
// Create default transitions?
$no_default_transitions = !empty($config['crud_machine_no_default_transitions']); /// @deprecated
// Exists state only
$this->states = array_replace_recursive($no_default_transitions ? array() : array(
'exists' => array(
'label' => _('Exists'),
'description' => '',
),
), $this->states ? : []);
// Simple 'exists' state if not state select is not defined
if ($this->state_select === null) {
$this->state_select = '"exists"';
}
// Actions
$this->actions = array_replace_recursive(array(
'create' => array(
'label' => _('Create'),
'description' => _('Create a new item'),
'transitions' => $no_default_transitions ? array() : array(
'' => array(
'targets' => array('exists'),
),
),
'returns' => self::RETURNS_NEW_ID,
'block' => array(
'inputs' => array(
$io_name => array()
),
'outputs' => array(
'ref' => 'return_value'
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
'edit' => array(
'label' => _('Edit'),
'description' => _('Modify item'),
'transitions' => $no_default_transitions ? array() : array(
'exists' => array(
'targets' => array('exists'),
),
),
'block' => array(
'inputs' => array(
'ref' => array(),
$io_name => array()
),
'outputs' => array(
'ref' => 'ref'
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
'delete' => array(
'label' => _('Delete'),
'description' => _('Delete item'),
'weight' => 80,
'transitions' => $no_default_transitions ? array() : array(
'exists' => array(
'targets' => array(''),
),
),
'block' => array(
'inputs' => array(
'ref' => array(),
),
'outputs' => array(
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
), $this->actions ? : []);
}
|
php
|
protected function setupDefaultMachine(array $config)
{
// Name of inputs and outputs with properties
$io_name = isset($config['io_name']) ? (string) $config['io_name'] : 'item';
// Create default transitions?
$no_default_transitions = !empty($config['crud_machine_no_default_transitions']); /// @deprecated
// Exists state only
$this->states = array_replace_recursive($no_default_transitions ? array() : array(
'exists' => array(
'label' => _('Exists'),
'description' => '',
),
), $this->states ? : []);
// Simple 'exists' state if not state select is not defined
if ($this->state_select === null) {
$this->state_select = '"exists"';
}
// Actions
$this->actions = array_replace_recursive(array(
'create' => array(
'label' => _('Create'),
'description' => _('Create a new item'),
'transitions' => $no_default_transitions ? array() : array(
'' => array(
'targets' => array('exists'),
),
),
'returns' => self::RETURNS_NEW_ID,
'block' => array(
'inputs' => array(
$io_name => array()
),
'outputs' => array(
'ref' => 'return_value'
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
'edit' => array(
'label' => _('Edit'),
'description' => _('Modify item'),
'transitions' => $no_default_transitions ? array() : array(
'exists' => array(
'targets' => array('exists'),
),
),
'block' => array(
'inputs' => array(
'ref' => array(),
$io_name => array()
),
'outputs' => array(
'ref' => 'ref'
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
'delete' => array(
'label' => _('Delete'),
'description' => _('Delete item'),
'weight' => 80,
'transitions' => $no_default_transitions ? array() : array(
'exists' => array(
'targets' => array(''),
),
),
'block' => array(
'inputs' => array(
'ref' => array(),
),
'outputs' => array(
),
'accepted_exceptions' => array(
'PDOException' => true,
),
),
),
), $this->actions ? : []);
}
|
Setup basic CRUD machine.
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L95-L181
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.create
|
protected function create(Reference $ref, $properties)
{
// filter out unknown keys
$properties = array_intersect_key($properties, $this->properties);
if (!$ref->isNullRef()) {
$properties = array_merge($properties, array_combine($this->describeId(), (array) $ref->id));
}
// Set times
if ($this->time_created_table_column) {
$properties[$this->time_created_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
if ($this->time_modified_table_column) {
$properties[$this->time_modified_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
if (empty($properties)) {
throw new \InvalidArgumentException('No valid properties provided.');
}
// Set owner
if ($this->user_id_table_column) {
$properties[$this->user_id_table_column] = $this->auth->getUserId();
}
// Check permission of owning machine
if ($this->owner_relation && $this->owner_create_transition) {
$ref_ref = $this->resolveMachineReference($this->owner_relation, $properties);
if (!$ref_ref->machine->isTransitionAllowed($ref_ref, $this->owner_create_transition)) {
throw new \RuntimeException(sprintf(
'Permission denied to create machine %s because transition %s of %s is not allowed.',
$this->machine_type, $this->owner_create_transition, $ref->machine_type
));
}
}
// Generate random ID
if ($this->generate_random_id) {
list($random_property) = $this->describeId();
if (empty($properties[$random_property])) {
$properties[$random_property] = mt_rand(1, 2147483647);
}
}
// Insert
$data = $this->encodeProperties($properties);
$q = $this->flupdo->insert()->into($this->flupdo->quoteIdent($this->table));
foreach ($data as $k => $v) {
$q->insert($this->flupdo->quoteIdent($k));
}
$q->values([$data]);
$n = $q->debugDump()->exec();
if (!$n) {
// Insert failed
return false;
}
// Return ID of inserted row
if ($ref->isNullRef()) {
$id_keys = $this->describeId();
$id = array();
foreach ($id_keys as $k) {
if (isset($properties[$k])) {
$id[] = $properties[$k];
} else {
// If part of ID is missing, it must be autoincremented
// column, otherwise the insert would have failed.
$id[] = $this->flupdo->lastInsertId();
}
}
} else {
$id = $ref->id;
}
if ($this->nested_sets_enabled) {
$this->recalculateTree();
}
return $id;
}
|
php
|
protected function create(Reference $ref, $properties)
{
// filter out unknown keys
$properties = array_intersect_key($properties, $this->properties);
if (!$ref->isNullRef()) {
$properties = array_merge($properties, array_combine($this->describeId(), (array) $ref->id));
}
// Set times
if ($this->time_created_table_column) {
$properties[$this->time_created_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
if ($this->time_modified_table_column) {
$properties[$this->time_modified_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
if (empty($properties)) {
throw new \InvalidArgumentException('No valid properties provided.');
}
// Set owner
if ($this->user_id_table_column) {
$properties[$this->user_id_table_column] = $this->auth->getUserId();
}
// Check permission of owning machine
if ($this->owner_relation && $this->owner_create_transition) {
$ref_ref = $this->resolveMachineReference($this->owner_relation, $properties);
if (!$ref_ref->machine->isTransitionAllowed($ref_ref, $this->owner_create_transition)) {
throw new \RuntimeException(sprintf(
'Permission denied to create machine %s because transition %s of %s is not allowed.',
$this->machine_type, $this->owner_create_transition, $ref->machine_type
));
}
}
// Generate random ID
if ($this->generate_random_id) {
list($random_property) = $this->describeId();
if (empty($properties[$random_property])) {
$properties[$random_property] = mt_rand(1, 2147483647);
}
}
// Insert
$data = $this->encodeProperties($properties);
$q = $this->flupdo->insert()->into($this->flupdo->quoteIdent($this->table));
foreach ($data as $k => $v) {
$q->insert($this->flupdo->quoteIdent($k));
}
$q->values([$data]);
$n = $q->debugDump()->exec();
if (!$n) {
// Insert failed
return false;
}
// Return ID of inserted row
if ($ref->isNullRef()) {
$id_keys = $this->describeId();
$id = array();
foreach ($id_keys as $k) {
if (isset($properties[$k])) {
$id[] = $properties[$k];
} else {
// If part of ID is missing, it must be autoincremented
// column, otherwise the insert would have failed.
$id[] = $this->flupdo->lastInsertId();
}
}
} else {
$id = $ref->id;
}
if ($this->nested_sets_enabled) {
$this->recalculateTree();
}
return $id;
}
|
Create
$ref may be nullRef, then auto increment is used.
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L189-L270
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.edit
|
protected function edit(Reference $ref, $properties)
{
// filter out unknown keys
$properties = array_intersect_key($properties, $this->properties);
if (empty($properties)) {
throw new \InvalidArgumentException('No valid properties provided.');
}
// Set modification time
if ($this->time_modified_table_column) {
$properties[$this->time_modified_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
// Build update query
$q = $this->flupdo->update($this->queryGetThisTable($this->flupdo));
$this->queryAddPrimaryKeyWhere($q, $ref->id);
foreach ($this->encodeProperties($properties) as $k => $v) {
if ($v instanceof \Smalldb\Flupdo\FlupdoRawSql || $v instanceof \Smalldb\Flupdo\FlupdoBuilder) {
$q->set(array($this->flupdo->quoteIdent($k).' = ', $v));
} else {
$q->set($q->quoteIdent($k).' = ?', $v);
}
}
// Add calculated properties
foreach ($this->properties as $pi => $p) {
if (!empty($p['calculated']) && isset($p['sql_update'])) {
$q->set($q->quoteIdent($pi).' = '.$p['sql_update']);
}
}
$n = $q->debugDump()->exec();
if ($n !== FALSE) {
if ($this->nested_sets_enabled) {
$this->recalculateTree();
}
return true;
} else {
return false;
}
}
|
php
|
protected function edit(Reference $ref, $properties)
{
// filter out unknown keys
$properties = array_intersect_key($properties, $this->properties);
if (empty($properties)) {
throw new \InvalidArgumentException('No valid properties provided.');
}
// Set modification time
if ($this->time_modified_table_column) {
$properties[$this->time_modified_table_column] = new \Smalldb\Flupdo\FlupdoRawSql('CURRENT_TIMESTAMP');
}
// Build update query
$q = $this->flupdo->update($this->queryGetThisTable($this->flupdo));
$this->queryAddPrimaryKeyWhere($q, $ref->id);
foreach ($this->encodeProperties($properties) as $k => $v) {
if ($v instanceof \Smalldb\Flupdo\FlupdoRawSql || $v instanceof \Smalldb\Flupdo\FlupdoBuilder) {
$q->set(array($this->flupdo->quoteIdent($k).' = ', $v));
} else {
$q->set($q->quoteIdent($k).' = ?', $v);
}
}
// Add calculated properties
foreach ($this->properties as $pi => $p) {
if (!empty($p['calculated']) && isset($p['sql_update'])) {
$q->set($q->quoteIdent($pi).' = '.$p['sql_update']);
}
}
$n = $q->debugDump()->exec();
if ($n !== FALSE) {
if ($this->nested_sets_enabled) {
$this->recalculateTree();
}
return true;
} else {
return false;
}
}
|
Edit
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L276-L317
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.delete
|
protected function delete(Reference $ref)
{
// build update query
$q = $this->flupdo->delete()->from($this->flupdo->quoteIdent($this->table));
$this->queryAddPrimaryKeyWhere($q, $ref->id);
$n = $q->debugDump()->exec();
if ($n) {
return true;
} else {
return false;
}
}
|
php
|
protected function delete(Reference $ref)
{
// build update query
$q = $this->flupdo->delete()->from($this->flupdo->quoteIdent($this->table));
$this->queryAddPrimaryKeyWhere($q, $ref->id);
$n = $q->debugDump()->exec();
if ($n) {
return true;
} else {
return false;
}
}
|
Delete
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L323-L336
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.recalculateTree
|
protected function recalculateTree()
{
if (!$this->nested_sets_enabled) {
throw new \RuntimeException('Nested sets are disabled for this entity.');
}
$q_table = $this->flupdo->quoteIdent($this->table);
$cols = $this->nested_sets_table_columns;
$c_order_by = $this->nested_sets_order_by;
$c_id = $this->flupdo->quoteIdent($cols['id']);
$c_parent_id = $this->flupdo->quoteIdent($cols['parent_id']);
$c_left = $this->flupdo->quoteIdent($cols['left']);
$c_right = $this->flupdo->quoteIdent($cols['right']);
$c_depth = $this->flupdo->quoteIdent($cols['depth']);
$set = $this->flupdo->select($c_id)
->from($q_table)
->where("$c_parent_id IS NULL")
->orderBy($c_order_by)
->query();
$this->recalculateSubTree($set, 1, 0, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth);
}
|
php
|
protected function recalculateTree()
{
if (!$this->nested_sets_enabled) {
throw new \RuntimeException('Nested sets are disabled for this entity.');
}
$q_table = $this->flupdo->quoteIdent($this->table);
$cols = $this->nested_sets_table_columns;
$c_order_by = $this->nested_sets_order_by;
$c_id = $this->flupdo->quoteIdent($cols['id']);
$c_parent_id = $this->flupdo->quoteIdent($cols['parent_id']);
$c_left = $this->flupdo->quoteIdent($cols['left']);
$c_right = $this->flupdo->quoteIdent($cols['right']);
$c_depth = $this->flupdo->quoteIdent($cols['depth']);
$set = $this->flupdo->select($c_id)
->from($q_table)
->where("$c_parent_id IS NULL")
->orderBy($c_order_by)
->query();
$this->recalculateSubTree($set, 1, 0, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth);
}
|
Recalculate nested-sets tree indices
To use this feature a parent, left, right and depth columns must be specified.
Composed primary keys are not supported yet.
Three extra columns are required: tree_left, tree_right, tree_depth
(ints, all nullable). This function will update them according to id
and parent_id columns.
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L350-L372
|
smalldb/libSmalldb
|
class/FlupdoCrudMachine.php
|
FlupdoCrudMachine.recalculateSubTree
|
private function recalculateSubTree($set, $left, $depth, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth)
{
foreach($set as $row) {
$id = $row['id'];
$this->flupdo->update($q_table)
->set("$c_left = ?", $left)
->set("$c_depth = ?", $depth)
->where("$c_id = ?", $id)
->exec();
$sub_set = $this->flupdo->select($c_id)
->from($q_table)
->where("$c_parent_id = ?", $id)
->orderBy($c_order_by)
->query();
$left = $this->recalculateSubTree($sub_set, $left + 1, $depth + 1,
$q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth);
$this->flupdo->update($q_table)
->set("$c_right = ?", $left)
->where("$c_id = ?", $id)
->exec();
$left++;
}
return $left;
}
|
php
|
private function recalculateSubTree($set, $left, $depth, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth)
{
foreach($set as $row) {
$id = $row['id'];
$this->flupdo->update($q_table)
->set("$c_left = ?", $left)
->set("$c_depth = ?", $depth)
->where("$c_id = ?", $id)
->exec();
$sub_set = $this->flupdo->select($c_id)
->from($q_table)
->where("$c_parent_id = ?", $id)
->orderBy($c_order_by)
->query();
$left = $this->recalculateSubTree($sub_set, $left + 1, $depth + 1,
$q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth);
$this->flupdo->update($q_table)
->set("$c_right = ?", $left)
->where("$c_id = ?", $id)
->exec();
$left++;
}
return $left;
}
|
Recalculate given subtree.
@see recalculateTree()
|
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L380-L408
|
alphacomm/alpharpc
|
src/AlphaRPC/Manager/Protocol/QueueStatusResponse.php
|
QueueStatusResponse.fromMessage
|
public static function fromMessage(Message $msg)
{
$queueStatus = array();
while ($msg->peek() !== null) {
$action = $msg->shift();
$queueStatus[$action] = array(
'action' => $action,
'queue' => $msg->shift(),
'busy' => $msg->shift(),
'available' => $msg->shift()
);
}
return new self($queueStatus);
}
|
php
|
public static function fromMessage(Message $msg)
{
$queueStatus = array();
while ($msg->peek() !== null) {
$action = $msg->shift();
$queueStatus[$action] = array(
'action' => $action,
'queue' => $msg->shift(),
'busy' => $msg->shift(),
'available' => $msg->shift()
);
}
return new self($queueStatus);
}
|
Creates an instance from the Message.
@param Message $msg
@return QueueStatusResponse
|
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/QueueStatusResponse.php#L61-L75
|
alphacomm/alpharpc
|
src/AlphaRPC/Manager/Protocol/QueueStatusResponse.php
|
QueueStatusResponse.toMessage
|
public function toMessage()
{
$m = new Message();
foreach ($this->queueStatus as $action) {
$m->push($action['action']);
$m->push($action['queue']);
$m->push($action['busy']);
$m->push($action['available']);
}
return $m;
}
|
php
|
public function toMessage()
{
$m = new Message();
foreach ($this->queueStatus as $action) {
$m->push($action['action']);
$m->push($action['queue']);
$m->push($action['busy']);
$m->push($action['available']);
}
return $m;
}
|
Create a new Message from this instance.
@return Message
|
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/Protocol/QueueStatusResponse.php#L82-L93
|
harmony-project/modular-bundle
|
source/Request/ModuleParamConverter.php
|
ModuleParamConverter.apply
|
public function apply(Request $request, ParamConverterConfiguration $configuration)
{
$name = $configuration->getName();
$object = $this->manager->getCurrentModule();
$request->attributes->set($name, $object);
return true;
}
|
php
|
public function apply(Request $request, ParamConverterConfiguration $configuration)
{
$name = $configuration->getName();
$object = $this->manager->getCurrentModule();
$request->attributes->set($name, $object);
return true;
}
|
{@inheritdoc}
@throws \InvalidArgumentException If one of the parameters has an invalid value
@throws ResourceNotFoundException If no module was matched to the request
|
https://github.com/harmony-project/modular-bundle/blob/2813f7285eb5ae18d2ebe7dd1623fd0e032cfab7/source/Request/ModuleParamConverter.php#L46-L54
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine._setOptions
|
protected function _setOptions(array $options) {
if (isset($options['escape'])) {
if (!is_callable($options['escape'])) {
throw new InvalidArgumentException('Mustache constructor "escape" option must be callable');
}
$this->_escape = $options['escape'];
}
if (isset($options['charset'])) {
$this->_charset = $options['charset'];
}
if (isset($options['delimiters'])) {
$delims = $options['delimiters'];
if (!is_array($delims)) {
$delims = array_map('trim', explode(' ', $delims, 2));
}
$this->_otag = $delims[0];
$this->_ctag = $delims[1];
}
if (isset($options['pragmas'])) {
foreach ($options['pragmas'] as $pragma_name => $pragma_value) {
if (!in_array($pragma_name, $this->_pragmasImplemented, true)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
}
}
$this->_pragmas = $options['pragmas'];
}
if (isset($options['throws_exceptions'])) {
foreach ($options['throws_exceptions'] as $exception => $value) {
$this->_throwsExceptions[$exception] = $value;
}
}
}
|
php
|
protected function _setOptions(array $options) {
if (isset($options['escape'])) {
if (!is_callable($options['escape'])) {
throw new InvalidArgumentException('Mustache constructor "escape" option must be callable');
}
$this->_escape = $options['escape'];
}
if (isset($options['charset'])) {
$this->_charset = $options['charset'];
}
if (isset($options['delimiters'])) {
$delims = $options['delimiters'];
if (!is_array($delims)) {
$delims = array_map('trim', explode(' ', $delims, 2));
}
$this->_otag = $delims[0];
$this->_ctag = $delims[1];
}
if (isset($options['pragmas'])) {
foreach ($options['pragmas'] as $pragma_name => $pragma_value) {
if (!in_array($pragma_name, $this->_pragmasImplemented, true)) {
throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
}
}
$this->_pragmas = $options['pragmas'];
}
if (isset($options['throws_exceptions'])) {
foreach ($options['throws_exceptions'] as $exception => $value) {
$this->_throwsExceptions[$exception] = $value;
}
}
}
|
Helper function for setting options from constructor args.
@access protected
@param array $options
@return void
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L140-L175
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine.render
|
public function render($template = null, $view = null, $partials = null) {
if ($template === null) $template = $this->_template;
if ($partials !== null) $this->_partials = $partials;
$otag_orig = $this->_otag;
$ctag_orig = $this->_ctag;
// Including server properties in the view
//$view = array_merge($this->server->getAll(), $view);
$view['baseUrl'] = $this->server->siteUrl('');
if ($view) {
$this->_context = array($view);
} else if (empty($this->_context)) {
$this->_context = array($this);
}
$template = $this->_renderPragmas($template);
$template = $this->_renderTemplate($template);
$this->_otag = $otag_orig;
$this->_ctag = $ctag_orig;
return $template;
}
|
php
|
public function render($template = null, $view = null, $partials = null) {
if ($template === null) $template = $this->_template;
if ($partials !== null) $this->_partials = $partials;
$otag_orig = $this->_otag;
$ctag_orig = $this->_ctag;
// Including server properties in the view
//$view = array_merge($this->server->getAll(), $view);
$view['baseUrl'] = $this->server->siteUrl('');
if ($view) {
$this->_context = array($view);
} else if (empty($this->_context)) {
$this->_context = array($this);
}
$template = $this->_renderPragmas($template);
$template = $this->_renderTemplate($template);
$this->_otag = $otag_orig;
$this->_ctag = $ctag_orig;
return $template;
}
|
Render the given template and view object.
Defaults to the template and view passed to the class constructor unless a new one is provided.
Optionally, pass an associative array of partials as well.
@access public
@param string $template (default: null)
@param mixed $view (default: null)
@param array $partials (default: null)
@return string Rendered Mustache template.
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L211-L235
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine._renderTemplate
|
protected function _renderTemplate($template) {
if ($section = $this->_findSection($template)) {
list($before, $type, $tag_name, $content, $after) = $section;
$rendered_before = $this->_renderTags($before);
$rendered_content = '';
$val = $this->_getVariable($tag_name);
switch($type) {
// inverted section
case '^':
if (empty($val)) {
$rendered_content = $this->_renderTemplate($content);
}
break;
// regular section
case '#':
// higher order sections
if ($this->_varIsCallable($val)) {
$rendered_content = $this->_renderTemplate(call_user_func($val, $content));
} else if ($this->_varIsIterable($val)) {
foreach ($val as $local_context) {
$this->_pushContext($local_context);
$rendered_content .= $this->_renderTemplate($content);
$this->_popContext();
}
} else if ($val) {
if (is_array($val) || is_object($val)) {
$this->_pushContext($val);
$rendered_content = $this->_renderTemplate($content);
$this->_popContext();
} else {
$rendered_content = $this->_renderTemplate($content);
}
}
break;
}
return $rendered_before . $rendered_content . $this->_renderTemplate($after);
}
return $this->_renderTags($template);
}
|
php
|
protected function _renderTemplate($template) {
if ($section = $this->_findSection($template)) {
list($before, $type, $tag_name, $content, $after) = $section;
$rendered_before = $this->_renderTags($before);
$rendered_content = '';
$val = $this->_getVariable($tag_name);
switch($type) {
// inverted section
case '^':
if (empty($val)) {
$rendered_content = $this->_renderTemplate($content);
}
break;
// regular section
case '#':
// higher order sections
if ($this->_varIsCallable($val)) {
$rendered_content = $this->_renderTemplate(call_user_func($val, $content));
} else if ($this->_varIsIterable($val)) {
foreach ($val as $local_context) {
$this->_pushContext($local_context);
$rendered_content .= $this->_renderTemplate($content);
$this->_popContext();
}
} else if ($val) {
if (is_array($val) || is_object($val)) {
$this->_pushContext($val);
$rendered_content = $this->_renderTemplate($content);
$this->_popContext();
} else {
$rendered_content = $this->_renderTemplate($content);
}
}
break;
}
return $rendered_before . $rendered_content . $this->_renderTemplate($after);
}
return $this->_renderTags($template);
}
|
Internal render function, used for recursive calls.
@access protected
@param string $template
@return string Rendered Mustache template.
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L261-L304
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine._prepareSectionRegEx
|
protected function _prepareSectionRegEx($otag, $ctag) {
return sprintf(
'/(?:(?<=\\n)[ \\t]*)?%s(?:(?P<type>[%s])(?P<tag_name>.+?)|=(?P<delims>.*?)=)%s\\n?/s',
preg_quote($otag, '/'),
self::SECTION_TYPES,
preg_quote($ctag, '/')
);
}
|
php
|
protected function _prepareSectionRegEx($otag, $ctag) {
return sprintf(
'/(?:(?<=\\n)[ \\t]*)?%s(?:(?P<type>[%s])(?P<tag_name>.+?)|=(?P<delims>.*?)=)%s\\n?/s',
preg_quote($otag, '/'),
self::SECTION_TYPES,
preg_quote($ctag, '/')
);
}
|
Prepare a section RegEx string for the given opening/closing tags.
@access protected
@param string $otag
@param string $ctag
@return string
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L314-L321
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine._findSection
|
protected function _findSection($template) {
$regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
$section_start = null;
$section_type = null;
$content_start = null;
$search_offset = 0;
$section_stack = array();
$matches = array();
while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
if (isset($matches['delims'][0])) {
list($otag, $ctag) = explode(' ', $matches['delims'][0]);
$regEx = $this->_prepareSectionRegEx($otag, $ctag);
$search_offset = $matches[0][1] + strlen($matches[0][0]);
continue;
}
$match = $matches[0][0];
$offset = $matches[0][1];
$type = $matches['type'][0];
$tag_name = trim($matches['tag_name'][0]);
$search_offset = $offset + strlen($match);
switch ($type) {
case '^':
case '#':
if (empty($section_stack)) {
$section_start = $offset;
$section_type = $type;
$content_start = $search_offset;
}
array_push($section_stack, $tag_name);
break;
case '/':
if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
}
}
if (empty($section_stack)) {
// $before, $type, $tag_name, $content, $after
return array(
substr($template, 0, $section_start),
$section_type,
$tag_name,
substr($template, $content_start, $offset - $content_start),
substr($template, $search_offset),
);
}
break;
}
}
if (!empty($section_stack)) {
if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
}
}
}
|
php
|
protected function _findSection($template) {
$regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
$section_start = null;
$section_type = null;
$content_start = null;
$search_offset = 0;
$section_stack = array();
$matches = array();
while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
if (isset($matches['delims'][0])) {
list($otag, $ctag) = explode(' ', $matches['delims'][0]);
$regEx = $this->_prepareSectionRegEx($otag, $ctag);
$search_offset = $matches[0][1] + strlen($matches[0][0]);
continue;
}
$match = $matches[0][0];
$offset = $matches[0][1];
$type = $matches['type'][0];
$tag_name = trim($matches['tag_name'][0]);
$search_offset = $offset + strlen($match);
switch ($type) {
case '^':
case '#':
if (empty($section_stack)) {
$section_start = $offset;
$section_type = $type;
$content_start = $search_offset;
}
array_push($section_stack, $tag_name);
break;
case '/':
if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
}
}
if (empty($section_stack)) {
// $before, $type, $tag_name, $content, $after
return array(
substr($template, 0, $section_start),
$section_type,
$tag_name,
substr($template, $content_start, $offset - $content_start),
substr($template, $search_offset),
);
}
break;
}
}
if (!empty($section_stack)) {
if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
}
}
}
|
Extract the first section from $template.
@access protected
@param string $template
@return array $before, $type, $tag_name, $content and $after
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L330-L392
|
Etenil/assegai
|
src/assegai/modules/mustache/MustacheEngine.php
|
MustacheEngine._renderPragmas
|
protected function _renderPragmas($template) {
$this->_localPragmas = $this->_pragmas;
// no pragmas
if (strpos($template, $this->_otag . '%') === false) {
return $template;
}
$regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
}
|
php
|
protected function _renderPragmas($template) {
$this->_localPragmas = $this->_pragmas;
// no pragmas
if (strpos($template, $this->_otag . '%') === false) {
return $template;
}
$regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
}
|
Initialize pragmas and remove all pragma tags.
@access protected
@param string $template
@return string
|
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L417-L427
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.