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
|
---|---|---|---|---|---|---|---|
zarathustra323/modlr-data | src/Zarathustra/ModlrData/DataTypes/TypeFactory.php | TypeFactory.overrideType | public function overrideType($name, $fqcn)
{
if (false === $this->hasType($name)) {
throw new InvalidArgumentException(sprintf('The type "%s" was not found.', $name));
}
return $this->setType($name, $fqcn);
} | php | public function overrideType($name, $fqcn)
{
if (false === $this->hasType($name)) {
throw new InvalidArgumentException(sprintf('The type "%s" was not found.', $name));
}
return $this->setType($name, $fqcn);
} | Overrides a type object with new class.
@param string $name
@param string $fqcn
@return self
@throws InvalidArgumentException If the type was not found. | https://github.com/zarathustra323/modlr-data/blob/7c2c767216055f75abf8cf22e2200f11998ed24e/src/Zarathustra/ModlrData/DataTypes/TypeFactory.php#L126-L132 |
bkstg/schedule-bundle | Timeline/EventSubscriber/EventLinkSubscriber.php | EventLinkSubscriber.setInvitedLink | public function setInvitedLink(TimelineLinkEvent $event): void
{
$action = $event->getAction();
if ('invited' != $action->getVerb()) {
return;
}
$event = $action->getComponent('indirectComplement')->getData();
$event->setLink($this->url_generator->generate('bkstg_event_read', [
'id' => $event->getId(),
'production_slug' => $event->getGroups()[0]->getSlug(),
]));
} | php | public function setInvitedLink(TimelineLinkEvent $event): void
{
$action = $event->getAction();
if ('invited' != $action->getVerb()) {
return;
}
$event = $action->getComponent('indirectComplement')->getData();
$event->setLink($this->url_generator->generate('bkstg_event_read', [
'id' => $event->getId(),
'production_slug' => $event->getGroups()[0]->getSlug(),
]));
} | Set the link for invited actions.
@param TimelineLinkEvent $event The timeline action event.
@return void | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Timeline/EventSubscriber/EventLinkSubscriber.php#L54-L67 |
bkstg/schedule-bundle | Timeline/EventSubscriber/EventLinkSubscriber.php | EventLinkSubscriber.setScheduledLink | public function setScheduledLink(TimelineLinkEvent $event): void
{
$action = $event->getAction();
if ('scheduled' != $action->getVerb()) {
return;
}
$production = $action->getComponent('indirectComplement')->getData();
$schedule = $action->getComponent('directComplement')->getData();
$event->setLink($this->url_generator->generate('bkstg_schedule_read', [
'id' => $schedule->getId(),
'production_slug' => $production->getSlug(),
]));
} | php | public function setScheduledLink(TimelineLinkEvent $event): void
{
$action = $event->getAction();
if ('scheduled' != $action->getVerb()) {
return;
}
$production = $action->getComponent('indirectComplement')->getData();
$schedule = $action->getComponent('directComplement')->getData();
$event->setLink($this->url_generator->generate('bkstg_schedule_read', [
'id' => $schedule->getId(),
'production_slug' => $production->getSlug(),
]));
} | Set the link for scheduled actions.
@param TimelineLinkEvent $event The timeline action event.
@return void | https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Timeline/EventSubscriber/EventLinkSubscriber.php#L76-L90 |
ARCANESOFT/Auth | src/Http/Requests/Admin/Roles/UpdateRoleRequest.php | UpdateRoleRequest.rules | public function rules()
{
/** @var \Arcanesoft\Auth\Models\Role $role */
$role = $this->route('auth_role');
return array_merge(parent::rules(), [
'slug' => ['required', 'string', 'min:3', $this->getSlugRule()->ignore($role->id)],
]);
} | php | public function rules()
{
/** @var \Arcanesoft\Auth\Models\Role $role */
$role = $this->route('auth_role');
return array_merge(parent::rules(), [
'slug' => ['required', 'string', 'min:3', $this->getSlugRule()->ignore($role->id)],
]);
} | Get the validation rules that apply to the request.
@return array | https://github.com/ARCANESOFT/Auth/blob/b33ca82597a76b1e395071f71ae3e51f1ec67e62/src/Http/Requests/Admin/Roles/UpdateRoleRequest.php#L31-L39 |
siriusSupreme/sirius-event | src/Dispatcher.php | Dispatcher.makeListener | public function makeListener($listener, $wildcard = false)
{
if (is_string($listener)) {
return $this->createClassListener($listener, $wildcard);
}
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return $listener($event, $payload);
} else {
return $listener(...array_values($payload));
}
};
} | php | public function makeListener($listener, $wildcard = false)
{
if (is_string($listener)) {
return $this->createClassListener($listener, $wildcard);
}
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return $listener($event, $payload);
} else {
return $listener(...array_values($payload));
}
};
} | Register an event listener with the dispatcher.
@param \Closure|string $listener
@param bool $wildcard
@return \Closure | https://github.com/siriusSupreme/sirius-event/blob/f29c1c8799a7d6ffbff5410d972424e041c8fd90/src/Dispatcher.php#L340-L353 |
jmfeurprier/perf-caching | lib/perf/Caching/MemcachedStorage.php | MemcachedStorage.store | public function store(CacheEntry $entry)
{
if (null === $entry->expirationTimestamp()) {
$expirationTimestamp = 0; // Never expires.
} else {
$expirationTimestamp = $entry->expirationTimestamp();
}
if (!$this->getConnection()->set($entry->id(), $entry, $expirationTimestamp)) {
return $this->failure('Failed to store data into memcache server.');
}
} | php | public function store(CacheEntry $entry)
{
if (null === $entry->expirationTimestamp()) {
$expirationTimestamp = 0; // Never expires.
} else {
$expirationTimestamp = $entry->expirationTimestamp();
}
if (!$this->getConnection()->set($entry->id(), $entry, $expirationTimestamp)) {
return $this->failure('Failed to store data into memcache server.');
}
} | Attempts to store provided cache entry into storage.
@param CacheEntry $entry
@return void
@throws \RuntimeException | https://github.com/jmfeurprier/perf-caching/blob/16cf61dae3aa4d6dcb8722e14760934457087173/lib/perf/Caching/MemcachedStorage.php#L69-L80 |
teonsystems/php-base | src/Validator/DocumentContentRegex.php | DocumentContentRegex.isValid | public function isValid ($value)
{
if (!($value instanceof \Teon\Base\Text\Extractor\ExtractorInterface)) {
$this->error(self::INVALID);
return false;
}
$TextExtractor = $value;
// Store value - all ZF2 validators do it
$this->setValue($TextExtractor);
\Zend\Stdlib\ErrorHandler::start();
$status = preg_match($this->pattern, $TextExtractor->getText());
\Zend\Stdlib\ErrorHandler::stop();
if (false === $status) {
$this->error(self::ERROROUS);
return false;
}
if (!$status) {
$this->error(self::NOT_MATCH);
return false;
}
return true;
} | php | public function isValid ($value)
{
if (!($value instanceof \Teon\Base\Text\Extractor\ExtractorInterface)) {
$this->error(self::INVALID);
return false;
}
$TextExtractor = $value;
// Store value - all ZF2 validators do it
$this->setValue($TextExtractor);
\Zend\Stdlib\ErrorHandler::start();
$status = preg_match($this->pattern, $TextExtractor->getText());
\Zend\Stdlib\ErrorHandler::stop();
if (false === $status) {
$this->error(self::ERROROUS);
return false;
}
if (!$status) {
$this->error(self::NOT_MATCH);
return false;
}
return true;
} | Is value valid?
@param ... Value to verify
@return bool | https://github.com/teonsystems/php-base/blob/010418fd9df3c447a74b36cf0d31e2d38a6527ac/src/Validator/DocumentContentRegex.php#L45-L71 |
NukaCode/Front-End-Bootstrap | src/NukaCode/Bootstrap/Filesystem/Config/Theme.php | Theme.updateEntry | public function updateEntry($package, $theme)
{
$this->verifyCommand($package);
$lines = file($this->config);
$config = $this->compactConfig($package);
$lines = $this->updateConfigDetails($theme, $lines, $config);
$this->file->delete($this->config);
$this->file->put($this->config, implode($lines));
} | php | public function updateEntry($package, $theme)
{
$this->verifyCommand($package);
$lines = file($this->config);
$config = $this->compactConfig($package);
$lines = $this->updateConfigDetails($theme, $lines, $config);
$this->file->delete($this->config);
$this->file->put($this->config, implode($lines));
} | Update the config with the color values for easy retrieval
@param $package
@param $theme | https://github.com/NukaCode/Front-End-Bootstrap/blob/46c30fba4c77afb74ec4a4d70c43c9cffd464d6e/src/NukaCode/Bootstrap/Filesystem/Config/Theme.php#L85-L96 |
NukaCode/Front-End-Bootstrap | src/NukaCode/Bootstrap/Filesystem/Config/Theme.php | Theme.compactConfig | private function compactConfig($package)
{
$config = (include $this->config);
array_map(function ($detail, $key) use (&$config) {
return $config['colors'][$key] = $detail['hex'];
}, $package, array_keys($package));
return $config;
} | php | private function compactConfig($package)
{
$config = (include $this->config);
array_map(function ($detail, $key) use (&$config) {
return $config['colors'][$key] = $detail['hex'];
}, $package, array_keys($package));
return $config;
} | @param $package
@return mixed | https://github.com/NukaCode/Front-End-Bootstrap/blob/46c30fba4c77afb74ec4a4d70c43c9cffd464d6e/src/NukaCode/Bootstrap/Filesystem/Config/Theme.php#L103-L112 |
NukaCode/Front-End-Bootstrap | src/NukaCode/Bootstrap/Filesystem/Config/Theme.php | Theme.updateConfigDetails | private function updateConfigDetails($theme, $lines, $config)
{
$inColors = false;
$filledColors = false;
foreach ($lines as $key => $line) {
if (strpos($line, "'theme' =>") !== false) {
$lines[$key] = "\t'theme' => '$theme',";
continue;
}
if (strpos($line, "'colors'") !== false) {
$inColors = true;
continue;
}
if ($inColors == true && $filledColors == false) {
list($lines, $filledColors) = $this->replaceColors($config, $lines, $key);
continue;
} elseif ($inColors == true) {
if (strpos($line, ']') !== false) {
$inColors = false;
continue;
}
unset($lines[$key]);
}
}
return $lines;
} | php | private function updateConfigDetails($theme, $lines, $config)
{
$inColors = false;
$filledColors = false;
foreach ($lines as $key => $line) {
if (strpos($line, "'theme' =>") !== false) {
$lines[$key] = "\t'theme' => '$theme',";
continue;
}
if (strpos($line, "'colors'") !== false) {
$inColors = true;
continue;
}
if ($inColors == true && $filledColors == false) {
list($lines, $filledColors) = $this->replaceColors($config, $lines, $key);
continue;
} elseif ($inColors == true) {
if (strpos($line, ']') !== false) {
$inColors = false;
continue;
}
unset($lines[$key]);
}
}
return $lines;
} | @param $theme
@param $lines
@param $config
@return mixed | https://github.com/NukaCode/Front-End-Bootstrap/blob/46c30fba4c77afb74ec4a4d70c43c9cffd464d6e/src/NukaCode/Bootstrap/Filesystem/Config/Theme.php#L121-L149 |
NukaCode/Front-End-Bootstrap | src/NukaCode/Bootstrap/Filesystem/Config/Theme.php | Theme.replaceColors | private function replaceColors($config, $lines, $key)
{
$entry = [];
foreach ($config['colors'] as $name => $color) {
$entry[] = "\t\t'$name' => '$color',";
}
$lines[$key] = implode("\n", $entry) . "\n";
$filledColors = true;
return [$lines, $filledColors];
} | php | private function replaceColors($config, $lines, $key)
{
$entry = [];
foreach ($config['colors'] as $name => $color) {
$entry[] = "\t\t'$name' => '$color',";
}
$lines[$key] = implode("\n", $entry) . "\n";
$filledColors = true;
return [$lines, $filledColors];
} | @param $config
@param $lines
@param $key
@return array | https://github.com/NukaCode/Front-End-Bootstrap/blob/46c30fba4c77afb74ec4a4d70c43c9cffd464d6e/src/NukaCode/Bootstrap/Filesystem/Config/Theme.php#L158-L168 |
agentmedia/phine-core | src/Core/Logic/Tree/PageTreeProvider.php | PageTreeProvider.TopMost | public function TopMost()
{
$sql = Access::SqlBuilder();
$tbl = Page::Schema()->Table();
$where = $sql->Equals($tbl->Field('Site'), $sql->Value($this->site->GetID()))
->And_($sql->IsNull($tbl->Field('Parent')))
->And_($sql->IsNull($tbl->Field('Previous')));
return Page::Schema()->First($where);
} | php | public function TopMost()
{
$sql = Access::SqlBuilder();
$tbl = Page::Schema()->Table();
$where = $sql->Equals($tbl->Field('Site'), $sql->Value($this->site->GetID()))
->And_($sql->IsNull($tbl->Field('Parent')))
->And_($sql->IsNull($tbl->Field('Previous')));
return Page::Schema()->First($where);
} | Gets the first and root page of the site
@return Page | https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Tree/PageTreeProvider.php#L31-L40 |
Hnto/nuki | src/Handlers/Http/Session.php | Session.add | public function add($key, $value, $filter = FILTER_DEFAULT) {
if (empty($key)) {
throw new Base('Session key cannot be empty');
}
if (empty($value)) {
throw new Base('Session value cannot be empty');
}
$sessionValue = filter_var($value, $filter);
$_SESSION[$key] = $sessionValue;
} | php | public function add($key, $value, $filter = FILTER_DEFAULT) {
if (empty($key)) {
throw new Base('Session key cannot be empty');
}
if (empty($value)) {
throw new Base('Session value cannot be empty');
}
$sessionValue = filter_var($value, $filter);
$_SESSION[$key] = $sessionValue;
} | {@inheritdoc} | https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Http/Session.php#L28-L40 |
Hnto/nuki | src/Handlers/Http/Session.php | Session.get | public function get($key = false) {
if ($key === false) {
return $_SESSION;
}
if (!$this->has($key)) {
return null;
}
return $_SESSION[$key];
} | php | public function get($key = false) {
if ($key === false) {
return $_SESSION;
}
if (!$this->has($key)) {
return null;
}
return $_SESSION[$key];
} | {@inheritdoc} | https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Http/Session.php#L45-L55 |
christopher-evans/log | src/AggregateLog.php | AggregateLog.log | public function log(string $level, string $message, array $context = [], \DateTimeInterface $time = null)
{
if (null === $time) {
$time = new \DateTimeImmutable();
}
$exceptions = new Exception\AggregateException('Error writing to log target.');
foreach ($this->notifications as $notification) {
/** @var Notification $notification */
try {
$notification->send($level, $message, $context, $time);
} catch (\Exception $exception) {
$exceptions->addException($exception);
}
}
if ($exceptions->count()) {
throw $exceptions;
}
} | php | public function log(string $level, string $message, array $context = [], \DateTimeInterface $time = null)
{
if (null === $time) {
$time = new \DateTimeImmutable();
}
$exceptions = new Exception\AggregateException('Error writing to log target.');
foreach ($this->notifications as $notification) {
/** @var Notification $notification */
try {
$notification->send($level, $message, $context, $time);
} catch (\Exception $exception) {
$exceptions->addException($exception);
}
}
if ($exceptions->count()) {
throw $exceptions;
}
} | @brief Add a log entry with a time, level, message and context parameters.
@param string $level Log level.
@param string $message Log message.
@param array $context Context parameters.
@param \DateTimeInterface $time Log time.
@throws Exception\AggregateException If there was an error adding the entry to one of the targets. | https://github.com/christopher-evans/log/blob/d1098654bb12fb4442a0191351485bb602630a31/src/AggregateLog.php#L63-L82 |
bseddon/XPath20 | Value/NMTOKENSValue.php | NMTOKENSValue.Equals | public function Equals($obj)
{
if ( ! $obj instanceof NMTOKENSValue )
{
return false;
}
/**
* @var NMTOKENSValue $other
*/
$other = $obj;
if ( count( $other->ValueList ) != count( $this->ValueList ) ) return false;
// BMS 2018-03-21 This test is order independent but should be order dependent
// return count( array_diff( $other->ValueList, $this->ValueList ) ) == 0;
foreach ( $this->ValueList as $index => $token )
{
if ( $other->ValueList[ $index ] != $token ) return false;
}
return true;
} | php | public function Equals($obj)
{
if ( ! $obj instanceof NMTOKENSValue )
{
return false;
}
/**
* @var NMTOKENSValue $other
*/
$other = $obj;
if ( count( $other->ValueList ) != count( $this->ValueList ) ) return false;
// BMS 2018-03-21 This test is order independent but should be order dependent
// return count( array_diff( $other->ValueList, $this->ValueList ) ) == 0;
foreach ( $this->ValueList as $index => $token )
{
if ( $other->ValueList[ $index ] != $token ) return false;
}
return true;
} | Equals
@param object $obj
@return bool | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/NMTOKENSValue.php#L87-L106 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.connect | public function connect($credentials = [])
{
if ($diff = array_diff(array_keys($this->settings), array_keys($credentials))) {
throw new \Exception("Missing credentials, the following fields are missing ".implode('/', $diff));
}
$this->settings = array_merge($this->settings, $credentials);
if (isset($this->settings['port']) === false) {
$this->settings['port'] = 143;
}
$this->conn = @imap_open('{'.$this->settings['server'].':'.$this->settings['port'].'/notls}',
$this->settings['username'], $this->settings['password']);
if ($this->conn == false) {
throw new \Exception("Could not connect or authorize to ".$this->settings['server'].':'.$this->settings['port']);
}
return ($this->conn != null);
} | php | public function connect($credentials = [])
{
if ($diff = array_diff(array_keys($this->settings), array_keys($credentials))) {
throw new \Exception("Missing credentials, the following fields are missing ".implode('/', $diff));
}
$this->settings = array_merge($this->settings, $credentials);
if (isset($this->settings['port']) === false) {
$this->settings['port'] = 143;
}
$this->conn = @imap_open('{'.$this->settings['server'].':'.$this->settings['port'].'/notls}',
$this->settings['username'], $this->settings['password']);
if ($this->conn == false) {
throw new \Exception("Could not connect or authorize to ".$this->settings['server'].':'.$this->settings['port']);
}
return ($this->conn != null);
} | Open a connection to a mail server.
@param array $credentials
@return bool
@throws \Exception | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L47-L67 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.setMailbox | public function setMailbox($mailbox = 'INBOX')
{
if ($mailbox == 'INBOX') {
$mailbox = "{".$this->settings['server']."}INBOX";
} else {
$mailbox = "{".$this->settings['server']."}INBOX.".imap_utf7_encode($mailbox);
}
$result = false;
if ($this->conn) {
$result = imap_reopen($this->conn, $mailbox);
$this->mailbox = $mailbox;
}
return $result;
} | php | public function setMailbox($mailbox = 'INBOX')
{
if ($mailbox == 'INBOX') {
$mailbox = "{".$this->settings['server']."}INBOX";
} else {
$mailbox = "{".$this->settings['server']."}INBOX.".imap_utf7_encode($mailbox);
}
$result = false;
if ($this->conn) {
$result = imap_reopen($this->conn, $mailbox);
$this->mailbox = $mailbox;
}
return $result;
} | @param string $mailbox
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L86-L103 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.getMailbox | public function getMailbox()
{
$mailbox = str_replace("{".$this->settings['server']."}", '', $this->mailbox);
$mailbox = (substr($mailbox, 0, 6) == 'INBOX.') ? substr($mailbox, -6) : $mailbox;
return $mailbox;
} | php | public function getMailbox()
{
$mailbox = str_replace("{".$this->settings['server']."}", '', $this->mailbox);
$mailbox = (substr($mailbox, 0, 6) == 'INBOX.') ? substr($mailbox, -6) : $mailbox;
return $mailbox;
} | Return the name of the current mailbox.
@return string | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L111-L117 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.filterUnReadMessagesTo | public function filterUnReadMessagesTo($to = '')
{
$filteredResult = $this->filterTo($to);
$filteredMessages = [];
if (is_array($filteredResult) && count($filteredResult) > 0) {
foreach ($filteredResult as $message) {
if (isset($message['header'])) {
$header = $message['header'];
if ($header->Unseen == 'U') {
$filteredMessages[] = $message;
}
}
}
}
return $filteredMessages;
} | php | public function filterUnReadMessagesTo($to = '')
{
$filteredResult = $this->filterTo($to);
$filteredMessages = [];
if (is_array($filteredResult) && count($filteredResult) > 0) {
foreach ($filteredResult as $message) {
if (isset($message['header'])) {
$header = $message['header'];
if ($header->Unseen == 'U') {
$filteredMessages[] = $message;
}
}
}
}
return $filteredMessages;
} | Filter unread message sent to $to
@param string $to
@return array | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L140-L157 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.filterTo | public function filterTo($to = '')
{
$msg_cnt = imap_num_msg($this->conn);
if ($msg_cnt > 0 && count($this->messages) == 0) {
$this->readMailbox();
}
$filteredResult = imap_search($this->conn, 'TO "'.$to.'"');
$filteredMessages = [];
if (is_array($filteredResult) && count($filteredResult) > 0) {
foreach ($filteredResult as $index) {
$filteredMessages[] = $this->getMessageInformation($index);
}
}
return $filteredMessages;
} | php | public function filterTo($to = '')
{
$msg_cnt = imap_num_msg($this->conn);
if ($msg_cnt > 0 && count($this->messages) == 0) {
$this->readMailbox();
}
$filteredResult = imap_search($this->conn, 'TO "'.$to.'"');
$filteredMessages = [];
if (is_array($filteredResult) && count($filteredResult) > 0) {
foreach ($filteredResult as $index) {
$filteredMessages[] = $this->getMessageInformation($index);
}
}
return $filteredMessages;
} | Filter message sent to $to
@param string $to
@return array | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L167-L184 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.createMailbox | public function createMailbox($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_createmailbox($this->conn, "{".$this->settings['server']."}INBOX.".$name);
} | php | public function createMailbox($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_createmailbox($this->conn, "{".$this->settings['server']."}INBOX.".$name);
} | Create a mailbox (folder)
@param string $name
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L194-L203 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.subscribeMailbox | public function subscribeMailbox($name = '') {
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_subscribe ( $this->conn, "{".$this->settings['server']."}INBOX.".$name );
} | php | public function subscribeMailbox($name = '') {
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_subscribe ( $this->conn, "{".$this->settings['server']."}INBOX.".$name );
} | Subscribe to a mailbox.
@param string $name
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L213-L220 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.deleteMailbox | public function deleteMailbox($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_deletemailbox($this->conn, "{".$this->settings['server']."}INBOX.".$name);
} | php | public function deleteMailbox($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
return imap_deletemailbox($this->conn, "{".$this->settings['server']."}INBOX.".$name);
} | Delete a mailbox (folder)
@param string $name
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L245-L254 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.mailboxExists | public function mailboxExists($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
$prefixedName = "{".$this->settings['server']."}INBOX.".$name;
$mailboxes = imap_list($this->conn, "{".$this->settings['server']."}", "*");
return in_array($prefixedName, $mailboxes);
} | php | public function mailboxExists($name = '')
{
if (empty($name)) {
return false;
}
$name = imap_utf7_encode($name);
$prefixedName = "{".$this->settings['server']."}INBOX.".$name;
$mailboxes = imap_list($this->conn, "{".$this->settings['server']."}", "*");
return in_array($prefixedName, $mailboxes);
} | Check to see if a given mailbox (folder) exists on the server.
@param string $name
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L266-L277 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.getPrettyMailboxes | public function getPrettyMailboxes()
{
$mailboxes = $this->getMailboxes();
$result = [];
if (is_array($mailboxes) && count($mailboxes) > 0) {
$prefixedMailbox = "INBOX.";
foreach ($mailboxes as $mailbox) {
// Remove the server prefix
$mailbox = str_replace('{'.$this->settings['server'].'}', '', $mailbox);
// Remove the INBOX. prefix (if present)
$mailbox = str_replace($prefixedMailbox, '', $mailbox);
$result[] = $mailbox;
}
}
return $result;
} | php | public function getPrettyMailboxes()
{
$mailboxes = $this->getMailboxes();
$result = [];
if (is_array($mailboxes) && count($mailboxes) > 0) {
$prefixedMailbox = "INBOX.";
foreach ($mailboxes as $mailbox) {
// Remove the server prefix
$mailbox = str_replace('{'.$this->settings['server'].'}', '', $mailbox);
// Remove the INBOX. prefix (if present)
$mailbox = str_replace($prefixedMailbox, '', $mailbox);
$result[] = $mailbox;
}
}
return $result;
} | Return all mailboxes (folders) on the server. This function removes the
mailbox prefixes like {server}INBOX.<name here>
@return array | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L297-L315 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.renameMailbox | public function renameMailbox($from = '', $to = '')
{
if (empty($from) || empty($to)) {
return false;
}
$from = imap_utf7_encode($from);
$to = imap_utf7_encode($to);
return imap_renamemailbox($this->conn, "{".$this->settings['server']."}INBOX.".$from,
"{".$this->settings['server']."}INBOX.".$to);
} | php | public function renameMailbox($from = '', $to = '')
{
if (empty($from) || empty($to)) {
return false;
}
$from = imap_utf7_encode($from);
$to = imap_utf7_encode($to);
return imap_renamemailbox($this->conn, "{".$this->settings['server']."}INBOX.".$from,
"{".$this->settings['server']."}INBOX.".$to);
} | Rename a mailbox (folder)
@param string $from
@param string $to
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L326-L337 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.moveMessage | public function moveMessage($index = -1, $to = '')
{
if (empty($to)) {
return false;
}
$msgId = 0;
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $index) {
$msgId = $msg['index'];
break;
}
}
}
if ($msgId >= 0) {
$to = imap_utf7_encode($to);
imap_mail_move($this->conn, $msgId, "INBOX.".$to);
imap_expunge($this->conn);
}
return false;
} | php | public function moveMessage($index = -1, $to = '')
{
if (empty($to)) {
return false;
}
$msgId = 0;
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $index) {
$msgId = $msg['index'];
break;
}
}
}
if ($msgId >= 0) {
$to = imap_utf7_encode($to);
imap_mail_move($this->conn, $msgId, "INBOX.".$to);
imap_expunge($this->conn);
}
return false;
} | Move a given message at $index to a given mailbox (folder).
@param int $index
@param string $to
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L348-L374 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.deleteMessage | public function deleteMessage($index = -1)
{
if ($index == -1) {
return false;
}
$result = imap_delete($this->conn, $index);
if ($result) {
// Real delete emails marked as deleted
imap_expunge($this->conn);
}
return $result;
} | php | public function deleteMessage($index = -1)
{
if ($index == -1) {
return false;
}
$result = imap_delete($this->conn, $index);
if ($result) {
// Real delete emails marked as deleted
imap_expunge($this->conn);
}
return $result;
} | Delete a given email message. The param $index
is bases of the [index] field on an email array.
@param int $index
@return bool | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L386-L398 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.getMessageInformation | public function getMessageInformation($id = '')
{
$message = [];
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $id) {
return $msg;
}
}
}
return $message;
} | php | public function getMessageInformation($id = '')
{
$message = [];
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $id) {
return $msg;
}
}
}
return $message;
} | Return message information without reading it from the server
@param string $id
@return mixed | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L408-L419 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.getMessage | public function getMessage($id = '')
{
$message = [];
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $id) {
$message = $msg;
break;
}
}
}
if (is_array($message) === true) {
// Get the message body but do not mark as read
$message['body'] = quoted_printable_decode(imap_fetchbody($this->conn, $message['index'], FT_PEEK));
}
return $message;
} | php | public function getMessage($id = '')
{
$message = [];
if (is_array($this->messages) == true) {
foreach($this ->messages as $msg) {
if ($msg['index'] == $id) {
$message = $msg;
break;
}
}
}
if (is_array($message) === true) {
// Get the message body but do not mark as read
$message['body'] = quoted_printable_decode(imap_fetchbody($this->conn, $message['index'], FT_PEEK));
}
return $message;
} | Return a message based on its index in the mailbox.
@param string $id
@return mixed | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L428-L446 |
johnnymast/mailreader | src/MailReader/MailReader.php | MailReader.readMailbox | public function readMailbox()
{
$msg_cnt = imap_num_msg($this->conn);
$messages = [];
for ($i = 1; $i <= $msg_cnt; $i++) {
$header = imap_headerinfo($this->conn, $i);
$messages[] = [
'index' => trim($header->Msgno),
'header' => $header,
'structure' => imap_fetchstructure($this->conn, $i)
];
}
$this->messages = $messages;
return $this->messages;
} | php | public function readMailbox()
{
$msg_cnt = imap_num_msg($this->conn);
$messages = [];
for ($i = 1; $i <= $msg_cnt; $i++) {
$header = imap_headerinfo($this->conn, $i);
$messages[] = [
'index' => trim($header->Msgno),
'header' => $header,
'structure' => imap_fetchstructure($this->conn, $i)
];
}
$this->messages = $messages;
return $this->messages;
} | Retrieve a list of message in the mailbox.
@return array | https://github.com/johnnymast/mailreader/blob/9c81843aece984eb6e2a9ba41f3be49733348d10/src/MailReader/MailReader.php#L454-L469 |
Wedeto/DB | src/Migrate/Module.php | Module.loadVersion | private function loadVersion()
{
try
{
$this->dao = $this->db->getDAO(DBVersion::class);
$this->db_version =
$this->dao->get(
QB::where(["module" => $this->module]),
QB::order(['migration_date' => 'DESC'])
)
?: new NullVersion;
}
catch (TableNotExistsException $e)
{
if ($this->module !== "wedeto.db")
{
throw new NoMigrationTableException();
}
$this->db_version = new NullVersion;
}
} | php | private function loadVersion()
{
try
{
$this->dao = $this->db->getDAO(DBVersion::class);
$this->db_version =
$this->dao->get(
QB::where(["module" => $this->module]),
QB::order(['migration_date' => 'DESC'])
)
?: new NullVersion;
}
catch (TableNotExistsException $e)
{
if ($this->module !== "wedeto.db")
{
throw new NoMigrationTableException();
}
$this->db_version = new NullVersion;
}
} | Load the current version from the database | https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Migrate/Module.php#L88-L108 |
Wedeto/DB | src/Migrate/Module.php | Module.scanMigrations | protected function scanMigrations()
{
$glob = rtrim($this->migration_path, '/') . '/*-to-*.[sp][qh][lp]';
$it = new \GlobIterator($glob, \FilesystemIterator::NEW_CURRENT_AND_KEY);
$regex = '/^([0-9]+)-to-([0-9]+)\.(sql|php)$/';
$this->migrations = [];
$this->max_version = 0;
foreach ($it as $filename => $pathinfo)
{
if (!$pathinfo->isFile())
continue;
if (preg_match($regex, $filename, $matches) === 1)
{
$from_version = (int)$matches[1];
$to_version = (int)$matches[2];
if ($to_version > $this->max_version)
$this->max_version = $to_version;
$path = $pathinfo->getPathname();
$this->migrations[$from_version][$to_version] = $path;
}
}
// Sort the migrations ascending on their target versions per source version
foreach ($this->migrations as $from => &$to)
ksort($to);
// Sort the migrations on their source version
ksort($this->migrations);
} | php | protected function scanMigrations()
{
$glob = rtrim($this->migration_path, '/') . '/*-to-*.[sp][qh][lp]';
$it = new \GlobIterator($glob, \FilesystemIterator::NEW_CURRENT_AND_KEY);
$regex = '/^([0-9]+)-to-([0-9]+)\.(sql|php)$/';
$this->migrations = [];
$this->max_version = 0;
foreach ($it as $filename => $pathinfo)
{
if (!$pathinfo->isFile())
continue;
if (preg_match($regex, $filename, $matches) === 1)
{
$from_version = (int)$matches[1];
$to_version = (int)$matches[2];
if ($to_version > $this->max_version)
$this->max_version = $to_version;
$path = $pathinfo->getPathname();
$this->migrations[$from_version][$to_version] = $path;
}
}
// Sort the migrations ascending on their target versions per source version
foreach ($this->migrations as $from => &$to)
ksort($to);
// Sort the migrations on their source version
ksort($this->migrations);
} | Scan the path to find all available migrations. File should be named
according to the pattern:
SOURCE-to-TARGET.(php|sql)
Migration files should be SQL for simple structure changes that can be
applied automatically. In cases where data needs to migrate from one
or several columns/tables to another, a PHP file can be used instead.
The PHP file will be included, with a variable called $db available that
should be used to perform the migrations.
NOTE: Migrations should always happen in SQL, not using objects, as
these objects may change later on. The DB\Schema utilities can be used
to generate these queries. | https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Migrate/Module.php#L182-L216 |
Wedeto/DB | src/Migrate/Module.php | Module.migrateTo | public function migrateTo(int $target_version)
{
if ($this->max_version === null)
$this->scanMigrations();
$current_version = $this->getCurrentVersion();
$trajectory = $this->plan($current_version, $target_version);
$db = $this->db;
foreach ($trajectory as $migration)
{
$migration['module'] = $this->module;
$filename = $migration['file'];
$ext = strtolower(substr($filename, -4));
$db->beginTransaction();
try
{
static::$logger->info("Migrating module {module} from {from} to {to} using file {file}", $migration);
if ($ext === ".php")
{
executePHP($db, $filename);
}
elseif ($ext === ".sql")
{
$db->executeSQL($filename);
}
// If no exceptions were thrown, we're going to assume that the
// upgrade succeeded, so update the version number in the
// database and commit the changes.
// Clear the database schema cache
$db->clearCache();
$this->dao = $this->db->getDAO(DBVersion::class);
$version = new DBVersion;
$version->module = $this->module;
$version->from_version = (int)$migration['from'];
$version->to_version = (int)$migration['to'];
$version->migration_date = new \DateTime();
$version->filename = $filename;
$version->md5sum = md5(file_get_contents($filename));
$this->dao->save($version);
static::$logger->info("Succesfully migrated module {module} from {from} to {to} using file {file}", $migration);
$db->commit();
}
catch (\Exception $e)
{
// Upgrade failed, roll back to previous state
static::$logger->error("Migration of module {module} from {from} to {to} using file {file}", $migration);
static::$logger->error("Exception: {0}", [$e]);
$db->rollback();
throw $e;
}
}
} | php | public function migrateTo(int $target_version)
{
if ($this->max_version === null)
$this->scanMigrations();
$current_version = $this->getCurrentVersion();
$trajectory = $this->plan($current_version, $target_version);
$db = $this->db;
foreach ($trajectory as $migration)
{
$migration['module'] = $this->module;
$filename = $migration['file'];
$ext = strtolower(substr($filename, -4));
$db->beginTransaction();
try
{
static::$logger->info("Migrating module {module} from {from} to {to} using file {file}", $migration);
if ($ext === ".php")
{
executePHP($db, $filename);
}
elseif ($ext === ".sql")
{
$db->executeSQL($filename);
}
// If no exceptions were thrown, we're going to assume that the
// upgrade succeeded, so update the version number in the
// database and commit the changes.
// Clear the database schema cache
$db->clearCache();
$this->dao = $this->db->getDAO(DBVersion::class);
$version = new DBVersion;
$version->module = $this->module;
$version->from_version = (int)$migration['from'];
$version->to_version = (int)$migration['to'];
$version->migration_date = new \DateTime();
$version->filename = $filename;
$version->md5sum = md5(file_get_contents($filename));
$this->dao->save($version);
static::$logger->info("Succesfully migrated module {module} from {from} to {to} using file {file}", $migration);
$db->commit();
}
catch (\Exception $e)
{
// Upgrade failed, roll back to previous state
static::$logger->error("Migration of module {module} from {from} to {to} using file {file}", $migration);
static::$logger->error("Exception: {0}", [$e]);
$db->rollback();
throw $e;
}
}
} | Perform a migration from the current version to the target version
@param int $version The target version
@throws MigrationException Whenever no migration path can be found to the target version
@throws DBException When something goes wrong during the migration | https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Migrate/Module.php#L242-L301 |
Wedeto/DB | src/Migrate/Module.php | Module.plan | protected function plan(int $from, int $to)
{
$migrations = [];
if ($from === $to)
return $migrations;
$is_downgrade = $to < $from;
$reachable = $this->migrations[$from] ?? [];
// For downgrades, we want the lowest reachable target that is above or equal to the final target
// For upgrades, we want the highest reachable target that is below or equal to the final target
// To always use the first encountered, the array needs to be reversed for upgrades, as it's sorted by key
if (!$is_downgrade)
$reachable = array_reverse($reachable, true);
// Traverse the reachable migrations
foreach ($reachable as $direct_to => $path)
{
if (
($direct_to === $to) || // Bingo
($is_downgrade && $direct_to > $to) || // Proper downgrade
(!$is_downgrade && $direct_to < $to) // Proper upgrade
)
{
// In the right direction, so add to the path
$migrations[] = ['from' => $from, 'to' => $direct_to, 'file' => $path];
break;
}
}
if (count($migrations) === 0)
throw new MigrationException("No migration path from version $from to $to for module {$this->module}");
$last = end($migrations);
if ($last['to'] !== $to)
{
$rest = $this->plan($last['to'], $to);
foreach ($rest as $migration)
$migrations[] = $migration;
}
return $migrations;
} | php | protected function plan(int $from, int $to)
{
$migrations = [];
if ($from === $to)
return $migrations;
$is_downgrade = $to < $from;
$reachable = $this->migrations[$from] ?? [];
// For downgrades, we want the lowest reachable target that is above or equal to the final target
// For upgrades, we want the highest reachable target that is below or equal to the final target
// To always use the first encountered, the array needs to be reversed for upgrades, as it's sorted by key
if (!$is_downgrade)
$reachable = array_reverse($reachable, true);
// Traverse the reachable migrations
foreach ($reachable as $direct_to => $path)
{
if (
($direct_to === $to) || // Bingo
($is_downgrade && $direct_to > $to) || // Proper downgrade
(!$is_downgrade && $direct_to < $to) // Proper upgrade
)
{
// In the right direction, so add to the path
$migrations[] = ['from' => $from, 'to' => $direct_to, 'file' => $path];
break;
}
}
if (count($migrations) === 0)
throw new MigrationException("No migration path from version $from to $to for module {$this->module}");
$last = end($migrations);
if ($last['to'] !== $to)
{
$rest = $this->plan($last['to'], $to);
foreach ($rest as $migration)
$migrations[] = $migration;
}
return $migrations;
} | Plan a path through available migrations to reach a specified version
from another version. This is always done in one direction,
opportunistically. This means that when downgrading, no intermediate
upgrades are performed, even if they may result in shorter path.
Whenever a more than one step is available, the larger one is selected.
Potentially, this could result in sinks with no way out. Design your
upgrade trajectories with this in mind.
@param $from The source version to start planning from
@param $to The target version to plan towards
@return array The list of migrations to execute. When $from and $to are equal,
an empty array is returned.
@throws MigrationException When no migration path can be found | https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Migrate/Module.php#L320-L363 |
chalasr/RCHCapistranoBundle | Generator/AbstractGenerator.php | AbstractGenerator.open | public function open()
{
if (!is_dir($directory = dirname($this->path))) {
try {
mkdir($directory, 0777);
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Unable to create directory "%s". Please change the permissions or create the directory manually.', $directory));
}
}
if (file_exists($this->path)) {
unlink($this->path);
}
$this->file = fopen($this->path, 'w');
} | php | public function open()
{
if (!is_dir($directory = dirname($this->path))) {
try {
mkdir($directory, 0777);
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Unable to create directory "%s". Please change the permissions or create the directory manually.', $directory));
}
}
if (file_exists($this->path)) {
unlink($this->path);
}
$this->file = fopen($this->path, 'w');
} | {@inheritdoc} | https://github.com/chalasr/RCHCapistranoBundle/blob/c4a4cbaa2bc05f33bf431fd3afe6cac39947640e/Generator/AbstractGenerator.php#L70-L85 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.getAbstractNode | public function getAbstractNode( $index )
{
if ( ! isset( $this->_childs[ $index ] ) )
throw new IndexOutOfRangeException();
return $this->_childs[ $index ];
} | php | public function getAbstractNode( $index )
{
if ( ! isset( $this->_childs[ $index ] ) )
throw new IndexOutOfRangeException();
return $this->_childs[ $index ];
} | getAbstractNode
@param int $index
@throws IndexOutOfRangeException
@return AbstractNode | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L148-L153 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.setAbstractNode | public function setAbstractNode( $index, $node )
{
if ( is_null( $this->_childs ) )
{
throw new IndexOutOfRangeException();
}
$this->_childs[ $index ] = $node;
} | php | public function setAbstractNode( $index, $node )
{
if ( is_null( $this->_childs ) )
{
throw new IndexOutOfRangeException();
}
$this->_childs[ $index ] = $node;
} | setAbstractNode
@param int $index
@param AbstractNode $node
@throws IndexOutOfRangeException | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L161-L169 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.Add | public function Add( $node )
{
if ( ! $node instanceof AbstractNode )
{
$node = $this->Create( $this->_context, $node );
}
if ( ! is_null( $node->getParent() ) )
{
throw new ArgumentException( "\$node" );
}
$node->setParent( $this );
if ( is_null( $this->_childs ) )
{
$this->_childs = array(); // new List<AbstractNode>();
}
$this->_childs[] = $node;
} | php | public function Add( $node )
{
if ( ! $node instanceof AbstractNode )
{
$node = $this->Create( $this->_context, $node );
}
if ( ! is_null( $node->getParent() ) )
{
throw new ArgumentException( "\$node" );
}
$node->setParent( $this );
if ( is_null( $this->_childs ) )
{
$this->_childs = array(); // new List<AbstractNode>();
}
$this->_childs[] = $node;
} | Add a node
@param AbstractNode|object $node
@return void | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L176-L196 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.Bind | public function Bind()
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node)
{
$node->Bind();
}
}
} | php | public function Bind()
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node)
{
$node->Bind();
}
}
} | Bind
@return void | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L215-L224 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.Create | public static function Create( $context, $value )
{
if ( $value instanceof PathStep )
{
return new PathExprNode( $context, $value );
}
if ( $value instanceof AbstractNode )
{
return $value;
}
return new ValueNode( $context, $value );
} | php | public static function Create( $context, $value )
{
if ( $value instanceof PathStep )
{
return new PathExprNode( $context, $value );
}
if ( $value instanceof AbstractNode )
{
return $value;
}
return new ValueNode( $context, $value );
} | Create
@param XPath2Context $context
@param object $value
@return AbstractNode | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L232-L245 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.TraverseSubtree | public function TraverseSubtree( $action )
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node )
{
$action( $node );
$node->TraverseSubtree( $action );
}
}
} | php | public function TraverseSubtree( $action )
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node )
{
$action( $node );
$node->TraverseSubtree( $action );
}
}
} | TraverseSubtree
@param Function $action
@return void | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L252-L262 |
bseddon/XPath20 | AST/AbstractNode.php | AbstractNode.IsContextSensitive | public function IsContextSensitive()
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node )
{
if ( $node->IsContextSensitive() )
{
return true;
}
}
}
return false;
} | php | public function IsContextSensitive()
{
if ( ! is_null( $this->_childs ) )
{
foreach ( $this->_childs as $node )
{
if ( $node->IsContextSensitive() )
{
return true;
}
}
}
return false;
} | IsContextSensitive
@return bool | https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/AST/AbstractNode.php#L268-L282 |
DeimosProject/Request | src/Request/AdapterExtension.php | AdapterExtension.unsafeFilter | private function unsafeFilter($call, $arguments)
{
$arguments[1] = isset($arguments[1]) ? $arguments[1] : null;
$arguments[2] = false;
return call_user_func_array([$this, $call], $arguments);
} | php | private function unsafeFilter($call, $arguments)
{
$arguments[1] = isset($arguments[1]) ? $arguments[1] : null;
$arguments[2] = false;
return call_user_func_array([$this, $call], $arguments);
} | @param $call
@param $arguments
@return mixed | https://github.com/DeimosProject/Request/blob/3e45af0fdbfc3c47c27de27a98e8980ba42c3737/src/Request/AdapterExtension.php#L60-L66 |
DeimosProject/Request | src/Request/AdapterExtension.php | AdapterExtension.betweenFilter | private function betweenFilter($call, $arguments)
{
$num = $this->unsafeFilter($call, $arguments);
return max(min($arguments[2], $num), $arguments[1]);
} | php | private function betweenFilter($call, $arguments)
{
$num = $this->unsafeFilter($call, $arguments);
return max(min($arguments[2], $num), $arguments[1]);
} | @param $call
@param $arguments
@return mixed | https://github.com/DeimosProject/Request/blob/3e45af0fdbfc3c47c27de27a98e8980ba42c3737/src/Request/AdapterExtension.php#L74-L79 |
DeimosProject/Request | src/Request/AdapterExtension.php | AdapterExtension.parameterInit | private function parameterInit($name)
{
$parameters = preg_replace('~([A-Z])~', '_$1', $name, 1);
$parameters = $this->normalizeLow($parameters);
return explode('_', $parameters);
} | php | private function parameterInit($name)
{
$parameters = preg_replace('~([A-Z])~', '_$1', $name, 1);
$parameters = $this->normalizeLow($parameters);
return explode('_', $parameters);
} | @param $name
@return array | https://github.com/DeimosProject/Request/blob/3e45af0fdbfc3c47c27de27a98e8980ba42c3737/src/Request/AdapterExtension.php#L86-L92 |
ZendExperts/phpids | lib/IDS/Caching/Factory.php | IDS_Caching.factory | public static function factory($init, $type)
{
$object = false;
$wrapper = preg_replace(
'/\W+/m',
null,
ucfirst($init->config['Caching']['caching'])
);
$class = 'IDS_Caching_' . $wrapper;
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR .
$wrapper . '.php';
if (file_exists($path)) {
include_once $path;
if (class_exists($class)) {
$object = call_user_func(array($class, 'getInstance'),
$type, $init);
}
}
return $object;
} | php | public static function factory($init, $type)
{
$object = false;
$wrapper = preg_replace(
'/\W+/m',
null,
ucfirst($init->config['Caching']['caching'])
);
$class = 'IDS_Caching_' . $wrapper;
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR .
$wrapper . '.php';
if (file_exists($path)) {
include_once $path;
if (class_exists($class)) {
$object = call_user_func(array($class, 'getInstance'),
$type, $init);
}
}
return $object;
} | Factory method
@param object $init the IDS_Init object
@param string $type the caching type
@return object the caching facility | https://github.com/ZendExperts/phpids/blob/f30df04eea47b94d056e2ae9ec8fea1c626f1c03/lib/IDS/Caching/Factory.php#L62-L85 |
yaapi/coding-standards | YaAPI/Sniffs/Commenting/FunctionCommentSniff.php | YaAPI_Sniffs_Commenting_FunctionCommentSniff.processParams | protected function processParams(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
$params = [];
$maxType = 0;
$maxVar = 0;
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag)
{
if ($tokens[$tag]['content'] !== '@param')
{
continue;
}
$type = '';
$typeSpace = 0;
$var = '';
$varSpace = 0;
$comment = '';
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING)
{
$matches = [];
preg_match('/([^$&]+)(?:((?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches);
$typeLen = strlen($matches[1]);
$type = trim($matches[1]);
$typeSpace = ($typeLen - strlen($type));
$typeLen = strlen($type);
if ($typeLen > $maxType)
{
$maxType = $typeLen;
}
if (isset($matches[2]) === true)
{
$var = $matches[2];
$varLen = strlen($var);
if ($varLen > $maxVar)
{
$maxVar = $varLen;
}
if (isset($matches[4]) === true)
{
$varSpace = strlen($matches[3]);
$comment = $matches[4];
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true)
{
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
}
else
{
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++)
{
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING)
{
$comment .= ' ' . $tokens[$i]['content'];
}
}
}
else
{
$error = 'Missing parameter comment';
$phpcsFile->addError($error, $tag, 'MissingParamComment');
}
}
else
{
$error = 'Missing parameter name';
$phpcsFile->addError($error, $tag, 'MissingParamName');
}
}
else
{
$error = 'Missing parameter type';
$phpcsFile->addError($error, $tag, 'MissingParamType');
}
$params[] = [
'tag' => $tag,
'type' => $type,
'var' => $var,
'comment' => $comment,
'type_space' => $typeSpace,
'var_space' => $varSpace,
'align_space' => $tokens[($tag + 1)]['content'],
];
}
$realParams = $phpcsFile->getMethodParameters($stackPtr);
$foundParams = [];
$previousParam = null;
foreach ($params as $pos => $param)
{
if ($param['var'] === '')
{
continue;
}
$foundParams[] = $param['var'];
// YaAPI change: There must be 3 spaces after the @param tag to make it line up with the @return tag
if ($param['align_space'] !== ' ')
{
$error = 'Expected 3 spaces before variable type, found %s';
$spaces = strlen($param['align_space']);
$data = [$spaces];
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'BeforeParamType', $data);
if ($fix === true)
{
$phpcsFile->fixer->beginChangeset();
for ($i = 0; $i < $spaces; $i++)
{
$phpcsFile->fixer->replaceToken(($param['tag'] + 1), '');
}
$phpcsFile->fixer->addContent($param['tag'], ' ');
$phpcsFile->fixer->endChangeset();
}
}
// Make sure the param name is correct.
if (isset($realParams[$pos]) === true)
{
$realName = $realParams[$pos]['name'];
if ($realName !== $param['var'])
{
$code = 'ParamNameNoMatch';
$data = [
$param['var'],
$realName,
];
$error = 'Doc comment for parameter %s does not match ';
if (strtolower($param['var']) === strtolower($realName))
{
$error .= 'case of ';
$code = 'ParamNameNoCaseMatch';
}
$error .= 'actual variable name %s';
$phpcsFile->addError($error, $param['tag'], $code, $data);
}
}
elseif (substr($param['var'], -4) !== ',...')
{
// We must have an extra parameter comment.
$error = 'Superfluous parameter comment';
$phpcsFile->addError($error, $param['tag'], 'ExtraParamComment');
}
if ($param['comment'] === '')
{
continue;
}
// YaAPI change: Enforces alignment of the param variables and comments
if ($previousParam !== null)
{
$previousName = ($previousParam['var'] !== '') ? $previousParam['var'] : 'UNKNOWN';
// Check to see if the parameters align properly.
if (!$this->paramVarsAlign($param, $previousParam))
{
$error = 'The variable names for parameters %s and %s do not align';
$data = [
$previousName,
$param['var'],
];
$phpcsFile->addError($error, $param['tag'], 'ParameterNamesNotAligned', $data);
}
// Check to see if the comments align properly.
if (!$this->paramCommentsAlign($param, $previousParam))
{
$error = 'The comments for parameters %s and %s do not align';
$data = [
$previousName,
$param['var'],
];
$phpcsFile->addError($error, $param['tag'], 'ParameterCommentsNotAligned', $data);
}
}
$previousParam = $param;
}
$realNames = [];
foreach ($realParams as $realParam)
{
$realNames[] = $realParam['name'];
}
// Report missing comments.
$diff = array_diff($realNames, $foundParams);
foreach ($diff as $neededParam)
{
$error = 'Doc comment for parameter "%s" missing';
$data = [$neededParam];
$phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data);
}
} | php | protected function processParams(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
$params = [];
$maxType = 0;
$maxVar = 0;
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag)
{
if ($tokens[$tag]['content'] !== '@param')
{
continue;
}
$type = '';
$typeSpace = 0;
$var = '';
$varSpace = 0;
$comment = '';
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING)
{
$matches = [];
preg_match('/([^$&]+)(?:((?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches);
$typeLen = strlen($matches[1]);
$type = trim($matches[1]);
$typeSpace = ($typeLen - strlen($type));
$typeLen = strlen($type);
if ($typeLen > $maxType)
{
$maxType = $typeLen;
}
if (isset($matches[2]) === true)
{
$var = $matches[2];
$varLen = strlen($var);
if ($varLen > $maxVar)
{
$maxVar = $varLen;
}
if (isset($matches[4]) === true)
{
$varSpace = strlen($matches[3]);
$comment = $matches[4];
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true)
{
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
}
else
{
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++)
{
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING)
{
$comment .= ' ' . $tokens[$i]['content'];
}
}
}
else
{
$error = 'Missing parameter comment';
$phpcsFile->addError($error, $tag, 'MissingParamComment');
}
}
else
{
$error = 'Missing parameter name';
$phpcsFile->addError($error, $tag, 'MissingParamName');
}
}
else
{
$error = 'Missing parameter type';
$phpcsFile->addError($error, $tag, 'MissingParamType');
}
$params[] = [
'tag' => $tag,
'type' => $type,
'var' => $var,
'comment' => $comment,
'type_space' => $typeSpace,
'var_space' => $varSpace,
'align_space' => $tokens[($tag + 1)]['content'],
];
}
$realParams = $phpcsFile->getMethodParameters($stackPtr);
$foundParams = [];
$previousParam = null;
foreach ($params as $pos => $param)
{
if ($param['var'] === '')
{
continue;
}
$foundParams[] = $param['var'];
// YaAPI change: There must be 3 spaces after the @param tag to make it line up with the @return tag
if ($param['align_space'] !== ' ')
{
$error = 'Expected 3 spaces before variable type, found %s';
$spaces = strlen($param['align_space']);
$data = [$spaces];
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'BeforeParamType', $data);
if ($fix === true)
{
$phpcsFile->fixer->beginChangeset();
for ($i = 0; $i < $spaces; $i++)
{
$phpcsFile->fixer->replaceToken(($param['tag'] + 1), '');
}
$phpcsFile->fixer->addContent($param['tag'], ' ');
$phpcsFile->fixer->endChangeset();
}
}
// Make sure the param name is correct.
if (isset($realParams[$pos]) === true)
{
$realName = $realParams[$pos]['name'];
if ($realName !== $param['var'])
{
$code = 'ParamNameNoMatch';
$data = [
$param['var'],
$realName,
];
$error = 'Doc comment for parameter %s does not match ';
if (strtolower($param['var']) === strtolower($realName))
{
$error .= 'case of ';
$code = 'ParamNameNoCaseMatch';
}
$error .= 'actual variable name %s';
$phpcsFile->addError($error, $param['tag'], $code, $data);
}
}
elseif (substr($param['var'], -4) !== ',...')
{
// We must have an extra parameter comment.
$error = 'Superfluous parameter comment';
$phpcsFile->addError($error, $param['tag'], 'ExtraParamComment');
}
if ($param['comment'] === '')
{
continue;
}
// YaAPI change: Enforces alignment of the param variables and comments
if ($previousParam !== null)
{
$previousName = ($previousParam['var'] !== '') ? $previousParam['var'] : 'UNKNOWN';
// Check to see if the parameters align properly.
if (!$this->paramVarsAlign($param, $previousParam))
{
$error = 'The variable names for parameters %s and %s do not align';
$data = [
$previousName,
$param['var'],
];
$phpcsFile->addError($error, $param['tag'], 'ParameterNamesNotAligned', $data);
}
// Check to see if the comments align properly.
if (!$this->paramCommentsAlign($param, $previousParam))
{
$error = 'The comments for parameters %s and %s do not align';
$data = [
$previousName,
$param['var'],
];
$phpcsFile->addError($error, $param['tag'], 'ParameterCommentsNotAligned', $data);
}
}
$previousParam = $param;
}
$realNames = [];
foreach ($realParams as $realParam)
{
$realNames[] = $realParam['name'];
}
// Report missing comments.
$diff = array_diff($realNames, $foundParams);
foreach ($diff as $neededParam)
{
$error = 'Doc comment for parameter "%s" missing';
$data = [$neededParam];
$phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data);
}
} | Process the function parameter comments.
Extends PEAR.Commenting.FunctionComment.processReturn to enforce correct alignment of the doc block.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param integer $stackPtr The position of the current token in the stack passed in $tokens.
@param integer $commentStart The position in the stack where the comment started.
@return void
@todo Reinstate the check that params come after the function's comment and has a blank line before them
@todo Reinstate the check that there is a blank line after all params are declared | https://github.com/yaapi/coding-standards/blob/b913fceff1c9b6f5af92eb235c8f72e8306a36e5/YaAPI/Sniffs/Commenting/FunctionCommentSniff.php#L168-L387 |
CeusMedia/Router | src/Router.php | Router.add | public function add( $controller, $action = 'index', $pattern, $method = '*' ){
$route = new Route( $controller, $action, $pattern, strtoupper( $method ) );
return $this->registry->add( $route );
} | php | public function add( $controller, $action = 'index', $pattern, $method = '*' ){
$route = new Route( $controller, $action, $pattern, strtoupper( $method ) );
return $this->registry->add( $route );
} | ...
@access public
@param string $controller Name of controller class
@param string $action Name of action name
@param string $pattern Pattern to resolve route by
@param string $method HTTP method (GET|POST|PUT|DELETE)
@return string ID of added route | https://github.com/CeusMedia/Router/blob/d4c68e8c2895abf5c13835e1671635507e2fb21d/src/Router.php#L65-L68 |
CeusMedia/Router | src/Router.php | Router.resolve | public function resolve( $path, $method = "GET", $strict = TRUE ){
return $this->resolver->resolve( $path, $method, $strict );
} | php | public function resolve( $path, $method = "GET", $strict = TRUE ){
return $this->resolver->resolve( $path, $method, $strict );
} | ...
@access public
@param string $path ...
@param string $method HTTP method (GET|POST|PUT|DELETE)
@param boolean $strict Flag: resolve in strict mode
@return Route | https://github.com/CeusMedia/Router/blob/d4c68e8c2895abf5c13835e1671635507e2fb21d/src/Router.php#L118-L120 |
agentmedia/phine-core | src/Core/Logic/Module/FrontendForm.php | FrontendForm.AddUniqueSubmit | protected function AddUniqueSubmit($label)
{
$name = $label . '-' . $this->Content()->GetID();
$fullLabel = $this->Label($label);
$this->AddSubmit($name, Trans($fullLabel));
} | php | protected function AddUniqueSubmit($label)
{
$name = $label . '-' . $this->Content()->GetID();
$fullLabel = $this->Label($label);
$this->AddSubmit($name, Trans($fullLabel));
} | Adds a submit button with a unique name
@param string $label The wording label used for the submit button | https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendForm.php#L12-L17 |
mullanaphy/variable | src/PHY/Variable/Obj.php | Obj.chain | public function chain($value = null)
{
if (null !== $value) {
$this->validate($value);
$this->set($value);
}
$this->chaining = true;
$this->chain = clone $this->current;
return $this;
} | php | public function chain($value = null)
{
if (null !== $value) {
$this->validate($value);
$this->set($value);
}
$this->chaining = true;
$this->chain = clone $this->current;
return $this;
} | {@inheritDoc} | https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/Obj.php#L57-L66 |
mullanaphy/variable | src/PHY/Variable/Obj.php | Obj.toArr | public function toArr()
{
$class = $this->get();
$class = new \PHY\Variable\Arr((array)$class);
foreach ($class as $key => $value) {
if (is_object($value)) {
$class[$key] = (new static($value))->toArr();
}
}
return $class;
} | php | public function toArr()
{
$class = $this->get();
$class = new \PHY\Variable\Arr((array)$class);
foreach ($class as $key => $value) {
if (is_object($value)) {
$class[$key] = (new static($value))->toArr();
}
}
return $class;
} | {@inheritDoc} | https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/Obj.php#L71-L81 |
mullanaphy/variable | src/PHY/Variable/Obj.php | Obj.toArray | public function toArray()
{
$class = $this->get();
$class = (array)$class;
foreach ($class as $key => $value) {
if (is_object($value)) {
$class[$key] = (new static($value))->toArray();
}
}
return $class;
} | php | public function toArray()
{
$class = $this->get();
$class = (array)$class;
foreach ($class as $key => $value) {
if (is_object($value)) {
$class[$key] = (new static($value))->toArray();
}
}
return $class;
} | Recursively convert our object into an array.
@return array | https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/Obj.php#L88-L98 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.validateTypes | protected function validateTypes(Dictionary $types, $path = "")
{
$spath = empty($path) ? "" : $path . ".";
foreach ($types as $key => $value)
{
$kpath = $spath . $key;
if ($value instanceof Dictionary)
{
$this->validateTypes($value, $kpath);
}
elseif (is_string($value))
{
$types[$key] = new Validator($value);
}
elseif (!($value instanceof Validator))
{
throw new \InvalidArgumentException(
"Unknown type: " . Functions::str($value) . " for " . $kpath
);
}
}
} | php | protected function validateTypes(Dictionary $types, $path = "")
{
$spath = empty($path) ? "" : $path . ".";
foreach ($types as $key => $value)
{
$kpath = $spath . $key;
if ($value instanceof Dictionary)
{
$this->validateTypes($value, $kpath);
}
elseif (is_string($value))
{
$types[$key] = new Validator($value);
}
elseif (!($value instanceof Validator))
{
throw new \InvalidArgumentException(
"Unknown type: " . Functions::str($value) . " for " . $kpath
);
}
}
} | Validate that all provided types are actually type validators
@param Dictionary $types The supplied type validators
@param string $path The key path, used for reporting errors | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L69-L90 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.setType | public function setType($key, $type)
{
$args = func_get_args();
$type = array_pop($args);
if (!($type instanceof Validator))
$type = new Validator($type);
if ($this->types->has($args))
{
$old_type = $this->types->get($args);
if ($old_type != $type)
throw new \LogicException("Duplicate key: " . WF::str($args));
}
else
{
$args[] = $type;
$this->types->set($args, null);
}
return $this;
} | php | public function setType($key, $type)
{
$args = func_get_args();
$type = array_pop($args);
if (!($type instanceof Validator))
$type = new Validator($type);
if ($this->types->has($args))
{
$old_type = $this->types->get($args);
if ($old_type != $type)
throw new \LogicException("Duplicate key: " . WF::str($args));
}
else
{
$args[] = $type;
$this->types->set($args, null);
}
return $this;
} | Add a type for a parameter
@param string $key The key to set a type for. Can be repeated to go deeper
@param Validator $type The type for the parameter
@return TypedDictionary Provides fluent interface | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L98-L118 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.set | public function set($key, $value)
{
if (is_array($key) && $value === null)
$args = $key;
else
$args = func_get_args();
$path = $args;
$value = array_pop($path);
$type = $this->types->dget($path);
$kpath = implode('.', $path);
// Key is undefined, but it may be in a untyped sub-array
if ($type === null)
{
$cpy = $path;
while (count($cpy))
{
$last = array_pop($cpy);
$subtype = $this->types->dget($cpy);
if ($subtype instanceof Validator && $subtype->getType() === Type::ARRAY)
return parent::set($args, null);
}
}
if ($type === null)
throw new \InvalidArgumentException("Undefined key: " . $kpath);
if ($type instanceof Dictionary)
{
// Subfiltering required - extract values
if (!Functions::is_array_like($value))
throw new \InvalidArgumentException("Value must be array at: " . $kpath);
foreach ($value as $subkey => $subval)
{
$nargs = $path;
$nargs[] = $subkey;
$nargs[] = $subval;
$this->set($nargs, null);
}
return;
}
if (!$type->validate($value))
{
$error = $type->getErrorMessage($value);
$msg = WF::fillPlaceholders($error['msg'], $error['context'] ?? []);
throw new \InvalidArgumentException($msg);
}
return parent::set($args, null);
} | php | public function set($key, $value)
{
if (is_array($key) && $value === null)
$args = $key;
else
$args = func_get_args();
$path = $args;
$value = array_pop($path);
$type = $this->types->dget($path);
$kpath = implode('.', $path);
// Key is undefined, but it may be in a untyped sub-array
if ($type === null)
{
$cpy = $path;
while (count($cpy))
{
$last = array_pop($cpy);
$subtype = $this->types->dget($cpy);
if ($subtype instanceof Validator && $subtype->getType() === Type::ARRAY)
return parent::set($args, null);
}
}
if ($type === null)
throw new \InvalidArgumentException("Undefined key: " . $kpath);
if ($type instanceof Dictionary)
{
// Subfiltering required - extract values
if (!Functions::is_array_like($value))
throw new \InvalidArgumentException("Value must be array at: " . $kpath);
foreach ($value as $subkey => $subval)
{
$nargs = $path;
$nargs[] = $subkey;
$nargs[] = $subval;
$this->set($nargs, null);
}
return;
}
if (!$type->validate($value))
{
$error = $type->getErrorMessage($value);
$msg = WF::fillPlaceholders($error['msg'], $error['context'] ?? []);
throw new \InvalidArgumentException($msg);
}
return parent::set($args, null);
} | Set a value, after type checking
@param string $key The key to set. Can be repeated to go deeper
@param mixed $value Whatever to set. Will be type checked
@return TypedDictionary Provides fluent interface | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L126-L178 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.& | public function &dget($key, $default = null)
{
$args = WF::flatten_array(func_get_args());
if (func_num_args() > 1)
{
$default = array_pop($args);
if (!($default instanceof DefVal))
$default = new DefVal($default);
$args[] = $default;
}
// Get the value, without referencing, so that we actually return a copy
$result = parent::dget($args, null);
if ($result instanceof Dictionary)
{
// Sub-arrays are returned as dictionary - which allow
// modification without type checking. Re-wrap into
// a TypedDictionary including the correct types
$path = $args;
$types = $this->types->dget($path);
if (WF::is_array_like($types))
{
$dict = new TypedDictionary($types);
$dict->values = &$result->values;
$result = $dict;
}
}
// Return the copy to keep it unmodifiable
return $result;
} | php | public function &dget($key, $default = null)
{
$args = WF::flatten_array(func_get_args());
if (func_num_args() > 1)
{
$default = array_pop($args);
if (!($default instanceof DefVal))
$default = new DefVal($default);
$args[] = $default;
}
// Get the value, without referencing, so that we actually return a copy
$result = parent::dget($args, null);
if ($result instanceof Dictionary)
{
// Sub-arrays are returned as dictionary - which allow
// modification without type checking. Re-wrap into
// a TypedDictionary including the correct types
$path = $args;
$types = $this->types->dget($path);
if (WF::is_array_like($types))
{
$dict = new TypedDictionary($types);
$dict->values = &$result->values;
$result = $dict;
}
}
// Return the copy to keep it unmodifiable
return $result;
} | We override dget as dget returns a reference, allowing the
TypedDictionary to be modified from the outside. This avoids the checks,
so this needs to be disallowed.
@param string $key The key to set. Can be repeated to go deeper
@param mixed $default A default value to return in absence | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L188-L220 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.addAll | public function addAll($values)
{
foreach ($values as $key => $value)
$this->set($key, $value);
return $this;
} | php | public function addAll($values)
{
foreach ($values as $key => $value)
$this->set($key, $value);
return $this;
} | Add all provided values, checking their types
@param array $values Array with values.
@return TypedDictionary Provides fluent interface | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L227-L232 |
Wedeto/Util | src/TypedDictionary.php | TypedDictionary.wrap | public static function wrap(array &$values)
{
$types = new Dictionary;
self::determineTypes($values, $types);
return new TypedDictionary($types, $values);
} | php | public static function wrap(array &$values)
{
$types = new Dictionary;
self::determineTypes($values, $types);
return new TypedDictionary($types, $values);
} | Customize wrapping of the TypedDictionary - the wrapped array can still
be modified externally so we need to make sure the appropriate types are
propagated
@throws RuntimeException Always | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/TypedDictionary.php#L296-L302 |
azhai/code-refactor | src/CodeRefactor/Mixin/VisitorMixin.php | VisitorMixin.normalizeValue | public static function normalizeValue($value)
{
if ($value instanceof Node) {
return $value;
} elseif (is_null($value)) {
return new Expr\ConstFetch(
new Name('null')
);
} elseif (is_bool($value)) {
return new Expr\ConstFetch(
new Name($value ? 'true' : 'false')
);
} elseif (is_int($value)) {
return new Scalar\LNumber($value);
} elseif (is_float($value)) {
return new Scalar\DNumber($value);
} elseif (is_string($value)) {
return new Scalar\String_($value);
} elseif (is_array($value)) {
$items = [];
$lastKey = -1;
foreach ($value as $itemKey => $itemValue) {
// for consecutive, numeric keys don't generate keys
if (null !== $lastKey && ++$lastKey === $itemKey) {
$items[] = new Expr\ArrayItem(
self::normalizeValue($itemValue)
);
} else {
$lastKey = null;
$items[] = new Expr\ArrayItem(
self::normalizeValue($itemValue),
self::normalizeValue($itemKey)
);
}
}
return new Expr\Array_($items);
} else {
throw new \LogicException('Invalid value');
}
} | php | public static function normalizeValue($value)
{
if ($value instanceof Node) {
return $value;
} elseif (is_null($value)) {
return new Expr\ConstFetch(
new Name('null')
);
} elseif (is_bool($value)) {
return new Expr\ConstFetch(
new Name($value ? 'true' : 'false')
);
} elseif (is_int($value)) {
return new Scalar\LNumber($value);
} elseif (is_float($value)) {
return new Scalar\DNumber($value);
} elseif (is_string($value)) {
return new Scalar\String_($value);
} elseif (is_array($value)) {
$items = [];
$lastKey = -1;
foreach ($value as $itemKey => $itemValue) {
// for consecutive, numeric keys don't generate keys
if (null !== $lastKey && ++$lastKey === $itemKey) {
$items[] = new Expr\ArrayItem(
self::normalizeValue($itemValue)
);
} else {
$lastKey = null;
$items[] = new Expr\ArrayItem(
self::normalizeValue($itemValue),
self::normalizeValue($itemKey)
);
}
}
return new Expr\Array_($items);
} else {
throw new \LogicException('Invalid value');
}
} | Normalizes a value: Converts nulls, booleans, integers,
floats, strings and arrays into their respective nodes
@param mixed $value The value to normalize
@return Expr The normalized value | https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Mixin/VisitorMixin.php#L25-L64 |
cmsgears/module-sns-connect | frontend/controllers/TwitterController.php | TwitterController.init | public function init() {
parent::init();
$this->modelService = Yii::$app->factory->get( 'twitterProfileService' );
$this->twitterService = Yii::$app->factory->get( 'twitterService' );
} | php | public function init() {
parent::init();
$this->modelService = Yii::$app->factory->get( 'twitterProfileService' );
$this->twitterService = Yii::$app->factory->get( 'twitterService' );
} | Constructor and Initialisation ------------------------------ | https://github.com/cmsgears/module-sns-connect/blob/753ee4157d41c81a701689624f4c44760a6cada3/frontend/controllers/TwitterController.php#L47-L54 |
cmsgears/module-sns-connect | frontend/controllers/TwitterController.php | TwitterController.actionLogin | public function actionLogin() {
$this->twitterService->requestToken();
$authToken = Yii::$app->session->get( 'tw_oauth_token' );
$this->redirect( "https://api.twitter.com/oauth/authorize?oauth_token=$authToken" );
} | php | public function actionLogin() {
$this->twitterService->requestToken();
$authToken = Yii::$app->session->get( 'tw_oauth_token' );
$this->redirect( "https://api.twitter.com/oauth/authorize?oauth_token=$authToken" );
} | TwitterController --------------------- | https://github.com/cmsgears/module-sns-connect/blob/753ee4157d41c81a701689624f4c44760a6cada3/frontend/controllers/TwitterController.php#L86-L93 |
mwyatt/core | src/FileSystem.php | FileSystem.globRecursive | private function globRecursive($pattern)
{
$paths = glob($pattern);
foreach ($paths as $path) {
if (strpos($path, '.') === false) {
$paths = array_merge($paths, $this->globRecursive($path . '/*'));
}
}
return $paths;
} | php | private function globRecursive($pattern)
{
$paths = glob($pattern);
foreach ($paths as $path) {
if (strpos($path, '.') === false) {
$paths = array_merge($paths, $this->globRecursive($path . '/*'));
}
}
return $paths;
} | watch out can be slow!
4.75s for 20k paths
@param string $pattern '/*'
@return array paths | https://github.com/mwyatt/core/blob/8ea9d67cc84fe6aff17a469c703d5492dbcd93ed/src/FileSystem.php#L99-L108 |
DaGhostman/codewave | src/Aspects/Catchable.php | Catchable.aroundCatchableAnnotation | public function aroundCatchableAnnotation(MethodInvocation $invocation)
{
try {
return $invocation->proceed();
} catch (\Exception $ex) {
$this->logger->error('Unhandled exception {exception} with {message} occurred in {file}:{line}', [
'exception' => get_class($ex),
'message' => $ex->getMessage() ,
'file' => $ex->getFile(),
'line' => $ex->getLine()
]);
throw $ex;
}
} | php | public function aroundCatchableAnnotation(MethodInvocation $invocation)
{
try {
return $invocation->proceed();
} catch (\Exception $ex) {
$this->logger->error('Unhandled exception {exception} with {message} occurred in {file}:{line}', [
'exception' => get_class($ex),
'message' => $ex->getMessage() ,
'file' => $ex->getFile(),
'line' => $ex->getLine()
]);
throw $ex;
}
} | @param MethodInvocation $invocation
@Around("@annotation(Wave\Framework\Annotations\LogErrors)")
@throws \Exception
@return mixed | https://github.com/DaGhostman/codewave/blob/f0f58e721699cdaaf87cbfaf8ce589a6b3c473b8/src/Aspects/Catchable.php#L67-L81 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.get | public function get(/*# string */ $key)/*# : string */
{
// try front-end cache first
if ($this->frontHas($key)) {
return $this->front->get($key);
}
// get from backend cache
return $this->back->get($key);
} | php | public function get(/*# string */ $key)/*# : string */
{
// try front-end cache first
if ($this->frontHas($key)) {
return $this->front->get($key);
}
// get from backend cache
return $this->back->get($key);
} | Either end get ok is ok
{@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L127-L136 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.has | public function has(/*# string */ $key)/*# : int */
{
// try front-end cache first
$res = $this->frontHas($key);
if ($res) {
return $res;
}
// try backend cache
return $this->backHas($key);
} | php | public function has(/*# string */ $key)/*# : int */
{
// try front-end cache first
$res = $this->frontHas($key);
if ($res) {
return $res;
}
// try backend cache
return $this->backHas($key);
} | Either end has is ok
{inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L169-L179 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.clear | public function clear()/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->clear()) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | php | public function clear()/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->clear()) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | Need both ends clear ok
{@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L186-L198 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.delete | public function delete(/*# string */ $key)/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->delete($key)) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | php | public function delete(/*# string */ $key)/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->delete($key)) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | Need both ends delete ok
{@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L205-L217 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.commit | public function commit()/*# : bool */
{
$ends = [ $this->front, $this->back ];
$res = false;
foreach ($ends as $end) {
// commit failed, set error
if (!$end->commit()) {
$this->setError(
$end->getError(),
$end->getErrorCode()
);
// one commit is ok, then all ok
} else {
$res = true;
}
}
return $res;
} | php | public function commit()/*# : bool */
{
$ends = [ $this->front, $this->back ];
$res = false;
foreach ($ends as $end) {
// commit failed, set error
if (!$end->commit()) {
$this->setError(
$end->getError(),
$end->getErrorCode()
);
// one commit is ok, then all ok
} else {
$res = true;
}
}
return $res;
} | One end commit ok is ok
{@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L240-L260 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.purge | public function purge(/*# int */ $maxlife)/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->purge($maxlife)) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | php | public function purge(/*# int */ $maxlife)/*# : bool */
{
$ends = [ $this->front, $this->back ];
foreach ($ends as $end) {
if (!$end->purge($maxlife)) {
return $this->falseAndSetError(
$end->getError(),
$end->getErrorCode()
);
}
}
return $this->trueAndFlushError();
} | Need both ends purge ok
{@inheritDoc} | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L267-L279 |
phossa/phossa-cache | src/Phossa/Cache/Driver/CompositeDriver.php | CompositeDriver.protectedSave | protected function protectedSave(
CacheItemInterface $item,
$function = 'save'
)/*# : bool */ {
// write to both ?
$func = $this->tester;
$both = $func($item);
// if $both is true, write to front
$res1 = false;
if ($both) {
if ($this->front->$function($item)) {
$res1 = true; // ok
} else {
$this->setError(
$this->front->getError(),
$this->front->getErrorCode()
);
}
}
// always write to backend
$res2 = false;
if ($this->back->$function($item)) {
$res2 = true; // ok
} else {
$this->setError(
$this->back->getError(),
$this->back->getErrorCode()
);
}
return $res1 || $res2 ? true : false;
} | php | protected function protectedSave(
CacheItemInterface $item,
$function = 'save'
)/*# : bool */ {
// write to both ?
$func = $this->tester;
$both = $func($item);
// if $both is true, write to front
$res1 = false;
if ($both) {
if ($this->front->$function($item)) {
$res1 = true; // ok
} else {
$this->setError(
$this->front->getError(),
$this->front->getErrorCode()
);
}
}
// always write to backend
$res2 = false;
if ($this->back->$function($item)) {
$res2 = true; // ok
} else {
$this->setError(
$this->back->getError(),
$this->back->getErrorCode()
);
}
return $res1 || $res2 ? true : false;
} | local save method, one end save ok is ok
@param CacheItemInterface $item
@param string $function save or saveDeferred
@return bool
@access protected | https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/Driver/CompositeDriver.php#L299-L332 |
PascalKleindienst/simple-api-client | src/Model.php | Model.fill | private function fill($attributes)
{
// json
if (is_string($attributes)) {
$attributes = json_decode($attributes, true);
}
// check if attributes are valid
if (!is_array($attributes)) {
throw new \InvalidArgumentException('Attributes must be of type array or a valid json string');
}
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
} | php | private function fill($attributes)
{
// json
if (is_string($attributes)) {
$attributes = json_decode($attributes, true);
}
// check if attributes are valid
if (!is_array($attributes)) {
throw new \InvalidArgumentException('Attributes must be of type array or a valid json string');
}
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
} | Fill the attributes
@param string|array $attributes
@return void | https://github.com/PascalKleindienst/simple-api-client/blob/f4e20aa65bb9c340b8aff78acaede7dc62cd2105/src/Model.php#L35-L50 |
PascalKleindienst/simple-api-client | src/Model.php | Model.getAttribute | public function getAttribute($key)
{
$value = $this->getAttributeValue($key);
// First we will check for the presence of a mutator for the set operation
// which simply lets the developers tweak the attribute as it is set.
if ($this->hasGetMutator($key)) {
$method = 'get' . studly_case($key) . 'Attribute';
return $this->{$method}($value);
}
return $value;
} | php | public function getAttribute($key)
{
$value = $this->getAttributeValue($key);
// First we will check for the presence of a mutator for the set operation
// which simply lets the developers tweak the attribute as it is set.
if ($this->hasGetMutator($key)) {
$method = 'get' . studly_case($key) . 'Attribute';
return $this->{$method}($value);
}
return $value;
} | Get an attribute from the $attributes array.
@param string $key
@return mixed | https://github.com/PascalKleindienst/simple-api-client/blob/f4e20aa65bb9c340b8aff78acaede7dc62cd2105/src/Model.php#L107-L120 |
PascalKleindienst/simple-api-client | src/Model.php | Model.getAttributeValue | protected function getAttributeValue($key)
{
if (array_key_exists($key, $this->attributes)) {
return $this->attributes[$key];
}
return null;
} | php | protected function getAttributeValue($key)
{
if (array_key_exists($key, $this->attributes)) {
return $this->attributes[$key];
}
return null;
} | Get an attribute from the $attributes array.
@param string $key
@return mixed | https://github.com/PascalKleindienst/simple-api-client/blob/f4e20aa65bb9c340b8aff78acaede7dc62cd2105/src/Model.php#L127-L134 |
PascalKleindienst/simple-api-client | src/Model.php | Model.makeCollection | public function makeCollection(array $values, $class = null)
{
$collection = new Collection($values);
if (!is_null($class) && class_exists($class)) {
$model = new $class();
if ($model instanceof Model) {
foreach ($collection as $key => $item) {
$collection[$key] = $model->newInstance($item);
}
}
}
return $collection;
} | php | public function makeCollection(array $values, $class = null)
{
$collection = new Collection($values);
if (!is_null($class) && class_exists($class)) {
$model = new $class();
if ($model instanceof Model) {
foreach ($collection as $key => $item) {
$collection[$key] = $model->newInstance($item);
}
}
}
return $collection;
} | Transform an array of values into a collection of models
@param array $values
@param null $class
@return \Illuminate\Support\Collection | https://github.com/PascalKleindienst/simple-api-client/blob/f4e20aa65bb9c340b8aff78acaede7dc62cd2105/src/Model.php#L161-L176 |
PenoaksDev/Milky-Framework | src/Milky/Account/Middleware/RedirectIfAuthenticated.php | RedirectIfAuthenticated.handle | public function handle( $request, Closure $next, $guard = null )
{
if ( Acct::check() )
return Redirect::to( '/' );
return $next( $request );
} | php | public function handle( $request, Closure $next, $guard = null )
{
if ( Acct::check() )
return Redirect::to( '/' );
return $next( $request );
} | Handle an incoming request.
@param Request $request
@param \Closure $next
@param string|null $guard
@return mixed | https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Account/Middleware/RedirectIfAuthenticated.php#L18-L24 |
story75/Doctrine-Annotations | src/Factory/AnnotationReaderFactory.php | AnnotationReaderFactory.create | public function create(array $parameters = [])
{
$parameters = $this->optionResolver->resolve($parameters);
$this->registerLoader();
$this->setIgnoredNames();
if (!$parameters['cache'] instanceof Cache) {
throw new \InvalidArgumentException('"cache" has to be instance an instance of ' . Cache::class);
}
$reader = new CachedReader(
new AnnotationReader(),
$parameters['cache'],
$parameters['debug']
);
if ($parameters['indexed'] === true) {
return new IndexedReader($reader);
}
return $reader;
} | php | public function create(array $parameters = [])
{
$parameters = $this->optionResolver->resolve($parameters);
$this->registerLoader();
$this->setIgnoredNames();
if (!$parameters['cache'] instanceof Cache) {
throw new \InvalidArgumentException('"cache" has to be instance an instance of ' . Cache::class);
}
$reader = new CachedReader(
new AnnotationReader(),
$parameters['cache'],
$parameters['debug']
);
if ($parameters['indexed'] === true) {
return new IndexedReader($reader);
}
return $reader;
} | Return an object with fully injected dependencies
@param array $parameters
@return Reader | https://github.com/story75/Doctrine-Annotations/blob/ac909323e5894d764eb39e5bb9509071566021ad/src/Factory/AnnotationReaderFactory.php#L80-L102 |
rancoud/Session | src/DriverManager.php | DriverManager.useDefaultEncryptionDriver | public static function useDefaultEncryptionDriver(string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DefaultEncryption();
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | php | public static function useDefaultEncryptionDriver(string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DefaultEncryption();
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | @param string $key
@param string|null $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L48-L56 |
rancoud/Session | src/DriverManager.php | DriverManager.useFileEncryptionDriver | public static function useFileEncryptionDriver(string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new FileEncryption();
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | php | public static function useFileEncryptionDriver(string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new FileEncryption();
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | @param string $key
@param string|null $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L74-L82 |
rancoud/Session | src/DriverManager.php | DriverManager.useNewDatabaseDriver | public static function useNewDatabaseDriver($configuration): void
{
static::throwExceptionIfHasStarted();
$driver = new Database();
$driver->setNewDatabase($configuration);
static::$driver = $driver;
} | php | public static function useNewDatabaseDriver($configuration): void
{
static::throwExceptionIfHasStarted();
$driver = new Database();
$driver->setNewDatabase($configuration);
static::$driver = $driver;
} | @param \Rancoud\Database\Configurator|array $configuration
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L89-L97 |
rancoud/Session | src/DriverManager.php | DriverManager.useCurrentDatabaseDriver | public static function useCurrentDatabaseDriver($databaseInstance): void
{
static::throwExceptionIfHasStarted();
$driver = new Database();
$driver->setCurrentDatabase($databaseInstance);
static::$driver = $driver;
} | php | public static function useCurrentDatabaseDriver($databaseInstance): void
{
static::throwExceptionIfHasStarted();
$driver = new Database();
$driver->setCurrentDatabase($databaseInstance);
static::$driver = $driver;
} | @param \Rancoud\Database\Database $databaseInstance
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L104-L112 |
rancoud/Session | src/DriverManager.php | DriverManager.useNewDatabaseEncryptionDriver | public static function useNewDatabaseEncryptionDriver($configuration, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DatabaseEncryption();
$driver->setNewDatabase($configuration);
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | php | public static function useNewDatabaseEncryptionDriver($configuration, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DatabaseEncryption();
$driver->setNewDatabase($configuration);
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | @param \Rancoud\Database\Configurator|array $configuration
@param string $key
@param string $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L121-L130 |
rancoud/Session | src/DriverManager.php | DriverManager.useCurrentDatabaseEncryptionDriver | public static function useCurrentDatabaseEncryptionDriver($databaseInstance, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DatabaseEncryption();
$driver->setCurrentDatabase($databaseInstance);
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | php | public static function useCurrentDatabaseEncryptionDriver($databaseInstance, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new DatabaseEncryption();
$driver->setCurrentDatabase($databaseInstance);
static::setKeyAndMethod($driver, $key, $method);
static::$driver = $driver;
} | @param \Rancoud\Database\Database $databaseInstance
@param string $key
@param string $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L139-L148 |
rancoud/Session | src/DriverManager.php | DriverManager.useNewRedisDriver | public static function useNewRedisDriver($configuration): void
{
static::throwExceptionIfHasStarted();
$driver = new Redis();
$driver->setNewRedis($configuration);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | php | public static function useNewRedisDriver($configuration): void
{
static::throwExceptionIfHasStarted();
$driver = new Redis();
$driver->setNewRedis($configuration);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | @param array|string $configuration
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L155-L164 |
rancoud/Session | src/DriverManager.php | DriverManager.useCurrentRedisDriver | public static function useCurrentRedisDriver($redisInstance): void
{
static::throwExceptionIfHasStarted();
$driver = new Redis();
$driver->setCurrentRedis($redisInstance);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | php | public static function useCurrentRedisDriver($redisInstance): void
{
static::throwExceptionIfHasStarted();
$driver = new Redis();
$driver->setCurrentRedis($redisInstance);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | @param \Predis\Client $redisInstance
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L171-L180 |
rancoud/Session | src/DriverManager.php | DriverManager.useNewRedisEncryptionDriver | public static function useNewRedisEncryptionDriver($configuration, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new RedisEncryption();
$driver->setNewRedis($configuration);
static::setKeyAndMethod($driver, $key, $method);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | php | public static function useNewRedisEncryptionDriver($configuration, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new RedisEncryption();
$driver->setNewRedis($configuration);
static::setKeyAndMethod($driver, $key, $method);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | @param array|string $configuration
@param string $key
@param string $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L189-L199 |
rancoud/Session | src/DriverManager.php | DriverManager.useCurrentRedisEncryptionDriver | public static function useCurrentRedisEncryptionDriver($redisInstance, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new RedisEncryption();
$driver->setCurrentRedis($redisInstance);
static::setKeyAndMethod($driver, $key, $method);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | php | public static function useCurrentRedisEncryptionDriver($redisInstance, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
$driver = new RedisEncryption();
$driver->setCurrentRedis($redisInstance);
static::setKeyAndMethod($driver, $key, $method);
$driver->setLifetime(static::getLifetimeForRedis());
static::$driver = $driver;
} | @param \Predis\Client $redisInstance
@param string $key
@param string $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L208-L218 |
rancoud/Session | src/DriverManager.php | DriverManager.setKeyAndMethod | private static function setKeyAndMethod($driver, $key, $method): void
{
$driver->setKey($key);
if ($method !== null) {
$driver->setMethod($method);
}
} | php | private static function setKeyAndMethod($driver, $key, $method): void
{
$driver->setKey($key);
if ($method !== null) {
$driver->setMethod($method);
}
} | @param \Rancoud\Session\Encryption $driver
@param $key
@param $method
@throws \Exception | https://github.com/rancoud/Session/blob/8c79fae900a0804b3c0637e51bf52d8bb9b9cfb3/src/DriverManager.php#L227-L233 |
MichaelRShelton/attribute-translator | src/Providers/AttributeTranslatorServiceProvider.php | AttributeTranslatorServiceProvider.registerService | public function registerService()
{
$this->app->bind('mrs.attributes.translator', function ($attributeMap = []) {
return new AttributeTranslator($attributeMap);
});
$this->app->alias('mrs.attributes.translator', 'attributes.translator');
$this->app->alias('mrs.attributes.translator', AttributeTranslatorInterface::class);
} | php | public function registerService()
{
$this->app->bind('mrs.attributes.translator', function ($attributeMap = []) {
return new AttributeTranslator($attributeMap);
});
$this->app->alias('mrs.attributes.translator', 'attributes.translator');
$this->app->alias('mrs.attributes.translator', AttributeTranslatorInterface::class);
} | Register services to the application container. | https://github.com/MichaelRShelton/attribute-translator/blob/48a0ef01058647eeeeeeb8954f93b479bd713b82/src/Providers/AttributeTranslatorServiceProvider.php#L46-L53 |
Palmabit-IT/library | src/Palmabit/Library/ImportExport/CsvFileReader.php | CsvFileReader.open | public function open($path)
{
$this->convertToLF($path);
$this->spl_file_object = new SplFileObject($path);
$this->spl_file_object->setCsvControl($this->delimiter);
$this->columns_name = $this->spl_file_object->fgetcsv();
} | php | public function open($path)
{
$this->convertToLF($path);
$this->spl_file_object = new SplFileObject($path);
$this->spl_file_object->setCsvControl($this->delimiter);
$this->columns_name = $this->spl_file_object->fgetcsv();
} | Open stream from a source
A source can be anything: for instance a db, a file, or a socket
@param String $path
@return void
@throws \Palmabit\Library\Exceptions\CannotOpenFileException | https://github.com/Palmabit-IT/library/blob/ec49a3c333eb4e94d9610a0f58d82c9ea1ade4b9/src/Palmabit/Library/ImportExport/CsvFileReader.php#L36-L42 |
Palmabit-IT/library | src/Palmabit/Library/ImportExport/CsvFileReader.php | CsvFileReader.readElement | public function readElement()
{
$csv_line_data = $this->spl_file_object->fgetcsv();
if($csv_line_data)
{
$csv_line_data[0] = $this->convertToUtf8($csv_line_data);
if($this->isValidLine($csv_line_data))
{
$csv_line = array_combine($this->columns_name, $csv_line_data);
// we cast it to StdClass
return (object)$csv_line;
}
}
return false;
} | php | public function readElement()
{
$csv_line_data = $this->spl_file_object->fgetcsv();
if($csv_line_data)
{
$csv_line_data[0] = $this->convertToUtf8($csv_line_data);
if($this->isValidLine($csv_line_data))
{
$csv_line = array_combine($this->columns_name, $csv_line_data);
// we cast it to StdClass
return (object)$csv_line;
}
}
return false;
} | Reads a single element from the source
then return a Object instance
@return \StdClass|false object instance | https://github.com/Palmabit-IT/library/blob/ec49a3c333eb4e94d9610a0f58d82c9ea1ade4b9/src/Palmabit/Library/ImportExport/CsvFileReader.php#L50-L65 |
Palmabit-IT/library | src/Palmabit/Library/ImportExport/CsvFileReader.php | CsvFileReader.readElements | public function readElements()
{
$iterator = new ArrayIterator;
do
{
$object = $this->readElement();
if($object) $iterator->append($object);
} while((boolean)$object);
$this->objects = $iterator;
return $this->objects;
} | php | public function readElements()
{
$iterator = new ArrayIterator;
do
{
$object = $this->readElement();
if($object) $iterator->append($object);
} while((boolean)$object);
$this->objects = $iterator;
return $this->objects;
} | Read all the objects from the source
@return \ArrayIterator | https://github.com/Palmabit-IT/library/blob/ec49a3c333eb4e94d9610a0f58d82c9ea1ade4b9/src/Palmabit/Library/ImportExport/CsvFileReader.php#L81-L92 |
Vectrex/vxPHP | src/Form/FormElement/FormElementWithOptions/SelectOptionElement.php | SelectOptionElement.render | public function render($force = false) {
if(empty($this->html) || $force) {
if($this->selected) {
$this->attributes['selected'] = 'selected';
}
else {
unset($this->attributes['selected']);
}
$this->attributes['value'] = $this->getValue();
$attr = [];
foreach($this->attributes as $k => $v) {
$attr[] = sprintf('%s="%s"', $k, $v);
}
$this->html = sprintf(
'<option %s>%s</option>',
implode(' ', $attr),
$this->getLabel()->getLabelText()
);
}
return $this->html;
} | php | public function render($force = false) {
if(empty($this->html) || $force) {
if($this->selected) {
$this->attributes['selected'] = 'selected';
}
else {
unset($this->attributes['selected']);
}
$this->attributes['value'] = $this->getValue();
$attr = [];
foreach($this->attributes as $k => $v) {
$attr[] = sprintf('%s="%s"', $k, $v);
}
$this->html = sprintf(
'<option %s>%s</option>',
implode(' ', $attr),
$this->getLabel()->getLabelText()
);
}
return $this->html;
} | render option element; when $force is FALSE a cached element rendering is re-used
@param boolean $force
@return string | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/FormElement/FormElementWithOptions/SelectOptionElement.php#L43-L71 |
Aviogram/Common | src/Hydrator/ByConfigBuilder.php | ByConfigBuilder.addField | public function addField($fieldName, $getMethod, $setMethod, ByConfigBuilder $include = null, $formatter = null)
{
if (method_exists($this->getEntityPrototype(), $getMethod) === false) {
throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $getMethod, $this->entityClassName), 2);
}
if (method_exists($this->getEntityPrototype(), $setMethod) === false) {
throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $setMethod, $this->entityClassName), 2);
}
$this->mapping[$fieldName] = array(
'getter' => $getMethod,
'setter' => $setMethod,
'include' => $include,
'formatter' => $formatter,
);
return $this;
} | php | public function addField($fieldName, $getMethod, $setMethod, ByConfigBuilder $include = null, $formatter = null)
{
if (method_exists($this->getEntityPrototype(), $getMethod) === false) {
throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $getMethod, $this->entityClassName), 2);
}
if (method_exists($this->getEntityPrototype(), $setMethod) === false) {
throw new Exception\ConfigFailed(sprintf($this->exceptions[2], $setMethod, $this->entityClassName), 2);
}
$this->mapping[$fieldName] = array(
'getter' => $getMethod,
'setter' => $setMethod,
'include' => $include,
'formatter' => $formatter,
);
return $this;
} | Set a mapping
@param string $fieldName
@param string $getMethod
@param string $setMethod
@param ByConfigBuilder $include
@param Closure $formatter
@return $this | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L91-L109 |
Aviogram/Common | src/Hydrator/ByConfigBuilder.php | ByConfigBuilder.isInclude | public function isInclude($fieldName)
{
if ($this->hasField($fieldName) === false) {
return false;
}
$class = __CLASS__;
return ($this->mapping[$fieldName]['include'] instanceof $class);
} | php | public function isInclude($fieldName)
{
if ($this->hasField($fieldName) === false) {
return false;
}
$class = __CLASS__;
return ($this->mapping[$fieldName]['include'] instanceof $class);
} | Check if the given fieldName is an include
@param string $fieldName
@return bool TRUE on include | FALSE when field does not exists or field is not a include | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L130-L139 |
Aviogram/Common | src/Hydrator/ByConfigBuilder.php | ByConfigBuilder.getSetter | public function getSetter($fieldName)
{
if ($this->hasField($fieldName) === false) {
return false;
}
return $this->mapping[$fieldName]['setter'];
} | php | public function getSetter($fieldName)
{
if ($this->hasField($fieldName) === false) {
return false;
}
return $this->mapping[$fieldName]['setter'];
} | Return the setter name
@param string $fieldName
@return string | bool FALSE when field does not exists | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L148-L155 |
Aviogram/Common | src/Hydrator/ByConfigBuilder.php | ByConfigBuilder.getGetter | public function getGetter($fieldName)
{
if ($this->hasField($fieldName) === false)
{
return false;
}
return $this->mapping[$fieldName]['getter'];
} | php | public function getGetter($fieldName)
{
if ($this->hasField($fieldName) === false)
{
return false;
}
return $this->mapping[$fieldName]['getter'];
} | Return the getter name
@param string $fieldName
@return string | bool FALSE when field does not exists | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L164-L171 |
Aviogram/Common | src/Hydrator/ByConfigBuilder.php | ByConfigBuilder.getInclude | public function getInclude($fieldName)
{
if ($this->isInclude($fieldName) === false) {
return false;
}
return $this->mapping[$fieldName]['include'];
} | php | public function getInclude($fieldName)
{
if ($this->isInclude($fieldName) === false) {
return false;
}
return $this->mapping[$fieldName]['include'];
} | Get the include config
@param string $fieldName
@return ByConfigBuilder | bool FALSE when fieldName is not a include | https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfigBuilder.php#L180-L187 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.