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
|
---|---|---|---|---|---|---|---|
Phauthentic/password-hashers | src/AbstractPasswordHasher.php | AbstractPasswordHasher.checkSaltPositionArgument | protected function checkSaltPositionArgument($position): void
{
if (!in_array($position, [self::SALT_BEFORE, self::SALT_AFTER])) {
throw new InvalidArgumentException(sprintf(
'`%s` is an invalud argument, it has to be `` or ``',
$position,
self::SALT_BEFORE,
self::SALT_AFTER
));
}
} | php | protected function checkSaltPositionArgument($position): void
{
if (!in_array($position, [self::SALT_BEFORE, self::SALT_AFTER])) {
throw new InvalidArgumentException(sprintf(
'`%s` is an invalud argument, it has to be `` or ``',
$position,
self::SALT_BEFORE,
self::SALT_AFTER
));
}
} | Checks the salt position argument
@return void | https://github.com/Phauthentic/password-hashers/blob/c0679d51c941d8808ae143a20e63daab2d4388ec/src/AbstractPasswordHasher.php#L60-L70 |
akumar2-velsof/guzzlehttp | src/Event/AbstractTransferEvent.php | AbstractTransferEvent.intercept | public function intercept(ResponseInterface $response)
{
$this->transaction->response = $response;
$this->transaction->exception = null;
$this->stopPropagation();
} | php | public function intercept(ResponseInterface $response)
{
$this->transaction->response = $response;
$this->transaction->exception = null;
$this->stopPropagation();
} | Intercept the request and associate a response
@param ResponseInterface $response Response to set | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Event/AbstractTransferEvent.php#L57-L62 |
eloquent/endec | src/Base16/Base16EncodeTransform.php | Base16EncodeTransform.transform | public function transform($data, &$context, $isEnd = false)
{
return array(strtoupper(bin2hex($data)), strlen($data), null);
} | php | public function transform($data, &$context, $isEnd = false)
{
return array(strtoupper(bin2hex($data)), strlen($data), null);
} | Transform the supplied data.
This method may transform only part of the supplied data. The return
value includes information about how much data was actually consumed. The
transform can be forced to consume all data by passing a boolean true as
the $isEnd argument.
The $context argument will initially be null, but any value assigned to
this variable will persist until the stream transformation is complete.
It can be used as a place to store state, such as a buffer.
It is guaranteed that this method will be called with $isEnd = true once,
and only once, at the end of the stream transformation.
@param string $data The data to transform.
@param mixed &$context An arbitrary context value.
@param boolean $isEnd True if all supplied data must be transformed.
@return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base16/Base16EncodeTransform.php#L58-L61 |
PhoxPHP/Glider | src/Platform/Pdo/PdoProvider.php | PdoProvider.queryBuilder | public function queryBuilder(ConnectionInterface $connection, String $connectionId=null) : QueryBuilderProvider
{
return new PdoQueryBuilder($connection, $connectionId);
} | php | public function queryBuilder(ConnectionInterface $connection, String $connectionId=null) : QueryBuilderProvider
{
return new PdoQueryBuilder($connection, $connectionId);
} | We're using pdo query builder.
{@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Platform/Pdo/PdoProvider.php#L99-L102 |
PhoxPHP/Glider | src/Platform/Pdo/PdoProvider.php | PdoProvider.schemaManager | public function schemaManager(String $connectionId=null, QueryBuilderProvider $queryBuilder) : SchemaManagerContract
{
return new PdoSchemaManager($connectionId, $queryBuilder);
} | php | public function schemaManager(String $connectionId=null, QueryBuilderProvider $queryBuilder) : SchemaManagerContract
{
return new PdoSchemaManager($connectionId, $queryBuilder);
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Platform/Pdo/PdoProvider.php#L107-L110 |
gplcart/file_manager | handlers/validators/Copy.php | Copy.validateCopy | public function validateCopy(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateDestinationNameCopy();
$this->validateDestinationDirectoryCopy();
$this->validateDestinationExistanceCopy();
return $this->getResult();
} | php | public function validateCopy(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validateDestinationNameCopy();
$this->validateDestinationDirectoryCopy();
$this->validateDestinationExistanceCopy();
return $this->getResult();
} | Validates an array of submitted command data
@param array $submitted
@param array $options
@return boolean|array | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/validators/Copy.php#L44-L54 |
gplcart/file_manager | handlers/validators/Copy.php | Copy.validateDestinationNameCopy | protected function validateDestinationNameCopy()
{
$destination = $this->getSubmitted('destination');
if ($destination !== '' && preg_match('/^[\w-]+[\w-\/]*[\w-]+$|^[\w-]$/', $destination) !== 1) {
$this->setErrorInvalid('destination', $this->translation->text('Destination'));
}
} | php | protected function validateDestinationNameCopy()
{
$destination = $this->getSubmitted('destination');
if ($destination !== '' && preg_match('/^[\w-]+[\w-\/]*[\w-]+$|^[\w-]$/', $destination) !== 1) {
$this->setErrorInvalid('destination', $this->translation->text('Destination'));
}
} | Validates a directory name | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/validators/Copy.php#L59-L66 |
gplcart/file_manager | handlers/validators/Copy.php | Copy.validateDestinationDirectoryCopy | protected function validateDestinationDirectoryCopy()
{
if ($this->isError()) {
return null;
}
$initial_path = $this->scanner->getInitialPath(true);
$directory = gplcart_path_normalize("$initial_path/" . $this->getSubmitted('destination'));
if (!file_exists($directory) && !mkdir($directory, 0777, true)) {
$this->setError('destination', $this->translation->text('Destination does not exist'));
return false;
}
if (!is_dir($directory)) {
$this->setError('destination', $this->translation->text('Destination is not a directory'));
return false;
}
if (!is_writable($directory)) {
$this->setError('destination', $this->translation->text('Directory is not writable'));
return false;
}
$this->setSubmitted('directory', $directory);
return true;
} | php | protected function validateDestinationDirectoryCopy()
{
if ($this->isError()) {
return null;
}
$initial_path = $this->scanner->getInitialPath(true);
$directory = gplcart_path_normalize("$initial_path/" . $this->getSubmitted('destination'));
if (!file_exists($directory) && !mkdir($directory, 0777, true)) {
$this->setError('destination', $this->translation->text('Destination does not exist'));
return false;
}
if (!is_dir($directory)) {
$this->setError('destination', $this->translation->text('Destination is not a directory'));
return false;
}
if (!is_writable($directory)) {
$this->setError('destination', $this->translation->text('Directory is not writable'));
return false;
}
$this->setSubmitted('directory', $directory);
return true;
} | Validates a destination directory
@return bool | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/validators/Copy.php#L72-L98 |
gplcart/file_manager | handlers/validators/Copy.php | Copy.validateDestinationExistanceCopy | protected function validateDestinationExistanceCopy()
{
if ($this->isError()) {
return null;
}
$destinations = array();
$directory = $this->getSubmitted('directory');
$error = null;
foreach ((array) $this->getSubmitted('files') as $index => $file) {
/* @var $file \SplFileInfo */
if ($file->isDir() && gplcart_path_normalize($file->getRealPath()) === $directory) {
$error = $this->translation->text('Destination already exists');
continue;
}
$destination = "$directory/" . $file->getBasename();
if (file_exists($destination)) {
$error = $this->translation->text('Destination already exists');
continue;
}
$destinations[$index] = $destination;
}
if (isset($error)) {
$this->setError('destination', $error);
} else {
$this->setSubmitted('destinations', $destinations);
}
return true;
} | php | protected function validateDestinationExistanceCopy()
{
if ($this->isError()) {
return null;
}
$destinations = array();
$directory = $this->getSubmitted('directory');
$error = null;
foreach ((array) $this->getSubmitted('files') as $index => $file) {
/* @var $file \SplFileInfo */
if ($file->isDir() && gplcart_path_normalize($file->getRealPath()) === $directory) {
$error = $this->translation->text('Destination already exists');
continue;
}
$destination = "$directory/" . $file->getBasename();
if (file_exists($destination)) {
$error = $this->translation->text('Destination already exists');
continue;
}
$destinations[$index] = $destination;
}
if (isset($error)) {
$this->setError('destination', $error);
} else {
$this->setSubmitted('destinations', $destinations);
}
return true;
} | Validates file destinations
@return boolean | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/validators/Copy.php#L104-L139 |
fxpio/fxp-gluon | Block/Extension/NavbarExtension.php | NavbarExtension.buildView | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if ($options['hidden']) {
BlockUtil::addAttributeClass($view, 'hidden');
}
if (null !== $options['sidebar_locked']) {
BlockUtil::addAttribute($view, 'data-navbar-sidebar', 'true');
}
if (\in_array($options['sidebar_locked'], ['left', 'right'])) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-locked-'.$options['sidebar_locked']);
} elseif ('full_left' === $options['sidebar_locked']) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-full-locked-left');
} elseif ('full_right' === $options['sidebar_locked']) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-full-locked-right');
}
} | php | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if ($options['hidden']) {
BlockUtil::addAttributeClass($view, 'hidden');
}
if (null !== $options['sidebar_locked']) {
BlockUtil::addAttribute($view, 'data-navbar-sidebar', 'true');
}
if (\in_array($options['sidebar_locked'], ['left', 'right'])) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-locked-'.$options['sidebar_locked']);
} elseif ('full_left' === $options['sidebar_locked']) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-full-locked-left');
} elseif ('full_right' === $options['sidebar_locked']) {
BlockUtil::addAttributeClass($view, 'navbar-sidebar-full-locked-right');
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/NavbarExtension.php#L31-L48 |
fxpio/fxp-gluon | Block/Extension/NavbarExtension.php | NavbarExtension.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'hidden' => false,
'sidebar_locked' => null,
]);
$resolver->addAllowedTypes('hidden', 'bool');
$resolver->addAllowedTypes('sidebar_locked', ['null', 'string']);
$resolver->setAllowedValues('sidebar_locked', [null, 'left', 'right', 'full_left', 'full_right']);
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'hidden' => false,
'sidebar_locked' => null,
]);
$resolver->addAllowedTypes('hidden', 'bool');
$resolver->addAllowedTypes('sidebar_locked', ['null', 'string']);
$resolver->setAllowedValues('sidebar_locked', [null, 'left', 'right', 'full_left', 'full_right']);
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/NavbarExtension.php#L53-L64 |
hal-platform/hal-core | src/Repository/ApplicationRepository.php | ApplicationRepository.getGroupedApplications | public function getGroupedApplications()
{
$organizations = $this->getEntityManager()
->getRepository(Organization::class)
->findAll();
$applications = $this->findAll();
usort($applications, $this->applicationSorter());
usort($organizations, $this->organizationSorter());
$grouped = [];
foreach ($organizations as $org) {
$grouped[$org->id()] = [];
}
foreach ($applications as $app) {
$orgID = $app->organization() ? $app->organization()->id() : 'none';
$grouped[$orgID][] = $app;
}
return $grouped;
} | php | public function getGroupedApplications()
{
$organizations = $this->getEntityManager()
->getRepository(Organization::class)
->findAll();
$applications = $this->findAll();
usort($applications, $this->applicationSorter());
usort($organizations, $this->organizationSorter());
$grouped = [];
foreach ($organizations as $org) {
$grouped[$org->id()] = [];
}
foreach ($applications as $app) {
$orgID = $app->organization() ? $app->organization()->id() : 'none';
$grouped[$orgID][] = $app;
}
return $grouped;
} | Get all applications sorted into organizations.
@return array | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/ApplicationRepository.php#L33-L55 |
hal-platform/hal-core | src/Repository/ApplicationRepository.php | ApplicationRepository.getPagedResults | public function getPagedResults($limit = 25, $page = 0)
{
$template = self::DQL_ALL;
$dql = sprintf($template, Application::class);
return $this->getPaginator($dql, $limit, $page, []);
} | php | public function getPagedResults($limit = 25, $page = 0)
{
$template = self::DQL_ALL;
$dql = sprintf($template, Application::class);
return $this->getPaginator($dql, $limit, $page, []);
} | @param int $limit
@param int $page
@return Paginator | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/ApplicationRepository.php#L63-L69 |
rujiali/acquia-site-factory-cli | src/AppBundle/Connector/ConnectorThemes.php | ConnectorThemes.sendNotification | public function sendNotification($scope, $event, $nid = null, $theme = null, $timestamp = null, $uid = null)
{
if ($this->connector->getURL() === null) {
return 'Cannot find site URL from configuration.';
}
$url = $this->connector->getURL().self::VERSION.'/notification';
$params = [
'scope' => $scope,
'event' => $event,
'nid' => $nid,
'theme' => $theme,
'timestamp' => $timestamp,
'uid' => $uid,
];
$response = $this->connector->connecting($url, $params, 'POST');
if (isset($response->notification)) {
return $response->message;
}
return $response;
} | php | public function sendNotification($scope, $event, $nid = null, $theme = null, $timestamp = null, $uid = null)
{
if ($this->connector->getURL() === null) {
return 'Cannot find site URL from configuration.';
}
$url = $this->connector->getURL().self::VERSION.'/notification';
$params = [
'scope' => $scope,
'event' => $event,
'nid' => $nid,
'theme' => $theme,
'timestamp' => $timestamp,
'uid' => $uid,
];
$response = $this->connector->connecting($url, $params, 'POST');
if (isset($response->notification)) {
return $response->message;
}
return $response;
} | Send theme notification.
@param string $scope The scope.
@param string $event The event.
@param null $nid The node ID of the related entity (site or group).
@param null $theme The system name of the theme.
@param null $timestamp A Unix timestamp of when the event occurred.
@param null $uid The user id owning the notification and who should get notified if an error occurs during processing.
@return mixed|string | https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Connector/ConnectorThemes.php#L40-L60 |
rujiali/acquia-site-factory-cli | src/AppBundle/Connector/ConnectorThemes.php | ConnectorThemes.processModification | public function processModification($siteGroupId = null)
{
if ($this->connector->getURL() === null) {
return 'Cannot find site URL from configuration.';
}
$url = $this->connector->getURL().self::VERSION.'/process';
$params = [
'sitegroup_id' => $siteGroupId,
];
$response = $this->connector->connecting($url, $params, 'POST');
if (isset($response->sitegroups)) {
return $response->message;
}
return $response;
} | php | public function processModification($siteGroupId = null)
{
if ($this->connector->getURL() === null) {
return 'Cannot find site URL from configuration.';
}
$url = $this->connector->getURL().self::VERSION.'/process';
$params = [
'sitegroup_id' => $siteGroupId,
];
$response = $this->connector->connecting($url, $params, 'POST');
if (isset($response->sitegroups)) {
return $response->message;
}
return $response;
} | Process theme modification.
@param string $siteGroupId Site group ID.
@return mixed|string | https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Connector/ConnectorThemes.php#L69-L84 |
mlocati/concrete5-translation-library | src/Parser/DynamicItem/SelectAttributeValue.php | SelectAttributeValue.parseManual | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeKey', true) && class_exists('\AttributeType', true)) {
foreach (\AttributeKeyCategory::getList() as $akc) {
$akcHandle = $akc->getAttributeKeyCategoryHandle();
foreach (\AttributeKey::getList($akcHandle) as $ak) {
if ($ak->getAttributeType()->getAttributeTypeHandle() === 'select') {
foreach ($ak->getController()->getOptions() as $option) {
$this->addTranslation($translations, $option->getSelectAttributeOptionValue(false), 'SelectAttributeValue');
}
}
}
}
}
} | php | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\AttributeKeyCategory', true) && class_exists('\AttributeKey', true) && class_exists('\AttributeType', true)) {
foreach (\AttributeKeyCategory::getList() as $akc) {
$akcHandle = $akc->getAttributeKeyCategoryHandle();
foreach (\AttributeKey::getList($akcHandle) as $ak) {
if ($ak->getAttributeType()->getAttributeTypeHandle() === 'select') {
foreach ($ak->getController()->getOptions() as $option) {
$this->addTranslation($translations, $option->getSelectAttributeOptionValue(false), 'SelectAttributeValue');
}
}
}
}
}
} | {@inheritdoc}
@see \C5TL\Parser\DynamicItem\DynamicItem::parseManual() | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/SelectAttributeValue.php#L35-L49 |
apishka/easy-extend | source/Meta/Generator.php | Generator.generate | public function generate(string $filename): bool
{
$this->writeFile(
$filename,
$this->generateContents()
);
return true;
} | php | public function generate(string $filename): bool
{
$this->writeFile(
$filename,
$this->generateContents()
);
return true;
} | @param string $filename
@return bool | https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Meta/Generator.php#L43-L51 |
hal-platform/hal-core | src/VersionControl/GitHub/GitHubAdapter.php | GitHubAdapter.buildClient | public function buildClient(VersionControlProvider $vcs): ?VCSClientInterface
{
if ($vcs->type() !== VCSProviderEnum::TYPE_GITHUB) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$key = sprintf(self::CACHE_KEY_TEMPLATE, $vcs->type(), $vcs->id());
$client = $this->getFromCache($key);
if ($client instanceof VCSClientInterface) {
return $client;
}
$token = $vcs->parameter(Parameters::VCS_GH_TOKEN);
if (!$token) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$sdk = new Client($this->httpClientBuilder, null);
$sdk->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
$client = new GitHubClient($sdk, new ResultPager($sdk));
// Pass along the this cache. Ideally this is configurable.
$client->setCache($this->cache());
// Should only be in memory
$this->setToCache($key, $client, 60);
return $client;
} | php | public function buildClient(VersionControlProvider $vcs): ?VCSClientInterface
{
if ($vcs->type() !== VCSProviderEnum::TYPE_GITHUB) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$key = sprintf(self::CACHE_KEY_TEMPLATE, $vcs->type(), $vcs->id());
$client = $this->getFromCache($key);
if ($client instanceof VCSClientInterface) {
return $client;
}
$token = $vcs->parameter(Parameters::VCS_GH_TOKEN);
if (!$token) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$sdk = new Client($this->httpClientBuilder, null);
$sdk->authenticate($token, null, Client::AUTH_HTTP_TOKEN);
$client = new GitHubClient($sdk, new ResultPager($sdk));
// Pass along the this cache. Ideally this is configurable.
$client->setCache($this->cache());
// Should only be in memory
$this->setToCache($key, $client, 60);
return $client;
} | @param VersionControlProvider $vcs
@return VCSClientInterface|null | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/GitHub/GitHubAdapter.php#L71-L102 |
hal-platform/hal-core | src/VersionControl/GitHub/GitHubAdapter.php | GitHubAdapter.buildDownloader | public function buildDownloader(VersionControlProvider $vcs): ?VCSDownloaderInterface
{
if ($vcs->type() !== VCSProviderEnum::TYPE_GITHUB) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$baseURL = $this->baseURL;
$token = $vcs->parameter(Parameters::VCS_GH_TOKEN);
if (!$baseURL || !$token) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$options = $this->defaultGuzzleOptions + [
'base_uri' => $baseURL,
'headers' => [
'Authorization' => sprintf('token %s', $token),
],
'allow_redirects' => true,
'connect_timeout' => 5,
'timeout' => 300, # 5 minutes seems like a reasonable amount of time?
'http_errors' => false,
];
$guzzle = new GuzzleClient($options);
return new GitHubDownloader($guzzle);
} | php | public function buildDownloader(VersionControlProvider $vcs): ?VCSDownloaderInterface
{
if ($vcs->type() !== VCSProviderEnum::TYPE_GITHUB) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$baseURL = $this->baseURL;
$token = $vcs->parameter(Parameters::VCS_GH_TOKEN);
if (!$baseURL || !$token) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$options = $this->defaultGuzzleOptions + [
'base_uri' => $baseURL,
'headers' => [
'Authorization' => sprintf('token %s', $token),
],
'allow_redirects' => true,
'connect_timeout' => 5,
'timeout' => 300, # 5 minutes seems like a reasonable amount of time?
'http_errors' => false,
];
$guzzle = new GuzzleClient($options);
return new GitHubDownloader($guzzle);
} | @param VersionControlProvider $vcs
@return VCSDownloaderInterface|null | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/GitHub/GitHubAdapter.php#L109-L138 |
luoxiaojun1992/lb_framework | components/helpers/HashHelper.php | HashHelper.hash | public static function hash($str, $algo = self::MD5_HASH, $hmacKey = '', $rawOuput = false, $salt = null, $passwordAlgo = PASSWORD_DEFAULT, $passwordOptions = [])
{
if ($hmacKey && in_array($algo, [self::MD5_HASH, self::SHA1_HASH])) {
return hash_hmac($algo, $str, $hmacKey, $rawOuput);
}
switch ($algo) {
case self::MD5_HASH:
$hashCode = md5($str, $rawOuput);
break;
case self::SHA1_HASH:
$hashCode = sha1($str, $rawOuput);
break;
case self::CRYPT_HASH:
$hashCode = crypt($str, $salt);
break;
case self::PASSWORD_HASH:
$hashCode = password_hash($str, $passwordAlgo, $passwordOptions);
break;
default:
$hashCode = md5($str, $rawOuput);
}
return $hashCode;
} | php | public static function hash($str, $algo = self::MD5_HASH, $hmacKey = '', $rawOuput = false, $salt = null, $passwordAlgo = PASSWORD_DEFAULT, $passwordOptions = [])
{
if ($hmacKey && in_array($algo, [self::MD5_HASH, self::SHA1_HASH])) {
return hash_hmac($algo, $str, $hmacKey, $rawOuput);
}
switch ($algo) {
case self::MD5_HASH:
$hashCode = md5($str, $rawOuput);
break;
case self::SHA1_HASH:
$hashCode = sha1($str, $rawOuput);
break;
case self::CRYPT_HASH:
$hashCode = crypt($str, $salt);
break;
case self::PASSWORD_HASH:
$hashCode = password_hash($str, $passwordAlgo, $passwordOptions);
break;
default:
$hashCode = md5($str, $rawOuput);
}
return $hashCode;
} | Hashing
@param $str
@param string $algo
@param string $hmacKey
@param bool $rawOuput
@param null $salt
@param int $passwordAlgo
@param array $passwordOptions
@return bool|string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HashHelper.php#L29-L53 |
luoxiaojun1992/lb_framework | components/helpers/HashHelper.php | HashHelper.flexiHash | public static function flexiHash($str)
{
$md5 = substr(self::hash($str), 0, 8);
$seed = 31;
$hash = 0;
for ($i = 0; $i < 8; $i++) {
$hash = $hash * $seed + ord($md5{$i});
$i++;
}
return $hash & 0x7FFFFFFF;
} | php | public static function flexiHash($str)
{
$md5 = substr(self::hash($str), 0, 8);
$seed = 31;
$hash = 0;
for ($i = 0; $i < 8; $i++) {
$hash = $hash * $seed + ord($md5{$i});
$i++;
}
return $hash & 0x7FFFFFFF;
} | Flexi hashing
@param $str
@return int | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HashHelper.php#L61-L71 |
luoxiaojun1992/lb_framework | components/helpers/HashHelper.php | HashHelper.murmurhash | public static function murmurhash($str, int $seed = 0, $isInt = false, $version = 3)
{
if ($version != 3) {
throw new ParamException('Murmurhash' . $version . ' not supported');
}
return $isInt ? Murmur::hash3_int($str, $seed) : Murmur::hash3($str, $seed);
} | php | public static function murmurhash($str, int $seed = 0, $isInt = false, $version = 3)
{
if ($version != 3) {
throw new ParamException('Murmurhash' . $version . ' not supported');
}
return $isInt ? Murmur::hash3_int($str, $seed) : Murmur::hash3($str, $seed);
} | Murmurhash 3
@param $str
@param int $seed
@param bool $isInt
@param int $version
@return mixed
@throws ParamException | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/HashHelper.php#L83-L90 |
yupmin-ct/kollus-sdk-php | src/KollusServiceProvider.php | KollusServiceProvider.register | public function register()
{
$this->app->singleton(Client\ApiClient::class, function () {
$kollusApiClient = new Client\ApiClient(
config('kollus.domain'),
config('kollus.api_version'),
config('kollus.language')
);
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'api_access_token' => config('kollus.service_account.api_access_token')
]);
$kollusApiClient->setServiceAccount($serviceAccount);
$kollusApiClient->connect();
if (config('kollus.use_https')) {
$kollusApiClient->setSchema('https');
}
return $kollusApiClient;
});
$this->app->singleton(Client\VideoGatewayClient::class, function () {
$kollusVideoGatewayClient = new Client\VideoGatewayClient(
config('kollus.domain'),
config('kollus.api_version'),
config('kollus.language')
);
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'custom_key' => config('kollus.service_account.custom_key'),
'security_key' => config('kollus.service_account.security_key', null),
]);
if (config('kollus.use_https')) {
$kollusVideoGatewayClient->setSchema('https');
}
$kollusVideoGatewayClient->setServiceAccount($serviceAccount);
$kollusVideoGatewayClient->connect();
return $kollusVideoGatewayClient;
});
$this->app->singleton(Callback::class, function () {
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'custom_key' => config('kollus.service_account.custom_key'),
'security_key' => config('kollus.service_account.security_key'),
]);
$kollusCallback = new Callback($serviceAccount);
return $kollusCallback;
});
} | php | public function register()
{
$this->app->singleton(Client\ApiClient::class, function () {
$kollusApiClient = new Client\ApiClient(
config('kollus.domain'),
config('kollus.api_version'),
config('kollus.language')
);
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'api_access_token' => config('kollus.service_account.api_access_token')
]);
$kollusApiClient->setServiceAccount($serviceAccount);
$kollusApiClient->connect();
if (config('kollus.use_https')) {
$kollusApiClient->setSchema('https');
}
return $kollusApiClient;
});
$this->app->singleton(Client\VideoGatewayClient::class, function () {
$kollusVideoGatewayClient = new Client\VideoGatewayClient(
config('kollus.domain'),
config('kollus.api_version'),
config('kollus.language')
);
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'custom_key' => config('kollus.service_account.custom_key'),
'security_key' => config('kollus.service_account.security_key', null),
]);
if (config('kollus.use_https')) {
$kollusVideoGatewayClient->setSchema('https');
}
$kollusVideoGatewayClient->setServiceAccount($serviceAccount);
$kollusVideoGatewayClient->connect();
return $kollusVideoGatewayClient;
});
$this->app->singleton(Callback::class, function () {
$serviceAccount = new Container\ServiceAccount([
'key' => config('kollus.service_account.key'),
'custom_key' => config('kollus.service_account.custom_key'),
'security_key' => config('kollus.service_account.security_key'),
]);
$kollusCallback = new Callback($serviceAccount);
return $kollusCallback;
});
} | Register the application services.
@return void | https://github.com/yupmin-ct/kollus-sdk-php/blob/b380a01cdd73444456c633cf8e0fe2288dd2fa0b/src/KollusServiceProvider.php#L26-L85 |
matryoshka-model/matryoshka | library/ResultSet/ArrayObjectResultSet.php | ArrayObjectResultSet.setObjectPrototype | public function setObjectPrototype($objectPrototype)
{
if (!is_object($objectPrototype)
|| (!$objectPrototype instanceof ArrayObject && !method_exists($objectPrototype, 'exchangeArray'))
) {
throw new Exception\InvalidArgumentException(sprintf(
'Object must be of type %s, or at least implement %s',
'ArrayObject',
'exchangeArray'
));
}
$this->arrayObjectPrototype = $objectPrototype;
return $this;
} | php | public function setObjectPrototype($objectPrototype)
{
if (!is_object($objectPrototype)
|| (!$objectPrototype instanceof ArrayObject && !method_exists($objectPrototype, 'exchangeArray'))
) {
throw new Exception\InvalidArgumentException(sprintf(
'Object must be of type %s, or at least implement %s',
'ArrayObject',
'exchangeArray'
));
}
$this->arrayObjectPrototype = $objectPrototype;
return $this;
} | Set the item object prototype
@param object $objectPrototype
@throws Exception\InvalidArgumentException
@return ResultSetInterface | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/ResultSet/ArrayObjectResultSet.php#L41-L55 |
atelierspierrot/patterns | src/Patterns/Traits/AccessibleTrait.php | AccessibleTrait.__isset | public function __isset($var)
{
try {
$var = $this->validateAccessibleProperty($var);
$accessor = $this->getAccessorName($var, 'isset');
if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) {
return call_user_func(array($this, $accessor));
} else {
return isset($this->{$var});
}
} catch (RuntimeException $e) {
throw $e;
}
} | php | public function __isset($var)
{
try {
$var = $this->validateAccessibleProperty($var);
$accessor = $this->getAccessorName($var, 'isset');
if (method_exists($this, $accessor) && is_callable(array($this, $accessor))) {
return call_user_func(array($this, $accessor));
} else {
return isset($this->{$var});
}
} catch (RuntimeException $e) {
throw $e;
}
} | Test if an object property has been set, using the "issetVariable" method if defined
Called when you write `isset($obj->property)` or `empty($obj->property)`
@param string $var The property object to test
@return bool True if the property is already set
@throws \RuntimeException if the property doesn't exist in the object | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Traits/AccessibleTrait.php#L148-L161 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/Manager/TreeManager.php | TreeManager.generateTree | public function generateTree($nodes)
{
$superRoot = count(array_filter($nodes, function (ReadNodeInterface $node) {
return '-' == $node->getParentId();
}))? '-': 'root';
$list = array();
$list[$superRoot] = array();
foreach ($nodes as $node) {
if ($superRoot !== $node->getParentId() && $this->parentInList($node->getParentId(), $nodes)) {
$list[$node->getParentId()][] = $node;
continue;
}
$list[$superRoot][] = $node;
}
$tree = $this->createTree($list[$superRoot], $list);
return $tree;
} | php | public function generateTree($nodes)
{
$superRoot = count(array_filter($nodes, function (ReadNodeInterface $node) {
return '-' == $node->getParentId();
}))? '-': 'root';
$list = array();
$list[$superRoot] = array();
foreach ($nodes as $node) {
if ($superRoot !== $node->getParentId() && $this->parentInList($node->getParentId(), $nodes)) {
$list[$node->getParentId()][] = $node;
continue;
}
$list[$superRoot][] = $node;
}
$tree = $this->createTree($list[$superRoot], $list);
return $tree;
} | @param array $nodes
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/TreeManager.php#L17-L36 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/Manager/TreeManager.php | TreeManager.createTree | protected function createTree($nodes, $list)
{
$tree = array();
if (is_array($nodes)) {
foreach ($nodes as $node) {
$position = $this->getNodePosition($node, $tree);
$tree[$position] = array('node' => $node, 'child' => $this->getChildren($node, $list));
}
$tree = $this->sortArray($tree);
} elseif (!empty($nodes)) {
$tree = array('node' => $nodes, 'child' => $this->getChildren($nodes, $list));
}
return $tree;
} | php | protected function createTree($nodes, $list)
{
$tree = array();
if (is_array($nodes)) {
foreach ($nodes as $node) {
$position = $this->getNodePosition($node, $tree);
$tree[$position] = array('node' => $node, 'child' => $this->getChildren($node, $list));
}
$tree = $this->sortArray($tree);
} elseif (!empty($nodes)) {
$tree = array('node' => $nodes, 'child' => $this->getChildren($nodes, $list));
}
return $tree;
} | @param array|ReadNodeInterface $nodes
@param array $list
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/TreeManager.php#L44-L59 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/Manager/TreeManager.php | TreeManager.getChildren | protected function getChildren(ReadNodeInterface $node, $list)
{
$children = array();
if (!empty($list[$node->getNodeId()]) && is_array($list[$node->getNodeId()])) {
foreach ($list[$node->getNodeId()] as $child) {
$position = $this->getNodePosition($child, $children);
$children[$position] = $this->createTree($child, $list);
}
}
$children = $this->sortArray($children);
return $children;
} | php | protected function getChildren(ReadNodeInterface $node, $list)
{
$children = array();
if (!empty($list[$node->getNodeId()]) && is_array($list[$node->getNodeId()])) {
foreach ($list[$node->getNodeId()] as $child) {
$position = $this->getNodePosition($child, $children);
$children[$position] = $this->createTree($child, $list);
}
}
$children = $this->sortArray($children);
return $children;
} | @param ReadNodeInterface $node
@param array $list
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/TreeManager.php#L67-L81 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/Manager/TreeManager.php | TreeManager.parentInList | protected function parentInList($parentId, $list)
{
foreach ($list as $node) {
if ($parentId === $node->getNodeId()) {
return true;
}
}
return false;
} | php | protected function parentInList($parentId, $list)
{
foreach ($list as $node) {
if ($parentId === $node->getNodeId()) {
return true;
}
}
return false;
} | @param string $parentId
@param array $list
@return bool | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/TreeManager.php#L89-L98 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/Manager/TreeManager.php | TreeManager.getNodePosition | protected function getNodePosition(ReadNodeInterface $node, $tree)
{
$position = $node->getOrder();
while (array_key_exists($position, $tree)) {
$position++;
}
return $position;
} | php | protected function getNodePosition(ReadNodeInterface $node, $tree)
{
$position = $node->getOrder();
while (array_key_exists($position, $tree)) {
$position++;
}
return $position;
} | @param ReadNodeInterface $node
@param array $tree
@return mixed | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/TreeManager.php#L106-L114 |
borobudur-php/borobudur | src/Borobudur/Component/Messaging/Message/Factory.php | Factory.createFromMetadata | public function createFromMetadata(MetadataInterface $metadata, array $data): MessageInterface
{
if ($ids = $metadata->getParameter()->get('generate_ids')) {
foreach ((array) $ids as $id) {
$data[$id] = (string) Uuid::uuid4();
}
}
$class = $metadata->getMessageClass();
return new $class($data);
} | php | public function createFromMetadata(MetadataInterface $metadata, array $data): MessageInterface
{
if ($ids = $metadata->getParameter()->get('generate_ids')) {
foreach ((array) $ids as $id) {
$data[$id] = (string) Uuid::uuid4();
}
}
$class = $metadata->getMessageClass();
return new $class($data);
} | {@inheritdoc} | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Messaging/Message/Factory.php#L26-L37 |
martinvium/seine | src/Seine/Parser/DOM/DOMFactory.php | DOMFactory.getConfiguredBook | public function getConfiguredBook($fp, Configuration $config = null)
{
$book = $this->getBook();
$book->setWriter($this->getConfiguredWriter($fp, $config));
return $book;
} | php | public function getConfiguredBook($fp, Configuration $config = null)
{
$book = $this->getBook();
$book->setWriter($this->getConfiguredWriter($fp, $config));
return $book;
} | Get a Book already configured with a writer and options from the default configuration
or the $config param if passed in.
@param stream $fp
@param Configuration $config
@return Book | https://github.com/martinvium/seine/blob/b361241c88bb73e81c66259f59193b175223c2eb/src/Seine/Parser/DOM/DOMFactory.php#L128-L133 |
martinvium/seine | src/Seine/Parser/DOM/DOMFactory.php | DOMFactory.getConfiguredWriter | public function getConfiguredWriter($fp, Configuration $config = null)
{
if(! $config) {
$config = $this->config;
}
$writerName = $config->getOption(Configuration::OPT_WRITER);
if(! $writerName) {
throw new \Exception('Writer must be defined in config for getConfiguredWriter()');
}
$writer = $this->getWriterByName($fp, $writerName);
$writer->setAutoCloseStream($config->getOption(Configuration::OPT_AUTO_CLOSE_STREAM, false));
$writer->setConfig($config);
return $writer;
} | php | public function getConfiguredWriter($fp, Configuration $config = null)
{
if(! $config) {
$config = $this->config;
}
$writerName = $config->getOption(Configuration::OPT_WRITER);
if(! $writerName) {
throw new \Exception('Writer must be defined in config for getConfiguredWriter()');
}
$writer = $this->getWriterByName($fp, $writerName);
$writer->setAutoCloseStream($config->getOption(Configuration::OPT_AUTO_CLOSE_STREAM, false));
$writer->setConfig($config);
return $writer;
} | Get a writer configured using the default configuration or the one passed in.
@param stream $fp
@param Configuration $config
@return Writer | https://github.com/martinvium/seine/blob/b361241c88bb73e81c66259f59193b175223c2eb/src/Seine/Parser/DOM/DOMFactory.php#L142-L157 |
martinvium/seine | src/Seine/Parser/DOM/DOMFactory.php | DOMFactory.getWriterByName | public function getWriterByName($fp, $writerName)
{
$method = 'get' . $writerName;
if(method_exists($this->getWriterFactory(), $method)) {
return $this->getWriterFactory()->$method($fp);
} else {
throw new \InvalidArgumentException('writer not found: ' . $writerName);
}
} | php | public function getWriterByName($fp, $writerName)
{
$method = 'get' . $writerName;
if(method_exists($this->getWriterFactory(), $method)) {
return $this->getWriterFactory()->$method($fp);
} else {
throw new \InvalidArgumentException('writer not found: ' . $writerName);
}
} | Get a writer by it's name. The name is looked up in the writer factory prefixed with "get".
@example $writer = $factory->getWriterByName($fp, 'OfficeOpenXML2003StreamWriter');
@param stream $fp
@param string $writerName
@return Writer | https://github.com/martinvium/seine/blob/b361241c88bb73e81c66259f59193b175223c2eb/src/Seine/Parser/DOM/DOMFactory.php#L167-L175 |
WellCommerce/CatalogBundle | Helper/VariantHelper.php | VariantHelper.getVariants | public function getVariants(Product $product): array
{
$variants = [];
$product->getVariants()->map(function (Variant $variant) use (&$variants) {
if ($variant->isEnabled()) {
$this->extractVariantData($variant, $variants);
}
});
return $variants;
} | php | public function getVariants(Product $product): array
{
$variants = [];
$product->getVariants()->map(function (Variant $variant) use (&$variants) {
if ($variant->isEnabled()) {
$this->extractVariantData($variant, $variants);
}
});
return $variants;
} | {@inheritdoc} | https://github.com/WellCommerce/CatalogBundle/blob/b1809190298f6c6c04c472dbfd763c1ad0b68630/Helper/VariantHelper.php#L46-L57 |
WellCommerce/CatalogBundle | Helper/VariantHelper.php | VariantHelper.getAttributes | public function getAttributes(Product $product): array
{
$attributes = [];
$product->getVariants()->map(function (Variant $variant) use (&$attributes) {
if ($variant->isEnabled()) {
$this->extractAttributesData($variant, $attributes);
}
});
return $attributes;
} | php | public function getAttributes(Product $product): array
{
$attributes = [];
$product->getVariants()->map(function (Variant $variant) use (&$attributes) {
if ($variant->isEnabled()) {
$this->extractAttributesData($variant, $attributes);
}
});
return $attributes;
} | {@inheritdoc} | https://github.com/WellCommerce/CatalogBundle/blob/b1809190298f6c6c04c472dbfd763c1ad0b68630/Helper/VariantHelper.php#L62-L73 |
Synapse-Cmf/synapse-cmf | src/Synapse/Admin/Bundle/Controller/ImageAdminController.php | ImageAdminController.editAction | public function editAction(Image $image, Request $request)
{
$form = $this->container->get('form.factory')->createNamed(
'image',
ImageType::class,
$image,
array(
'action' => $this->container->get('router')->generate(
'synapse_admin_image_edition',
array('id' => $image->getId())
),
'method' => 'POST',
'csrf_protection' => false,
)
);
if ($request->request->has('image')) {
$form->handleRequest($request);
if ($form->isValid()) {
return $this->redirect(
$this->container->get('router')->generate(
'synapse_admin_image_edition',
array('id' => $image->getId())
)
);
}
}
return $this->render('SynapseAdminBundle:Image:edit.html.twig', array(
'image' => $image,
'theme' => $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
),
'form' => $form->createView(),
));
} | php | public function editAction(Image $image, Request $request)
{
$form = $this->container->get('form.factory')->createNamed(
'image',
ImageType::class,
$image,
array(
'action' => $this->container->get('router')->generate(
'synapse_admin_image_edition',
array('id' => $image->getId())
),
'method' => 'POST',
'csrf_protection' => false,
)
);
if ($request->request->has('image')) {
$form->handleRequest($request);
if ($form->isValid()) {
return $this->redirect(
$this->container->get('router')->generate(
'synapse_admin_image_edition',
array('id' => $image->getId())
)
);
}
}
return $this->render('SynapseAdminBundle:Image:edit.html.twig', array(
'image' => $image,
'theme' => $request->attributes->get(
'synapse_theme',
$this->container->get('synapse')
->enableDefaultTheme()
->getCurrentTheme()
),
'form' => $form->createView(),
));
} | Image edition action.
@param Request $request
@return Response | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/ImageAdminController.php#L55-L92 |
Synapse-Cmf/synapse-cmf | src/Synapse/Admin/Bundle/Controller/ImageAdminController.php | ImageAdminController.xhrFormatAction | public function xhrFormatAction(Image $image, $formatName, Request $request)
{
// retrieve format value object
if (!$format = $this->container->get('synapse.image_format.loader')
->retrieveOne(array('name' => $formatName))
) {
return new JsonResponse(
array(
'error' => 400,
'error_message' => sprintf('No format found with name "%s".', $formatName),
),
400
);
}
// form handle
$form = $this->container->get('form.factory')->createNamed(
'',
FormatType::class,
$image,
array(
'format' => $format,
'method' => 'POST',
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if (!$form->isValid()) {
return new JsonResponse(
array(
'error' => 400,
'error_message' => 'Invalid format data.',
),
400
);
}
// formatted image data
return new JsonResponse(
$form->getData()
->getFormattedImage($formatName)
->normalize(),
201
);
} | php | public function xhrFormatAction(Image $image, $formatName, Request $request)
{
// retrieve format value object
if (!$format = $this->container->get('synapse.image_format.loader')
->retrieveOne(array('name' => $formatName))
) {
return new JsonResponse(
array(
'error' => 400,
'error_message' => sprintf('No format found with name "%s".', $formatName),
),
400
);
}
// form handle
$form = $this->container->get('form.factory')->createNamed(
'',
FormatType::class,
$image,
array(
'format' => $format,
'method' => 'POST',
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if (!$form->isValid()) {
return new JsonResponse(
array(
'error' => 400,
'error_message' => 'Invalid format data.',
),
400
);
}
// formatted image data
return new JsonResponse(
$form->getData()
->getFormattedImage($formatName)
->normalize(),
201
);
} | Image formating action through XmlHttpRequest.
@param Image $image
@param string $formatName
@param Request $request
@return JsonResponse | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Admin/Bundle/Controller/ImageAdminController.php#L103-L147 |
symfony2admingenerator/FormBundle | Twig/Extension/FormExtension.php | FormExtension.renderJavascript | public function renderJavascript(FormView $view, $prototype = false)
{
$block = $prototype ? 'js_prototype' : 'js';
return $this->renderer->searchAndRenderBlock($view, $block);
} | php | public function renderJavascript(FormView $view, $prototype = false)
{
$block = $prototype ? 'js_prototype' : 'js';
return $this->renderer->searchAndRenderBlock($view, $block);
} | Render Function Form Javascript
@param FormView $view
@param bool $prototype
@return string | https://github.com/symfony2admingenerator/FormBundle/blob/0f0dbf8f0aecc3332daa959771af611f00b35359/Twig/Extension/FormExtension.php#L57-L62 |
symfony2admingenerator/FormBundle | Twig/Extension/FormExtension.php | FormExtension.escape_for_js | public function escape_for_js($var)
{
$functionPattern = "%^\\s*function\\s*\\(%is";
$callPattern = "%^\w+\((['\w\d]+(,\\s['\w\d]+)*)?\)(\.\w+\((['\w\d]+(,\\s['\w\d]+)*)?\))?$%is";
$jsonPattern = "%^\\s*\\{.*\\}\\s*$%is";
$arrayPattern = "%^\\s*\\[.*\\]\\s*$%is";
if (is_bool($var)) {
return $var ? 'true' : 'false';
}
if (is_null($var)) {
return 'null';
}
if ('undefined' === $var) {
return 'undefined';
}
if (is_string($var)
&& !preg_match($functionPattern, $var)
&& !preg_match($callPattern, $var)
&& !preg_match($jsonPattern, $var)
&& !preg_match($arrayPattern, $var)
) {
$var = preg_replace('(\r\n|\r|\n)', '', $var);
return '"'.str_replace('"', '"', $var).'"';
}
if (is_array($var)) {
$is_assoc = function ($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
};
if ($is_assoc($var)) {
$items = array();
foreach($var as $key => $val) {
$items[] = '"'.$key.'": '.$this->escape_for_js($val);
}
return '{'.implode(',', $items).'}';
} else {
$items = array();
foreach($var as $val) {
$items[] = $this->escape_for_js($val);
}
return '['.implode(',', $items).']';
}
}
return $var;
} | php | public function escape_for_js($var)
{
$functionPattern = "%^\\s*function\\s*\\(%is";
$callPattern = "%^\w+\((['\w\d]+(,\\s['\w\d]+)*)?\)(\.\w+\((['\w\d]+(,\\s['\w\d]+)*)?\))?$%is";
$jsonPattern = "%^\\s*\\{.*\\}\\s*$%is";
$arrayPattern = "%^\\s*\\[.*\\]\\s*$%is";
if (is_bool($var)) {
return $var ? 'true' : 'false';
}
if (is_null($var)) {
return 'null';
}
if ('undefined' === $var) {
return 'undefined';
}
if (is_string($var)
&& !preg_match($functionPattern, $var)
&& !preg_match($callPattern, $var)
&& !preg_match($jsonPattern, $var)
&& !preg_match($arrayPattern, $var)
) {
$var = preg_replace('(\r\n|\r|\n)', '', $var);
return '"'.str_replace('"', '"', $var).'"';
}
if (is_array($var)) {
$is_assoc = function ($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
};
if ($is_assoc($var)) {
$items = array();
foreach($var as $key => $val) {
$items[] = '"'.$key.'": '.$this->escape_for_js($val);
}
return '{'.implode(',', $items).'}';
} else {
$items = array();
foreach($var as $val) {
$items[] = $this->escape_for_js($val);
}
return '['.implode(',', $items).']';
}
}
return $var;
} | The default twig "escape('js')" filter does not recognize various
patterns in string and breaks the code (eg. anonymous functions).
This filter recognizes these patterns and treats them accordingly:
Value | behaviour
====================|======================================
Anonymous function > output raw
Function call > output raw
Json object > recursively iterate over properties,
| and escape each value individually
Json array > recursively iterate over values,
| and escape each individually
Boolean > output true or false
Null > output null
Undefined > output undefined
Other strings > replace quotes with " and output
| wrapped in quotes
@param string $var
@return string | https://github.com/symfony2admingenerator/FormBundle/blob/0f0dbf8f0aecc3332daa959771af611f00b35359/Twig/Extension/FormExtension.php#L97-L147 |
vetermanve/verse_statistic_client | src/Verse/StatisticClient/Stats.php | Stats.event | public function event($field, $userId, $scopeId = 0, array $context = [], float $count = 1, $eventTime = null)
{
$this->sendEventData($this->makeEventData($field, $userId, $scopeId, $context, $count, $eventTime));
return $this;
} | php | public function event($field, $userId, $scopeId = 0, array $context = [], float $count = 1, $eventTime = null)
{
$this->sendEventData($this->makeEventData($field, $userId, $scopeId, $context, $count, $eventTime));
return $this;
} | Отправить эвент с явной передачей userId и companyId
@param $field
@param $userId
@param int $scopeId
@param array $context
@param float|int $count
@param int|null $eventTime
@return $this|\Verse\StatisticClient\Stats | https://github.com/vetermanve/verse_statistic_client/blob/5d1f0f9fa5b1e874bc46c52d00b230a7fcf5acf4/src/Verse/StatisticClient/Stats.php#L39-L44 |
slickframework/form | src/Renderer/Div.php | Div.render | public function render($context = [])
{
parent::render($context);
$this->getEngine()->parse($this->template);
$data = [
'element' => $this->getElement(),
'context' => $context,
'renderer' => $this
];
return $this->getEngine()->process($data);
} | php | public function render($context = [])
{
parent::render($context);
$this->getEngine()->parse($this->template);
$data = [
'element' => $this->getElement(),
'context' => $context,
'renderer' => $this
];
return $this->getEngine()->process($data);
} | Render the HTML element in the provided context
@param array $context
@return string The HTML string output | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/Div.php#L27-L37 |
Laralum/Tickets | src/Controllers/MessageController.php | MessageController.confirmDestroy | public function confirmDestroy(Message $message)
{
$this->authorize('delete', $message);
return view('laralum::pages.confirmation', [
'method' => 'DELETE',
'message' => __('laralum_tickets::general.sure_del_message', ['id' => $message->id]),
'action' => route('laralum::tickets.messages.destroy', ['message' => $message->id]),
]);
} | php | public function confirmDestroy(Message $message)
{
$this->authorize('delete', $message);
return view('laralum::pages.confirmation', [
'method' => 'DELETE',
'message' => __('laralum_tickets::general.sure_del_message', ['id' => $message->id]),
'action' => route('laralum::tickets.messages.destroy', ['message' => $message->id]),
]);
} | View for cofirm delete message.
@param \Laralum\Tickets\Models\Message $message
@return \Illuminate\Http\Response | https://github.com/Laralum/Tickets/blob/834b04e28cc3be285fc0eac1a673f6370079e6d2/src/Controllers/MessageController.php#L98-L107 |
Laralum/Tickets | src/Controllers/MessageController.php | MessageController.destroy | public function destroy(Message $message)
{
$this->authorize('delete', $message);
$message->delete();
return redirect()->route('laralum::tickets.show', ['ticket' => $message->ticket->id]);
} | php | public function destroy(Message $message)
{
$this->authorize('delete', $message);
$message->delete();
return redirect()->route('laralum::tickets.show', ['ticket' => $message->ticket->id]);
} | Delete message.
@param \Laralum\Tickets\Models\Message $message
@return \Illuminate\Http\Response | https://github.com/Laralum/Tickets/blob/834b04e28cc3be285fc0eac1a673f6370079e6d2/src/Controllers/MessageController.php#L116-L122 |
guardianphp/user | src/Authenticator/UserPassword.php | UserPassword.authenticate | public function authenticate($subject, Caller $caller)
{
Assertion::isArray($subject);
Assertion::choicesNotEmpty($subject, ['password']);
Assertion::isInstanceOf(
$caller,
'Guardian\User\Caller',
sprintf('The caller was expected to be an instance of "%s"', 'Indigo\Guardian\Caller\User')
);
return $this->hasher->verify($subject['password'], $caller->getPassword());
} | php | public function authenticate($subject, Caller $caller)
{
Assertion::isArray($subject);
Assertion::choicesNotEmpty($subject, ['password']);
Assertion::isInstanceOf(
$caller,
'Guardian\User\Caller',
sprintf('The caller was expected to be an instance of "%s"', 'Indigo\Guardian\Caller\User')
);
return $this->hasher->verify($subject['password'], $caller->getPassword());
} | {@inheritdoc} | https://github.com/guardianphp/user/blob/ef5eed69a1dc5c4e8b95049993751c5772ddbd7f/src/Authenticator/UserPassword.php#L33-L44 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.make | public function make($key, $params = [])
{
if($this->aliasExist($key)) {
return $this->make($this->aliases[$key], $params);
}
if(is_callable($key)) {
return call_user_func_array($key, $this->resolveCallback($key, $params));
}
return $this->resolveClass($key, $params);
} | php | public function make($key, $params = [])
{
if($this->aliasExist($key)) {
return $this->make($this->aliases[$key], $params);
}
if(is_callable($key)) {
return call_user_func_array($key, $this->resolveCallback($key, $params));
}
return $this->resolveClass($key, $params);
} | Resolved dependencies for a key.
@param string $key
@param array $params
@return object
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L38-L49 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.need | public function need($key)
{
if(!isset($this->resolved[$key])) {
return $this->make($key);
}
return $this->resolved[$key];
} | php | public function need($key)
{
if(!isset($this->resolved[$key])) {
return $this->make($key);
}
return $this->resolved[$key];
} | Get the resolved type for a key that already resolved by the container.
If the key does not resolve, at first resolved it,
then returns the resolved type.
@param string $key
@return mixed | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L60-L67 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.bind | public function bind($key, $value)
{
if(is_callable($value)) {
$this->aliases[$key] = $value;
} elseif(is_object($value)) {
$this->resolved[$key] = $value;
} else {
if(class_exists($value)) $this->aliases[$key] = $value;
else throw new Exception("Class [ $value ] does not exist.");
}
} | php | public function bind($key, $value)
{
if(is_callable($value)) {
$this->aliases[$key] = $value;
} elseif(is_object($value)) {
$this->resolved[$key] = $value;
} else {
if(class_exists($value)) $this->aliases[$key] = $value;
else throw new Exception("Class [ $value ] does not exist.");
}
} | Bind a value for a key.
@param string $key
@param string|callback|object $value
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L77-L87 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.resolveCallback | public function resolveCallback(Closure $callback, $params = [])
{
$reflectionParameter = new ReflectionFunction($callback);
$dependencies = $reflectionParameter->getParameters();
return $this->getDependencies($dependencies, $params);
} | php | public function resolveCallback(Closure $callback, $params = [])
{
$reflectionParameter = new ReflectionFunction($callback);
$dependencies = $reflectionParameter->getParameters();
return $this->getDependencies($dependencies, $params);
} | Resolve dependencies for a callback.
@param Closure $callback
@param array $params
@return array
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L99-L106 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.resolveMethod | public function resolveMethod($class, $method, $params = [], $isRoute = false)
{
$reflectionMethod = new ReflectionMethod($class, $method);
$dependencies = $reflectionMethod->getParameters();
return $this->getDependencies($dependencies, $params, $isRoute);
} | php | public function resolveMethod($class, $method, $params = [], $isRoute = false)
{
$reflectionMethod = new ReflectionMethod($class, $method);
$dependencies = $reflectionMethod->getParameters();
return $this->getDependencies($dependencies, $params, $isRoute);
} | Resolve dependencies for a method.
@param string $class
@param string $method
@param array $params
@param bool $isRoute
@return array | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L118-L125 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.resolveClass | public function resolveClass($name, $params = [])
{
$reflectionClass = new ReflectionClass($name);
if (!$reflectionClass->isInstantiable()) {
throw new Exception("The [ {$name} ] is not instantiable.");
}
$constructor = $reflectionClass->getConstructor();
if (!is_null($constructor)) {
$dependencies = $constructor->getParameters();
$resolving = $this->getDependencies($dependencies, $params);
$instance = $reflectionClass->newInstanceArgs($resolving);
return $this->resolved[$name] = $this->getInstanceWithAppProperty($instance);
}
$instance = new $name;
return $this->resolved[$name] = $this->getInstanceWithAppProperty($instance);
} | php | public function resolveClass($name, $params = [])
{
$reflectionClass = new ReflectionClass($name);
if (!$reflectionClass->isInstantiable()) {
throw new Exception("The [ {$name} ] is not instantiable.");
}
$constructor = $reflectionClass->getConstructor();
if (!is_null($constructor)) {
$dependencies = $constructor->getParameters();
$resolving = $this->getDependencies($dependencies, $params);
$instance = $reflectionClass->newInstanceArgs($resolving);
return $this->resolved[$name] = $this->getInstanceWithAppProperty($instance);
}
$instance = new $name;
return $this->resolved[$name] = $this->getInstanceWithAppProperty($instance);
} | Resolve dependencies for a class.
@param string $name
@param array $params
@return object
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L136-L159 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.getDependencies | protected function getDependencies($dependencies, $params = [], $isRoute = false)
{
$resolving = [];
foreach ($dependencies as $dependency) {
if ($dependency->isDefaultValueAvailable()) {
$resolving = $this->getDependencyDefaultValue($dependency, $params, $resolving, $isRoute);
} elseif(isset($params[$dependency->name])) {
$resolving[] = $params[$dependency->name];
} else {
if ($dependency->getClass() === null) {
throw new Exception("The [ $" . "{$dependency->name} ] is not instantiable.");
}
$className = $dependency->getClass()->name;
if (!isset($this->resolved[$className])) {
$this->resolved[$className] = $this->make($className);
$resolving[] = $this->resolved[$className];
} else {
$resolving[] = $this->resolved[$className];
}
}
}
return $resolving;
} | php | protected function getDependencies($dependencies, $params = [], $isRoute = false)
{
$resolving = [];
foreach ($dependencies as $dependency) {
if ($dependency->isDefaultValueAvailable()) {
$resolving = $this->getDependencyDefaultValue($dependency, $params, $resolving, $isRoute);
} elseif(isset($params[$dependency->name])) {
$resolving[] = $params[$dependency->name];
} else {
if ($dependency->getClass() === null) {
throw new Exception("The [ $" . "{$dependency->name} ] is not instantiable.");
}
$className = $dependency->getClass()->name;
if (!isset($this->resolved[$className])) {
$this->resolved[$className] = $this->make($className);
$resolving[] = $this->resolved[$className];
} else {
$resolving[] = $this->resolved[$className];
}
}
}
return $resolving;
} | Get all required dependencies.
@param string $dependencies
@param array $params
@param bool $isRoute
@return array
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L171-L197 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.has | public function has($key)
{
if(array_key_exists($key, $this->aliases) || array_key_exists($key, $this->resolved)) {
return true;
} else {
return false;
}
} | php | public function has($key)
{
if(array_key_exists($key, $this->aliases) || array_key_exists($key, $this->resolved)) {
return true;
} else {
return false;
}
} | Check a key is already exists.
@param string $key
@return bool | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L206-L213 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.offsetGet | public function offsetGet($key)
{
if(array_key_exists($key, $this->resolved)) {
return $this->resolved[$key];
}
return $this->make($key);
} | php | public function offsetGet($key)
{
if(array_key_exists($key, $this->resolved)) {
return $this->resolved[$key];
}
return $this->make($key);
} | @param mixed $key
@return mixed | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L258-L265 |
IftekherSunny/Planet-Framework | src/Sun/Container/Container.php | Container.getDependencyDefaultValue | protected function getDependencyDefaultValue($dependency, $params, $resolving, $isRoute)
{
if ($isRoute) {
if(isset($params[$dependency->name])) {
$resolving[] = $params[$dependency->name];
} else {
$resolving[] = $dependency->getDefaultValue();
}
return $resolving;
} else {
$resolving[] = $dependency->getDefaultValue();
return $resolving;
}
} | php | protected function getDependencyDefaultValue($dependency, $params, $resolving, $isRoute)
{
if ($isRoute) {
if(isset($params[$dependency->name])) {
$resolving[] = $params[$dependency->name];
} else {
$resolving[] = $dependency->getDefaultValue();
}
return $resolving;
} else {
$resolving[] = $dependency->getDefaultValue();
return $resolving;
}
} | Get dependency default value.
@param $dependency
@param $params
@param $resolving
@param $isRoute
@return array | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Container/Container.php#L309-L324 |
schpill/thin | src/Html/Cell.php | Cell.cell | public function cell($value, array $attributes = null)
{
$cell = new self;
$cell->setValue($value);
if (null !== $attributes) {
$cell->setAttributes($attributes);
}
return $cell;
} | php | public function cell($value, array $attributes = null)
{
$cell = new self;
$cell->setValue($value);
if (null !== $attributes) {
$cell->setAttributes($attributes);
}
return $cell;
} | Generates a new table cell
@param string $value
@param array $attributes
@return FTV_Html_Cell | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Cell.php#L77-L87 |
gregorybesson/AdfabCore | src/AdfabCore/View/Helper/AdCKEditor.php | AdCKEditor.AdCKEditor | public function AdCKEditor($name,$options = array())
{
$CKEditor = new \AdfabCore\Service\CKEditor();
$CKEditor->returnOutput = true;
/*
* General module configurations
*/
if(isset($this->Config['BasePath'])) $CKEditor->basePath = $this->Config['BasePath'].'/';
if(isset($this->Config['Toolbar'])) $CKEditor->config['toolbar'] = $this->Config['Toolbar'];
if(isset($this->Config['Width'])) $CKEditor->config['width'] = $this->Config['Width'];
if(isset($this->Config['Height'])) $CKEditor->config['height'] = $this->Config['Height'];
if(isset($this->Config['Language'])) $CKEditor->config['language'] = $this->Config['Language'];
if(isset($this->Config['Color'])) $CKEditor->config['uiColor'] = $this->Config['Color'];
if(isset($this->Config['stylesSet'])) $CKEditor->config['stylesSet'] = $this->Config['stylesSet'];
if(isset($this->Config['contentsCss'])) $CKEditor->config['contentsCss']= $this->Config['contentsCss'];
if(isset($this->Config['templates_files'])) $CKEditor->config['templates_files'] = $this->Config['templates_files'];
// El Finder
if(isset($this->Config['ElFinderBaseURL'])) $CKEditor->config['filebrowserBrowseUrl'] = $this->Config['ElFinderBaseURL'];
if(isset($this->Config['ElFinderWindowWidth'])) $CKEditor->config['filebrowserWindowWidth'] = $this->Config['ElFinderWindowWidth'];
if(isset($this->Config['ElFinderWindowHeight'])) $CKEditor->config['filebrowserWindowHeight'] = $this->Config['ElFinderWindowHeight'];
/*
* special confirmations in your form
*/
if(isset($options['BasePath'])) $CKEditor->basePath = $options['BasePath'].'/';
if(isset($options['Toolbar'])) $CKEditor->config['toolbar'] = $options['Toolbar'];
if(isset($options['toolbar'])) $CKEditor->config['toolbar'] = $options['toolbar'];
if(isset($options['Width'])) $CKEditor->config['width'] = $options['Width'];
if(isset($options['Height'])) $CKEditor->config['height'] = $options['Height'];
if(isset($options['Language'])) $CKEditor->config['language'] = $options['Language'];
if(isset($options['Color'])) $CKEditor->config['uiColor'] = $options['uiColor'];
if(isset($options['stylesSet'])) $CKEditor->config['stylesSet'] = $options['stylesSet'];
if(isset($options['contentsCss'])) $CKEditor->config['contentsCss'] = $options['contentsCss'];
if(isset($options['templates_files'])) $CKEditor->config['templates_files'] = $options['templates_files'];
// El Finder
if(isset($options['ElFinderBaseURL'])) $CKEditor->config['filebrowserBrowseUrl'] = $options['ElFinderBaseURL'];
if(isset($options['ElFinderWindowWidth'])) $CKEditor->config['filebrowserWindowWidth'] = $options['ElFinderWindowWidth'];
if(isset($options['ElFinderWindowHeight'])) $CKEditor->config['filebrowserWindowHeight'] = $options['ElFinderWindowHeight'];
echo $CKEditor->replace($name);
} | php | public function AdCKEditor($name,$options = array())
{
$CKEditor = new \AdfabCore\Service\CKEditor();
$CKEditor->returnOutput = true;
/*
* General module configurations
*/
if(isset($this->Config['BasePath'])) $CKEditor->basePath = $this->Config['BasePath'].'/';
if(isset($this->Config['Toolbar'])) $CKEditor->config['toolbar'] = $this->Config['Toolbar'];
if(isset($this->Config['Width'])) $CKEditor->config['width'] = $this->Config['Width'];
if(isset($this->Config['Height'])) $CKEditor->config['height'] = $this->Config['Height'];
if(isset($this->Config['Language'])) $CKEditor->config['language'] = $this->Config['Language'];
if(isset($this->Config['Color'])) $CKEditor->config['uiColor'] = $this->Config['Color'];
if(isset($this->Config['stylesSet'])) $CKEditor->config['stylesSet'] = $this->Config['stylesSet'];
if(isset($this->Config['contentsCss'])) $CKEditor->config['contentsCss']= $this->Config['contentsCss'];
if(isset($this->Config['templates_files'])) $CKEditor->config['templates_files'] = $this->Config['templates_files'];
// El Finder
if(isset($this->Config['ElFinderBaseURL'])) $CKEditor->config['filebrowserBrowseUrl'] = $this->Config['ElFinderBaseURL'];
if(isset($this->Config['ElFinderWindowWidth'])) $CKEditor->config['filebrowserWindowWidth'] = $this->Config['ElFinderWindowWidth'];
if(isset($this->Config['ElFinderWindowHeight'])) $CKEditor->config['filebrowserWindowHeight'] = $this->Config['ElFinderWindowHeight'];
/*
* special confirmations in your form
*/
if(isset($options['BasePath'])) $CKEditor->basePath = $options['BasePath'].'/';
if(isset($options['Toolbar'])) $CKEditor->config['toolbar'] = $options['Toolbar'];
if(isset($options['toolbar'])) $CKEditor->config['toolbar'] = $options['toolbar'];
if(isset($options['Width'])) $CKEditor->config['width'] = $options['Width'];
if(isset($options['Height'])) $CKEditor->config['height'] = $options['Height'];
if(isset($options['Language'])) $CKEditor->config['language'] = $options['Language'];
if(isset($options['Color'])) $CKEditor->config['uiColor'] = $options['uiColor'];
if(isset($options['stylesSet'])) $CKEditor->config['stylesSet'] = $options['stylesSet'];
if(isset($options['contentsCss'])) $CKEditor->config['contentsCss'] = $options['contentsCss'];
if(isset($options['templates_files'])) $CKEditor->config['templates_files'] = $options['templates_files'];
// El Finder
if(isset($options['ElFinderBaseURL'])) $CKEditor->config['filebrowserBrowseUrl'] = $options['ElFinderBaseURL'];
if(isset($options['ElFinderWindowWidth'])) $CKEditor->config['filebrowserWindowWidth'] = $options['ElFinderWindowWidth'];
if(isset($options['ElFinderWindowHeight'])) $CKEditor->config['filebrowserWindowHeight'] = $options['ElFinderWindowHeight'];
echo $CKEditor->replace($name);
} | @param $name
@param $options
@return string | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/View/Helper/AdCKEditor.php#L40-L84 |
Dhii/map | src/IteratorAwareTrait.php | IteratorAwareTrait._getIterator | protected function _getIterator()
{
if (is_null($this->iterator)) {
$this->iterator = $this->_resolveIterator($this->_getDataStore());
}
return $this->iterator;
} | php | protected function _getIterator()
{
if (is_null($this->iterator)) {
$this->iterator = $this->_resolveIterator($this->_getDataStore());
}
return $this->iterator;
} | Retrieves the iterator of this instance's data store.
@since [*next-version*]
@return Iterator The iterator. | https://github.com/Dhii/map/blob/9ec82af42b7cb33d3b0b70d753e8a2bc7451cedf/src/IteratorAwareTrait.php#L35-L42 |
Dhii/map | src/IteratorAwareTrait.php | IteratorAwareTrait._setIterator | protected function _setIterator($iterator)
{
if ($iterator !== null && !($iterator instanceof Iterator)) {
throw $this->_createInvalidArgumentException(
$this->__('Invalid iterator'),
null,
null,
$iterator
);
}
$this->iterator = $iterator;
} | php | protected function _setIterator($iterator)
{
if ($iterator !== null && !($iterator instanceof Iterator)) {
throw $this->_createInvalidArgumentException(
$this->__('Invalid iterator'),
null,
null,
$iterator
);
}
$this->iterator = $iterator;
} | Sets the iterator for this instance.
@since [*next-version*]
@param Iterator|null $iterator The iterator instance, or null. | https://github.com/Dhii/map/blob/9ec82af42b7cb33d3b0b70d753e8a2bc7451cedf/src/IteratorAwareTrait.php#L51-L63 |
lechimp-p/flightcontrol | src/FDirectory.php | FDirectory.fmap | public function fmap(\Closure $trans) {
return $this->flightcontrol()->newFDirectory($this, function() use ($trans) {
return array_map($trans, $this->fcontents());
});
} | php | public function fmap(\Closure $trans) {
return $this->flightcontrol()->newFDirectory($this, function() use ($trans) {
return array_map($trans, $this->fcontents());
});
} | As this is as functor, we could map over it.
Turns an FDirectory a to an FDirectory b by using the provided $trans
function.
@param \Closure $trans a -> b
@return FDirectory | https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/FDirectory.php#L76-L80 |
lechimp-p/flightcontrol | src/FDirectory.php | FDirectory.outer_fmap | public function outer_fmap(\Closure $trans) {
return $this->flightcontrol()->newFDirectory($this, function() use ($trans) {
return $trans($this->fcontents());
});
} | php | public function outer_fmap(\Closure $trans) {
return $this->flightcontrol()->newFDirectory($this, function() use ($trans) {
return $trans($this->fcontents());
});
} | We could also map the complete array to a new array, e.g. to
filter it, make it longer or shorter.
@param \Closure $trans [a] -> [b]
@throws UnexpectedValueException in case $trans returns no error
@return FDirectory | https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/FDirectory.php#L90-L94 |
lechimp-p/flightcontrol | src/FDirectory.php | FDirectory.fold | public function fold($start_value, $iteration) {
return $this->outer_fmap(function($contents) use ($start_value, $iteration) {
$value = $start_value;
foreach($contents as $content) {
$value = $iteration($value, $content);
}
return $value;
});
} | php | public function fold($start_value, $iteration) {
return $this->outer_fmap(function($contents) use ($start_value, $iteration) {
$value = $start_value;
foreach($contents as $content) {
$value = $iteration($value, $content);
}
return $value;
});
} | Define the function to be iterated with and close this level
of iteration.
@param \Closure $iteration a -> File|Directory -> a
@return Iterator|a | https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/FDirectory.php#L103-L111 |
lechimp-p/flightcontrol | src/FDirectory.php | FDirectory.filter | public function filter(\Closure $predicate) {
return
$this->outer_fmap(function($fcontents) use ($predicate) {
return array_filter($fcontents, $predicate);
});
} | php | public function filter(\Closure $predicate) {
return
$this->outer_fmap(function($fcontents) use ($predicate) {
return array_filter($fcontents, $predicate);
});
} | We could filter the FDirectory by a $predicate-
@param \Closure $predicate a -> bool
@return FDirectory | https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/FDirectory.php#L119-L124 |
lechimp-p/flightcontrol | src/FDirectory.php | FDirectory.fcontents | public function fcontents() {
if ($this->contents === null) {
$cl = $this->contents_lazy;
$this->contents = $cl();
}
return $this->contents;
} | php | public function fcontents() {
if ($this->contents === null) {
$cl = $this->contents_lazy;
$this->contents = $cl();
}
return $this->contents;
} | The contents of this directory.
It should really return type any[], as we do want to return an array
from things of the same type (but depend on the construction of this
object).
@return mixed[] for an FDirectory a | https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/FDirectory.php#L135-L141 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.checkSession | public function checkSession()
{
// Get session token
$session_token = isset($_COOKIE[$this->cookie_name]) ? $_COOKIE[$this->cookie_name]
: (isset($_SERVER['HTTP_AUTH_TOKEN']) ? $_SERVER['HTTP_AUTH_TOKEN'] : null);
// Get reference to session state machine
if ($session_token) {
// Get session machine ref
$session_id = (array) $this->session_machine_ref_prefix;
$session_id[] = $session_token;
$this->session_machine = $this->smalldb->ref($session_id);
// Check session
if ($this->session_machine->state == '') {
// Invalid token
$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
} else {
// TODO: Validate token, not only session existence, and check whether session is in valid state (invoke a transition to check).
// TODO: Session should tell how long it will last so the cookie should have the same duration.
// Token is good - refresh cookie
setcookie($this->cookie_name, $session_token, time() + $this->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
}
} else {
// No token
$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
}
// Update token on state change
$t = $this;
$this->session_machine->afterTransition()->addListener(function($ref, $transition_name, $arguments, $return_value, $returns) use ($t) {
if (!$ref->state) {
// Remove cookie when session is terminated
setcookie($t->cookie_name, null, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
if (isset($_SESSION)) {
// Kill PHP session if in use
session_regenerate_id(true);
}
} else {
// Update cookie on state change
setcookie($t->cookie_name, $ref->id, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
}
});
// Everything else is up to the state machine
} | php | public function checkSession()
{
// Get session token
$session_token = isset($_COOKIE[$this->cookie_name]) ? $_COOKIE[$this->cookie_name]
: (isset($_SERVER['HTTP_AUTH_TOKEN']) ? $_SERVER['HTTP_AUTH_TOKEN'] : null);
// Get reference to session state machine
if ($session_token) {
// Get session machine ref
$session_id = (array) $this->session_machine_ref_prefix;
$session_id[] = $session_token;
$this->session_machine = $this->smalldb->ref($session_id);
// Check session
if ($this->session_machine->state == '') {
// Invalid token
$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
} else {
// TODO: Validate token, not only session existence, and check whether session is in valid state (invoke a transition to check).
// TODO: Session should tell how long it will last so the cookie should have the same duration.
// Token is good - refresh cookie
setcookie($this->cookie_name, $session_token, time() + $this->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
}
} else {
// No token
$this->session_machine = $this->smalldb->ref($this->session_machine_null_ref);
}
// Update token on state change
$t = $this;
$this->session_machine->afterTransition()->addListener(function($ref, $transition_name, $arguments, $return_value, $returns) use ($t) {
if (!$ref->state) {
// Remove cookie when session is terminated
setcookie($t->cookie_name, null, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
if (isset($_SESSION)) {
// Kill PHP session if in use
session_regenerate_id(true);
}
} else {
// Update cookie on state change
setcookie($t->cookie_name, $ref->id, time() + $t->cookie_ttl, '/', null, !empty($_SERVER['HTTPS']), true);
}
});
// Everything else is up to the state machine
} | Check session - read & update cookies, setup session state machine and register callbacks.
This must be called before using any state machines. No transitions
are invoked at this point, only the session state machine reference
is created. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L98-L145 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.getSessionMachine | public function getSessionMachine()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
return $this->session_machine;
} | php | public function getSessionMachine()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
return $this->session_machine;
} | Get session machine which manages all stuff around login and session. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L151-L157 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.getUserId | public function getUserId()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
return $this->session_machine->state !== '' ? $this->session_machine[$this->user_id_property] : null;
} | php | public function getUserId()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
return $this->session_machine->state !== '' ? $this->session_machine[$this->user_id_property] : null;
} | / @copydoc Smalldb\StateMachine\Auth\IAuth::getUserId() | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L161-L167 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.hasUserRoles | public function hasUserRoles($roles)
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
if (is_array($roles)) {
return count(array_intersect($this->getUserRoles(), $roles)) > 0;
} else {
return in_array($roles, $this->getUserRoles());
}
} | php | public function hasUserRoles($roles)
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
if (is_array($roles)) {
return count(array_intersect($this->getUserRoles(), $roles)) > 0;
} else {
return in_array($roles, $this->getUserRoles());
}
} | / @copydoc Smalldb\StateMachine\Auth\IAuth::hasUserRoles() | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L171-L182 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.isAllMighty | public function isAllMighty()
{
return ($this->all_mighty_cli && empty($_SERVER['REMOTE_ADDR']) && php_sapi_name() == 'cli')
|| ($this->all_mighty_user_role && $this->hasUserRoles($this->all_mighty_user_role));
} | php | public function isAllMighty()
{
return ($this->all_mighty_cli && empty($_SERVER['REMOTE_ADDR']) && php_sapi_name() == 'cli')
|| ($this->all_mighty_user_role && $this->hasUserRoles($this->all_mighty_user_role));
} | / @copydoc Smalldb\StateMachine\Auth\IAuth::isAllMighty() | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L185-L189 |
smalldb/libSmalldb | class/Auth/CookieAuth.php | CookieAuth.getUserRoles | protected function getUserRoles()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
if ($this->session_machine->state == '') {
return null;
} else {
return (array) $this->session_machine[$this->user_roles_property];
}
} | php | protected function getUserRoles()
{
if ($this->session_machine === null) {
throw new RuntimeException('Session machine not ready ‒ '.__METHOD__.' called too soon.');
}
if ($this->session_machine->state == '') {
return null;
} else {
return (array) $this->session_machine[$this->user_roles_property];
}
} | Get list of user's roles, or null if not logged in.
@note User's roles are typically not property of the session
machine, but they can be calculated property of the machine.
Therefore, there is no need to complicate this API with users. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Auth/CookieAuth.php#L199-L210 |
payapi/payapi-sdk-php | src/payapi/plugin/plugin.boc.php | plugin.consumerId | public function consumerId()
{
if (isset($this->session->data['customer_id']) === true) {
return $this->session->data['customer_id'];
}
return null;
} | php | public function consumerId()
{
if (isset($this->session->data['customer_id']) === true) {
return $this->session->data['customer_id'];
}
return null;
} | -> NEW | https://github.com/payapi/payapi-sdk-php/blob/6a675749c88742b261178d7977f2436d540132b4/src/payapi/plugin/plugin.boc.php#L134-L140 |
payapi/payapi-sdk-php | src/payapi/plugin/plugin.boc.php | plugin.consumerEmail | public function consumerEmail()
{
if ($this->consumerId() !== null) {
$customer_id = $this->consumerId();
$query =
$this->db->query("SELECT `email` FROM `" . DB_PREFIX . "customer` WHERE `customer_id` = '" . $customer_id . "' LIMIT 1");
if (isset($query->row['email']) === true) {
return $query->row['email'];
}
}
return null;
} | php | public function consumerEmail()
{
if ($this->consumerId() !== null) {
$customer_id = $this->consumerId();
$query =
$this->db->query("SELECT `email` FROM `" . DB_PREFIX . "customer` WHERE `customer_id` = '" . $customer_id . "' LIMIT 1");
if (isset($query->row['email']) === true) {
return $query->row['email'];
}
}
return null;
} | -> TODO | https://github.com/payapi/payapi-sdk-php/blob/6a675749c88742b261178d7977f2436d540132b4/src/payapi/plugin/plugin.boc.php#L142-L153 |
acacha/forge-publish | src/Console/Commands/PublishDomain.php | PublishDomain.defaultDomain | protected function defaultDomain()
{
if ($suffix = $this->parser->getDomainSuffix()) {
return strtolower(camel_case(basename(getcwd()))) . '.' . $suffix;
}
return '';
} | php | protected function defaultDomain()
{
if ($suffix = $this->parser->getDomainSuffix()) {
return strtolower(camel_case(basename(getcwd()))) . '.' . $suffix;
}
return '';
} | Default domain.
@return string | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDomain.php#L89-L95 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._init | public function _init() {
parent::_init();
if (!$model = $this->_model) {
throw new ConfigException("`'model'` option needs to be defined.");
}
$behavior = $this;
$model::applyFilter('save', function($self, $params, $chain) use ($behavior) {
if ($behavior->invokeMethod('_beforeSave', [$params])) {
return $chain->next($self, $params, $chain);
}
});
$model::applyFilter('delete', function($self, $params, $chain) use ($behavior) {
if ($behavior->invokeMethod('_beforeDelete', [$params])) {
return $chain->next($self, $params, $chain);
}
});
} | php | public function _init() {
parent::_init();
if (!$model = $this->_model) {
throw new ConfigException("`'model'` option needs to be defined.");
}
$behavior = $this;
$model::applyFilter('save', function($self, $params, $chain) use ($behavior) {
if ($behavior->invokeMethod('_beforeSave', [$params])) {
return $chain->next($self, $params, $chain);
}
});
$model::applyFilter('delete', function($self, $params, $chain) use ($behavior) {
if ($behavior->invokeMethod('_beforeDelete', [$params])) {
return $chain->next($self, $params, $chain);
}
});
} | Initializer function called by the constructor unless the constructor `'init'` flag is set
to `false`.
@see lithium\core\Object
@throws ConfigException | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L45-L62 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._scope | protected function _scope($entity) {
$scope = [];
foreach ($this->_config['scope'] as $key => $value) {
if (is_numeric($key)) {
if (isset($entity, $value)) {
$scope[$value] = $entity->$value;
} else {
$message = "The `{$value}` scope in not present in the entity.";
throw new UnexpectedValueException($message);
}
} else {
$scope[$key] = $value;
}
}
return $scope;
} | php | protected function _scope($entity) {
$scope = [];
foreach ($this->_config['scope'] as $key => $value) {
if (is_numeric($key)) {
if (isset($entity, $value)) {
$scope[$value] = $entity->$value;
} else {
$message = "The `{$value}` scope in not present in the entity.";
throw new UnexpectedValueException($message);
}
} else {
$scope[$key] = $value;
}
}
return $scope;
} | Setting a scope to an entity node.
@param object $entity
@return array The scope values
@throws UnexpectedValueException | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L71-L86 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.childrens | public function childrens($entity, $rec = null, $mode = 'all') {
extract($this->_config);
$recursive = $rec ? : $recursive;
if ($recursive) {
if ($mode === 'count') {
return ($entity->$right - $entity->$left - 1) / 2;
} else {
return $model::find($mode, [
'conditions' => [
$left => ['>' => $entity->$left],
$right => ['<' => $entity->$right]
] + $this->_scope($entity),
'order' => [$left => 'asc']]
);
}
} else {
$id = $entity->{$model::key()};
return $model::find($mode, [
'conditions' => [$parent => $id] + $this->_scope($entity),
'order' => [$left => 'asc']]
);
}
} | php | public function childrens($entity, $rec = null, $mode = 'all') {
extract($this->_config);
$recursive = $rec ? : $recursive;
if ($recursive) {
if ($mode === 'count') {
return ($entity->$right - $entity->$left - 1) / 2;
} else {
return $model::find($mode, [
'conditions' => [
$left => ['>' => $entity->$left],
$right => ['<' => $entity->$right]
] + $this->_scope($entity),
'order' => [$left => 'asc']]
);
}
} else {
$id = $entity->{$model::key()};
return $model::find($mode, [
'conditions' => [$parent => $id] + $this->_scope($entity),
'order' => [$left => 'asc']]
);
}
} | Returns all childrens of given element (including subchildren if `$recursive` is set
to true or recursive is configured true)
@param object $entity The entity to fetch the children of
@param Boolean $recursive Overrides configured recursive param for this method | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L95-L119 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.path | public function path($entity) {
extract($this->_config);
$data = [];
while ($entity->data($parent) !== null) {
$data[] = $entity;
$entity = $this->_getById($entity->$parent);
}
$data[] = $entity;
$data = array_reverse($data);
$model = $entity->model();
return $model::create($data, [
'exists' => true,
'class' => 'set'
]);
} | php | public function path($entity) {
extract($this->_config);
$data = [];
while ($entity->data($parent) !== null) {
$data[] = $entity;
$entity = $this->_getById($entity->$parent);
}
$data[] = $entity;
$data = array_reverse($data);
$model = $entity->model();
return $model::create($data, [
'exists' => true,
'class' => 'set'
]);
} | Get path
returns an array containing all elements from the tree root node to the node with given
an entity node (including this entity node) which have a parent/child relationship
@param object $entity | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L129-L144 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.move | public function move($entity, $newPosition, $newParent = null) {
extract($this->_config);
if ($newParent !== null) {
if($this->_scope($entity) !== ($parentScope = $this->_scope($newParent))) {
$entity->set($parentScope);
} elseif ($newParent->$left > $entity->$left && $newParent->$right < $entity->$right) {
return false;
}
$parentId = $newParent->data($model::key());
$entity->set([$parent => $parentId]);
$entity->save();
$parentNode = $newParent;
} else {
$newParent = $this->_getById($entity->$parent);
}
$childrenCount = $newParent->childrens(false, 'count');
$position = $this->_getPosition($entity, $childrenCount);
if ($position !== false) {
$count = abs($newPosition - $position);
for ($i = 0; $i < $count; $i++) {
if ($position < $newPosition) {
$entity->moveDown();
} else {
$entity->moveUp();
}
}
}
return true;
} | php | public function move($entity, $newPosition, $newParent = null) {
extract($this->_config);
if ($newParent !== null) {
if($this->_scope($entity) !== ($parentScope = $this->_scope($newParent))) {
$entity->set($parentScope);
} elseif ($newParent->$left > $entity->$left && $newParent->$right < $entity->$right) {
return false;
}
$parentId = $newParent->data($model::key());
$entity->set([$parent => $parentId]);
$entity->save();
$parentNode = $newParent;
} else {
$newParent = $this->_getById($entity->$parent);
}
$childrenCount = $newParent->childrens(false, 'count');
$position = $this->_getPosition($entity, $childrenCount);
if ($position !== false) {
$count = abs($newPosition - $position);
for ($i = 0; $i < $count; $i++) {
if ($position < $newPosition) {
$entity->moveDown();
} else {
$entity->moveUp();
}
}
}
return true;
} | Move
performs move operations of an entity in tree
@param object $entity the entity node to move
@param integer $newPosition Position new position of node in same level, starting with 0
@param object $newParent The new parent entity node | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L155-L186 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._beforeSave | protected function _beforeSave($params) {
extract($this->_config);
$entity = $params['entity'];
if (!$entity->data($model::key())) {
if ($entity->$parent) {
$this->_insertParent($entity);
} else {
$max = $this->_getMax($entity);
$entity->set([
$left => $max + 1,
$right => $max + 2
]);
}
} elseif (isset($entity->$parent)) {
if ($entity->$parent === $entity->data($model::key())) {
return false;
}
$oldNode = $this->_getById($entity->data($model::key()));
if ($oldNode->$parent === $entity->$parent) {
return true;
}
if (($newScope = $this->_scope($entity)) !== ($oldScope = $this->_scope($oldNode))) {
$this->_updateScope($entity, $oldScope, $newScope);
return true;
}
$this->_updateNode($entity);
}
return true;
} | php | protected function _beforeSave($params) {
extract($this->_config);
$entity = $params['entity'];
if (!$entity->data($model::key())) {
if ($entity->$parent) {
$this->_insertParent($entity);
} else {
$max = $this->_getMax($entity);
$entity->set([
$left => $max + 1,
$right => $max + 2
]);
}
} elseif (isset($entity->$parent)) {
if ($entity->$parent === $entity->data($model::key())) {
return false;
}
$oldNode = $this->_getById($entity->data($model::key()));
if ($oldNode->$parent === $entity->$parent) {
return true;
}
if (($newScope = $this->_scope($entity)) !== ($oldScope = $this->_scope($oldNode))) {
$this->_updateScope($entity, $oldScope, $newScope);
return true;
}
$this->_updateNode($entity);
}
return true;
} | Before save
this method is called befor each save
@param array $params | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L195-L224 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._insertParent | protected function _insertParent($entity) {
extract($this->_config);
$parent = $this->_getById($entity->$parent);
if ($parent) {
$r = $parent->$right;
$this->_update($r, '+', 2, $this->_scope($entity));
$entity->set([
$left => $r,
$right => $r + 1
]);
}
} | php | protected function _insertParent($entity) {
extract($this->_config);
$parent = $this->_getById($entity->$parent);
if ($parent) {
$r = $parent->$right;
$this->_update($r, '+', 2, $this->_scope($entity));
$entity->set([
$left => $r,
$right => $r + 1
]);
}
} | Insert a parent
inserts a node at given last position of parent set in $entity
@param object $entity | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L244-L255 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._updateNode | protected function _updateNode($entity) {
extract($this->_config);
$span = $entity->$right - $entity->$left;
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftY = $span + 1;
if ($entity->$parent !== null) {
$newParent = $this->_getById($entity->$parent);
if ($newParent) {
$boundary = $newParent->$right;
} else {
throw new UnexpectedValueException("The `{$parent}` with id `{$entity->$parent}` doesn't exists.");
}
} else {
$boundary = $this->_getMax($entity) + 1;
}
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
if ($entity->$right < $boundary) {
$rangeY = ['floor' => $entity->$right + 1, 'ceiling' => $boundary - 1];
$this->_updateBetween($rangeY, '-', $shiftY, $this->_scope($entity));
$shiftX = $boundary - $entity->$right - 1;
} else {
$rangeY = ['floor' => $boundary, 'ceiling' => $entity->$left - 1];
$this->_updateBetween($rangeY, '+', $shiftY, $this->_scope($entity));
$shiftX = ($boundary - 1) - $entity->$left + 1;
}
$this->_updateBetween([
'floor' => (0 - $span), 'ceiling' => 0
], '+', $spanToZero + $shiftX, $this->_scope($entity));
$entity->set([$left => $entity->$left + $shiftX, $right => $entity->$right + $shiftX]);
} | php | protected function _updateNode($entity) {
extract($this->_config);
$span = $entity->$right - $entity->$left;
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftY = $span + 1;
if ($entity->$parent !== null) {
$newParent = $this->_getById($entity->$parent);
if ($newParent) {
$boundary = $newParent->$right;
} else {
throw new UnexpectedValueException("The `{$parent}` with id `{$entity->$parent}` doesn't exists.");
}
} else {
$boundary = $this->_getMax($entity) + 1;
}
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
if ($entity->$right < $boundary) {
$rangeY = ['floor' => $entity->$right + 1, 'ceiling' => $boundary - 1];
$this->_updateBetween($rangeY, '-', $shiftY, $this->_scope($entity));
$shiftX = $boundary - $entity->$right - 1;
} else {
$rangeY = ['floor' => $boundary, 'ceiling' => $entity->$left - 1];
$this->_updateBetween($rangeY, '+', $shiftY, $this->_scope($entity));
$shiftX = ($boundary - 1) - $entity->$left + 1;
}
$this->_updateBetween([
'floor' => (0 - $span), 'ceiling' => 0
], '+', $spanToZero + $shiftX, $this->_scope($entity));
$entity->set([$left => $entity->$left + $shiftX, $right => $entity->$right + $shiftX]);
} | Update a node (when parent is changed)
all the "move an element with all its children" magic happens here!
first we calculate movements (shiftX, shiftY), afterwards shifting of ranges is done,
where rangeX is is the range of the element to move and rangeY the area between rangeX
and the new position of rangeX.
to avoid double shifting of already shifted data rangex first is shifted in area < 0
(which is always empty), after correcting rangeY's left and rights we move it to its
designated position.
@param object $entity updated tree element | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L270-L304 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._updateScope | protected function _updateScope($entity, $oldScope, $newScope) {
extract($this->_config);
$span = $entity->$right - $entity->$left;
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$this->_updateBetween($rangeX, '-', $spanToZero, $oldScope, $newScope);
$this->_update($entity->$right, '-', $span + 1, $oldScope);
$newParent = $this->_getById($entity->$parent);
$r = $newParent->$right;
$this->_update($r, '+', $span + 1, $newScope);
$this->_updateBetween([
'floor' => (0 - $span), 'ceiling' => 0
], '+', $span + $r, $newScope);
$entity->set([$left => $r, $right => $span + $r]);
} | php | protected function _updateScope($entity, $oldScope, $newScope) {
extract($this->_config);
$span = $entity->$right - $entity->$left;
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$this->_updateBetween($rangeX, '-', $spanToZero, $oldScope, $newScope);
$this->_update($entity->$right, '-', $span + 1, $oldScope);
$newParent = $this->_getById($entity->$parent);
$r = $newParent->$right;
$this->_update($r, '+', $span + 1, $newScope);
$this->_updateBetween([
'floor' => (0 - $span), 'ceiling' => 0
], '+', $span + $r, $newScope);
$entity->set([$left => $r, $right => $span + $r]);
} | Update a node (when scope has changed)
all the "move an element with all its children" magic happens here!
@param object $entity Updated tree element
@param array $oldScope Old scope data
@param array $newScope New scope data | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L315-L333 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._deleteFromTree | protected function _deleteFromTree($entity) {
extract($this->_config);
$span = 1;
if ($entity->$right - $entity->$left !== 1) {
$span = $entity->$right - $entity->$left;
$model::remove([$parent => $entity->data($model::key())]);
}
$this->_update($entity->$right, '-', $span + 1, $this->_scope($entity));
return true;
} | php | protected function _deleteFromTree($entity) {
extract($this->_config);
$span = 1;
if ($entity->$right - $entity->$left !== 1) {
$span = $entity->$right - $entity->$left;
$model::remove([$parent => $entity->data($model::key())]);
}
$this->_update($entity->$right, '-', $span + 1, $this->_scope($entity));
return true;
} | Delete from tree
deletes a node (and its children) from the tree
@param object $entity updated tree element | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L342-L352 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._getById | protected function _getById($id) {
$model = $this->_config['model'];
return $model::find('first', ['conditions' => [$model::key() => $id]]);
} | php | protected function _getById($id) {
$model = $this->_config['model'];
return $model::find('first', ['conditions' => [$model::key() => $id]]);
} | Get by id
returns the element with given id
@param integer $id the id to fetch from db | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L361-L364 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._update | protected function _update($rght, $dir = '+', $span = 2, $scp = []) {
extract($this->_config);
$model::update([$right => (object) ($right . $dir . $span)], [
$right => ['>=' => $rght]
] + $scp);
$model::update([$left => (object) ($left . $dir . $span)], [
$left => ['>' => $rght]
] + $scp);
} | php | protected function _update($rght, $dir = '+', $span = 2, $scp = []) {
extract($this->_config);
$model::update([$right => (object) ($right . $dir . $span)], [
$right => ['>=' => $rght]
] + $scp);
$model::update([$left => (object) ($left . $dir . $span)], [
$left => ['>' => $rght]
] + $scp);
} | Update node indices
Updates the Indices in greater than $rght with given value.
@param integer $rght the right index border to start indexing
@param string $dir Direction +/- (defaults to +)
@param integer $span value to be added/subtracted (defaults to 2)
@param array $scp The scope to apply updates on | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L376-L386 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._updateBetween | protected function _updateBetween($range, $dir = '+', $span = 2, $scp = [], $data = []) {
extract($this->_config);
$model::update([$right => (object) ($right . $dir . $span)], [
$right => [
'>=' => $range['floor'],
'<=' => $range['ceiling']
]] + $scp);
$model::update([$left => (object) ($left . $dir . $span)] + $data, [
$left => [
'>=' => $range['floor'],
'<=' => $range['ceiling']
]] + $scp);
} | php | protected function _updateBetween($range, $dir = '+', $span = 2, $scp = [], $data = []) {
extract($this->_config);
$model::update([$right => (object) ($right . $dir . $span)], [
$right => [
'>=' => $range['floor'],
'<=' => $range['ceiling']
]] + $scp);
$model::update([$left => (object) ($left . $dir . $span)] + $data, [
$left => [
'>=' => $range['floor'],
'<=' => $range['ceiling']
]] + $scp);
} | Update node indices between
Updates the Indices in given range with given value.
@param array $range the range to be updated
@param string $dir Direction +/- (defaults to +)
@param integer $span Value to be added/subtracted (defaults to 2)
@param array $scp The scope to apply updates on
@param array $data Additionnal scope datas (optionnal) | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L399-L413 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.moveDown | public function moveDown($entity) {
extract($this->_config);
$next = $model::find('first', [
'conditions' => [
$parent => $entity->$parent,
$left => $entity->$right + 1
]]);
if ($next !== null) {
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftX = ($next->$right - $next->$left) + 1;
$rangeY = ['floor' => $next->$left, 'ceiling' => $next->$right];
$shiftY = ($entity->$right - $entity->$left) + 1;
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
$this->_updateBetween($rangeY, '-', $shiftY, $this->_scope($entity));
$this->_updateBetween([
'floor' => (0 - $shiftY), 'ceiling' => 0
], '+', $spanToZero + $shiftX, $this->_scope($entity));
$entity->set([
$left => $entity->$left + $shiftX, $right => $entity->$right + $shiftX
]);
}
return true;
} | php | public function moveDown($entity) {
extract($this->_config);
$next = $model::find('first', [
'conditions' => [
$parent => $entity->$parent,
$left => $entity->$right + 1
]]);
if ($next !== null) {
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftX = ($next->$right - $next->$left) + 1;
$rangeY = ['floor' => $next->$left, 'ceiling' => $next->$right];
$shiftY = ($entity->$right - $entity->$left) + 1;
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
$this->_updateBetween($rangeY, '-', $shiftY, $this->_scope($entity));
$this->_updateBetween([
'floor' => (0 - $shiftY), 'ceiling' => 0
], '+', $spanToZero + $shiftX, $this->_scope($entity));
$entity->set([
$left => $entity->$left + $shiftX, $right => $entity->$right + $shiftX
]);
}
return true;
} | Moves an element down in order
@param object $entity The Entity to move down | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L420-L446 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.moveUp | public function moveUp($entity) {
extract($this->_config);
$prev = $model::find('first', [
'conditions' => [
$parent => $entity->$parent,
$right => $entity->$left - 1
]
]);
if (!$prev) {
return true;
}
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftX = ($prev->$right - $prev->$left) + 1;
$rangeY = ['floor' => $prev->$left, 'ceiling' => $prev->$right];
$shiftY = ($entity->$right - $entity->$left) + 1;
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
$this->_updateBetween($rangeY, '+', $shiftY, $this->_scope($entity));
$this->_updateBetween([
'floor' => (0 - $shiftY), 'ceiling' => 0
], '+', $spanToZero - $shiftX, $this->_scope($entity));
$entity->set([
$left => $entity->$left - $shiftX, $right => $entity->$right - $shiftX
]);
return true;
} | php | public function moveUp($entity) {
extract($this->_config);
$prev = $model::find('first', [
'conditions' => [
$parent => $entity->$parent,
$right => $entity->$left - 1
]
]);
if (!$prev) {
return true;
}
$spanToZero = $entity->$right;
$rangeX = ['floor' => $entity->$left, 'ceiling' => $entity->$right];
$shiftX = ($prev->$right - $prev->$left) + 1;
$rangeY = ['floor' => $prev->$left, 'ceiling' => $prev->$right];
$shiftY = ($entity->$right - $entity->$left) + 1;
$this->_updateBetween($rangeX, '-', $spanToZero, $this->_scope($entity));
$this->_updateBetween($rangeY, '+', $shiftY, $this->_scope($entity));
$this->_updateBetween([
'floor' => (0 - $shiftY), 'ceiling' => 0
], '+', $spanToZero - $shiftX, $this->_scope($entity));
$entity->set([
$left => $entity->$left - $shiftX, $right => $entity->$right - $shiftX
]);
return true;
} | Moves an element up in order
@param object $entity The Entity to move up | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L453-L480 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._getMax | protected function _getMax($entity) {
extract($this->_config);
$node = $model::find('first', [
'conditions' => $this->_scope($entity),
'order' => [$right => 'desc']
]);
if ($node) {
return $node->$right;
}
return 0;
} | php | protected function _getMax($entity) {
extract($this->_config);
$node = $model::find('first', [
'conditions' => $this->_scope($entity),
'order' => [$right => 'desc']
]);
if ($node) {
return $node->$right;
}
return 0;
} | Get max
@param object $entity An `Entity` object
@return The highest 'right' | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L488-L499 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree._getPosition | protected function _getPosition($entity, $childrenCount = false) {
extract($this->_config);
$parent = $this->_getById($entity->$parent);
if ($entity->$left === ($parent->$left + 1)) {
return 0;
}
if (($entity->$right + 1) === $parent->$right) {
if ($childrenCount === false) {
$childrenCount = $parent->childrens(false, 'count');
}
return $childrenCount - 1;
}
$count = 0;
$children = $parent->childrens(false);
$id = $entity->data($model::key());
foreach ($children as $child) {
if ($child->data($model::key()) === $id) {
return $count;
}
$count++;
}
return false;
} | php | protected function _getPosition($entity, $childrenCount = false) {
extract($this->_config);
$parent = $this->_getById($entity->$parent);
if ($entity->$left === ($parent->$left + 1)) {
return 0;
}
if (($entity->$right + 1) === $parent->$right) {
if ($childrenCount === false) {
$childrenCount = $parent->childrens(false, 'count');
}
return $childrenCount - 1;
}
$count = 0;
$children = $parent->childrens(false);
$id = $entity->data($model::key());
foreach ($children as $child) {
if ($child->data($model::key()) === $id) {
return $count;
}
$count++;
}
return false;
} | Returns the current position number of an element at the same level,
where 0 is first position
@param object $entity the entity node to get the position from.
@param integer $childrenCount number of children of entity's parent,
performance parameter to avoid double select. | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L509-L537 |
jails/li3_tree | extensions/data/behavior/Tree.php | Tree.verify | public function verify($entity) {
extract($this->_config);
$count = $model::find('count', [
'conditions' => [
$left => ['>' => $entity->$left],
$right => ['<' => $entity->$right]
] + $this->_scope($entity)
]);
if (!$count) {
return true;
}
$min = $entity->$left;
$edge = $entity->$right;
if ($entity->$left >= $entity->$right) {
$id = $entity->data($model::key());
$errors[] = ['root node', "`{$id}`", 'has left greater than right.'];
}
$errors = [];
for ($i = $min; $i <= $edge; $i++) {
$count = $model::find('count', [
'conditions' => [
'or' => [$left => $i, $right => $i]
] + $this->_scope($entity)
]);
if ($count !== 1) {
if ($count === 0) {
$errors[] = ['node boundary', "`{$i}`", 'missing'];
} else {
$errors[] = ['node boundary', "`{$i}`", 'duplicate'];
}
}
}
$node = $model::find('first', [
'conditions' => [
$right => ['<' => $left]
] + $this->_scope($entity)
]);
if ($node) {
$id = $node->data($model::key());
$errors[] = ['node id', "`{$id}`", 'has left greater or equal to right.'];
}
$model::bind('belongsTo', 'Verify', [
'to' => $model,
'key' => $parent
]);
$results = $model::find('all', [
'conditions' => $this->_scope($entity),
'with' => ['Verify']
]);
$id = $model::key();
foreach ($results as $key => $instance) {
if (is_null($instance->$left) || is_null($instance->$right)) {
$errors[] = ['node', $instance->$id,
'has invalid left or right values'];
} elseif ($instance->$left === $instance->$right) {
$errors[] = ['node', $instance->$id,
'left and right values identical'];
} elseif ($instance->$parent) {
if (!isset($instance->verify->$id) || !$instance->verify->$id) {
$errors[] = ['node', $instance->$id,
'The parent node ' . $instance->$parent . ' doesn\'t exist'];
} elseif ($instance->$left < $instance->verify->$left) {
$errors[] = ['node', $instance->$id,
'left less than parent (node ' . $instance->verify->$id . ').'];
} elseif ($instance->$right > $instance->verify->$right) {
$errors[] = ['node', $instance->$id,
'right greater than parent (node ' . $instance->verify->$id . ').'];
}
} elseif ($model::find('count', [
'conditions' => [
$left => ['<' => $instance->$left],
$right => ['>' => $instance->$right]
] + $this->_scope($entity)
])) {
$errors[] = ['node', $instance->$id, 'the parent field is blank, but has a parent'];
}
}
if ($errors) {
return $errors;
}
return true;
} | php | public function verify($entity) {
extract($this->_config);
$count = $model::find('count', [
'conditions' => [
$left => ['>' => $entity->$left],
$right => ['<' => $entity->$right]
] + $this->_scope($entity)
]);
if (!$count) {
return true;
}
$min = $entity->$left;
$edge = $entity->$right;
if ($entity->$left >= $entity->$right) {
$id = $entity->data($model::key());
$errors[] = ['root node', "`{$id}`", 'has left greater than right.'];
}
$errors = [];
for ($i = $min; $i <= $edge; $i++) {
$count = $model::find('count', [
'conditions' => [
'or' => [$left => $i, $right => $i]
] + $this->_scope($entity)
]);
if ($count !== 1) {
if ($count === 0) {
$errors[] = ['node boundary', "`{$i}`", 'missing'];
} else {
$errors[] = ['node boundary', "`{$i}`", 'duplicate'];
}
}
}
$node = $model::find('first', [
'conditions' => [
$right => ['<' => $left]
] + $this->_scope($entity)
]);
if ($node) {
$id = $node->data($model::key());
$errors[] = ['node id', "`{$id}`", 'has left greater or equal to right.'];
}
$model::bind('belongsTo', 'Verify', [
'to' => $model,
'key' => $parent
]);
$results = $model::find('all', [
'conditions' => $this->_scope($entity),
'with' => ['Verify']
]);
$id = $model::key();
foreach ($results as $key => $instance) {
if (is_null($instance->$left) || is_null($instance->$right)) {
$errors[] = ['node', $instance->$id,
'has invalid left or right values'];
} elseif ($instance->$left === $instance->$right) {
$errors[] = ['node', $instance->$id,
'left and right values identical'];
} elseif ($instance->$parent) {
if (!isset($instance->verify->$id) || !$instance->verify->$id) {
$errors[] = ['node', $instance->$id,
'The parent node ' . $instance->$parent . ' doesn\'t exist'];
} elseif ($instance->$left < $instance->verify->$left) {
$errors[] = ['node', $instance->$id,
'left less than parent (node ' . $instance->verify->$id . ').'];
} elseif ($instance->$right > $instance->verify->$right) {
$errors[] = ['node', $instance->$id,
'right greater than parent (node ' . $instance->verify->$id . ').'];
}
} elseif ($model::find('count', [
'conditions' => [
$left => ['<' => $instance->$left],
$right => ['>' => $instance->$right]
] + $this->_scope($entity)
])) {
$errors[] = ['node', $instance->$id, 'the parent field is blank, but has a parent'];
}
}
if ($errors) {
return $errors;
}
return true;
} | Check if the current tree is valid.
Returns true if the tree is valid otherwise an array of (type, incorrect left/right index,
message)
@param object $entity the entity node to get the position from.
@return mixed true if the tree is valid or empty, otherwise an array of (error type [node,
boundary], [incorrect left/right boundary,node id], message) | https://github.com/jails/li3_tree/blob/43fdbe9c621f1f712131c6a338bb5421da67fc17/extensions/data/behavior/Tree.php#L549-L641 |
alphacomm/alpharpc | src/AlphaRPC/Client/AlphaRPCStatus.php | AlphaRPCStatus.queueStatus | public function queueStatus($manager)
{
$socket = $this->getSocket($manager);
$stream = $socket->getStream();
$stream->send(new QueueStatusRequest());
$msg = $stream->read(new TimeoutTimer(1500));
if (!$msg instanceof QueueStatusResponse) {
throw new RuntimeException('Invalid response: '.get_class($msg).'.');
}
return $msg->getQueueStatus();
} | php | public function queueStatus($manager)
{
$socket = $this->getSocket($manager);
$stream = $socket->getStream();
$stream->send(new QueueStatusRequest());
$msg = $stream->read(new TimeoutTimer(1500));
if (!$msg instanceof QueueStatusResponse) {
throw new RuntimeException('Invalid response: '.get_class($msg).'.');
}
return $msg->getQueueStatus();
} | Requests the queue status.
@param string $manager
@return array
@throws \RuntimeException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/AlphaRPCStatus.php#L70-L83 |
igorwanbarros/autenticacao-laravel | src/Querys/PerfisUsuarios.php | PerfisUsuarios.get | public function get($id, $column = 'perfil_id')
{
$this->result
->select('autenticacao_perfis.*', 'autenticacao_users_perfis.*')
->join('autenticacao_perfis', function ($query) {
$query->on('autenticacao_perfis.id', '=', 'autenticacao_users_perfis.perfil_id')
->whereNull('autenticacao_perfis.deleted_at');
})
->where($column, '=', $id);
return $this;
} | php | public function get($id, $column = 'perfil_id')
{
$this->result
->select('autenticacao_perfis.*', 'autenticacao_users_perfis.*')
->join('autenticacao_perfis', function ($query) {
$query->on('autenticacao_perfis.id', '=', 'autenticacao_users_perfis.perfil_id')
->whereNull('autenticacao_perfis.deleted_at');
})
->where($column, '=', $id);
return $this;
} | @param $id
@param string $column
@return Builder | https://github.com/igorwanbarros/autenticacao-laravel/blob/e7e8217dae433934fe46c34516fb2f6f5f932fc1/src/Querys/PerfisUsuarios.php#L28-L39 |
fxpio/fxp-gluon | Block/Type/NavScrollableType.php | NavScrollableType.buildView | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if (null !== $view->parent && \in_array('navbar', $view->parent->vars['block_prefixes'])) {
BlockUtil::addAttributeClass($view->parent, 'has-nav-scrollable');
}
} | php | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if (null !== $view->parent && \in_array('navbar', $view->parent->vars['block_prefixes'])) {
BlockUtil::addAttributeClass($view->parent, 'has-nav-scrollable');
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/NavScrollableType.php#L29-L34 |
fxpio/fxp-gluon | Block/Type/NavScrollableType.php | NavScrollableType.finishView | public function finishView(BlockView $view, BlockInterface $block, array $options)
{
foreach ($view->children as $child) {
if (\in_array('nav', $child->vars['block_prefixes'])) {
BlockUtil::addAttributeClass($view, 'is-nav-'.$child->vars['style'], true);
}
}
} | php | public function finishView(BlockView $view, BlockInterface $block, array $options)
{
foreach ($view->children as $child) {
if (\in_array('nav', $child->vars['block_prefixes'])) {
BlockUtil::addAttributeClass($view, 'is-nav-'.$child->vars['style'], true);
}
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/NavScrollableType.php#L39-L46 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceFormValidators.php | HCServiceFormValidators.optimize | public function optimize (stdClass $data)
{
$data->formValidationName = $data->serviceName . 'Validator';
$data->formValidationNameSpace = str_replace ('\\http\\controllers', '\\validators', $data->controllerNamespace);
$data->formValidationDestination = str_replace ('/http/controllers', '/validators', $data->controllerDestination) . '/' . $data->formValidationName . '.php';
if (isset($data->mainModel->multiLanguage)) {
$data->formTranslationsValidationName = $data->serviceName . 'TranslationsValidator';
$data->formTranslationsValidationDestination = str_replace ('/http/controllers', '/validators', $data->controllerDestination) . '/' . $data->formTranslationsValidationName . '.php';
}
return $data;
} | php | public function optimize (stdClass $data)
{
$data->formValidationName = $data->serviceName . 'Validator';
$data->formValidationNameSpace = str_replace ('\\http\\controllers', '\\validators', $data->controllerNamespace);
$data->formValidationDestination = str_replace ('/http/controllers', '/validators', $data->controllerDestination) . '/' . $data->formValidationName . '.php';
if (isset($data->mainModel->multiLanguage)) {
$data->formTranslationsValidationName = $data->serviceName . 'TranslationsValidator';
$data->formTranslationsValidationDestination = str_replace ('/http/controllers', '/validators', $data->controllerDestination) . '/' . $data->formTranslationsValidationName . '.php';
}
return $data;
} | Optimizing configuration for form creation
@param stdClass $data
@return stdClass | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceFormValidators.php#L21-L33 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceFormValidators.php | HCServiceFormValidators.generate | public function generate (stdClass $data)
{
$files = [];
$this->createFileFromTemplate ([
"destination" => $data->formValidationDestination,
"templateDestination" => __DIR__ . '/../templates/service/validator.hctpl',
"content" => [
"formValidationNameSpace" => $data->formValidationNameSpace,
"formValidationName" => $data->formValidationName,
"formRules" => $this->getRules ($data->mainModel, array_merge ($this->getAutoFill (), ['id']), false),
],
]);
$files[] = $data->formValidationDestination;
if (isset($data->mainModel->multiLanguage)) {
$this->createFileFromTemplate ([
"destination" => $data->formTranslationsValidationDestination,
"templateDestination" => __DIR__ . '/../templates/service/validator.hctpl',
"content" => [
"formValidationNameSpace" => $data->formValidationNameSpace,
"formValidationName" => $data->formTranslationsValidationName,
"formRules" => $this->getRules ($data->mainModel->multiLanguage, array_merge ($this->getAutoFill (), ['id', 'record_id', 'language_id']), true),
],
]);
$files[] = $data->formTranslationsValidationDestination;
}
return $files;
} | php | public function generate (stdClass $data)
{
$files = [];
$this->createFileFromTemplate ([
"destination" => $data->formValidationDestination,
"templateDestination" => __DIR__ . '/../templates/service/validator.hctpl',
"content" => [
"formValidationNameSpace" => $data->formValidationNameSpace,
"formValidationName" => $data->formValidationName,
"formRules" => $this->getRules ($data->mainModel, array_merge ($this->getAutoFill (), ['id']), false),
],
]);
$files[] = $data->formValidationDestination;
if (isset($data->mainModel->multiLanguage)) {
$this->createFileFromTemplate ([
"destination" => $data->formTranslationsValidationDestination,
"templateDestination" => __DIR__ . '/../templates/service/validator.hctpl',
"content" => [
"formValidationNameSpace" => $data->formValidationNameSpace,
"formValidationName" => $data->formTranslationsValidationName,
"formRules" => $this->getRules ($data->mainModel->multiLanguage, array_merge ($this->getAutoFill (), ['id', 'record_id', 'language_id']), true),
],
]);
$files[] = $data->formTranslationsValidationDestination;
}
return $files;
} | Generating validator files
@param stdClass $data
@return array | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceFormValidators.php#L41-L73 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceFormValidators.php | HCServiceFormValidators.getRules | private function getRules (stdClass $model, array $skip, bool $multiLanguage)
{
$output = '';
if (!empty($model)) {
$tpl = file_get_contents (__DIR__ . '/../templates/shared/array.element.hctpl');
foreach ($model->columns as $column) {
if (in_array ($column->Field, $skip))
continue;
$key = $column->Field;
if ($multiLanguage)
$key = 'translations.*.' . $key;
if ($column->Null == "NO") {
$line = str_replace ('{key}', $key, $tpl);
$line = str_replace ('{value}', 'required', $line);
$output .= $line;
}
}
}
return $output;
} | php | private function getRules (stdClass $model, array $skip, bool $multiLanguage)
{
$output = '';
if (!empty($model)) {
$tpl = file_get_contents (__DIR__ . '/../templates/shared/array.element.hctpl');
foreach ($model->columns as $column) {
if (in_array ($column->Field, $skip))
continue;
$key = $column->Field;
if ($multiLanguage)
$key = 'translations.*.' . $key;
if ($column->Null == "NO") {
$line = str_replace ('{key}', $key, $tpl);
$line = str_replace ('{value}', 'required', $line);
$output .= $line;
}
}
}
return $output;
} | get rules
@param stdClass $model
@param array $skip
@param bool $multiLanguage
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceFormValidators.php#L84-L110 |
pmdevelopment/tool-bundle | Components/Helper/ComposerHelper.php | ComposerHelper.getConsoleDir | public static function getConsoleDir()
{
$rootDir = sprintf('%s/../../../../../../../..', __DIR__);
$paths = [
'bin',
'app',
];
foreach ($paths as $path) {
$fullPath = sprintf('%s/%s', $rootDir, $path);
if (true === is_dir($fullPath) && true === file_exists(sprintf('%s/console', $fullPath))) {
return $fullPath;
}
}
return null;
} | php | public static function getConsoleDir()
{
$rootDir = sprintf('%s/../../../../../../../..', __DIR__);
$paths = [
'bin',
'app',
];
foreach ($paths as $path) {
$fullPath = sprintf('%s/%s', $rootDir, $path);
if (true === is_dir($fullPath) && true === file_exists(sprintf('%s/console', $fullPath))) {
return $fullPath;
}
}
return null;
} | Get Console Dir
@return null|string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Components/Helper/ComposerHelper.php#L100-L118 |
mglaman/docker-helper | src/Machine.php | Machine.start | public static function start($name)
{
// Check if machine is running.
$status = self::status($name);
if ($status == self::STOPPED) {
// If not, try to start it.
return self::runCommand('start', [$name])->isSuccessful();
}
return $status == Machine::RUNNING;
} | php | public static function start($name)
{
// Check if machine is running.
$status = self::status($name);
if ($status == self::STOPPED) {
// If not, try to start it.
return self::runCommand('start', [$name])->isSuccessful();
}
return $status == Machine::RUNNING;
} | Start a machine.
@param $name
@return bool
@throws \Exception | https://github.com/mglaman/docker-helper/blob/b262a50dcdbc495487568f775a8f41da82ae2c03/src/Machine.php#L45-L56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.