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
|
---|---|---|---|---|---|---|---|
mglaman/docker-helper | src/Machine.php | Machine.getEnv | public static function getEnv($name)
{
$envs = [];
$output = self::runCommand('env', [$name]);
if (trim($output->getOutput()) == "$name is not running. Please start this with docker-machine start $name") {
throw new \Exception('Docker machine has not been started yet.');
}
$envOutput = explode(PHP_EOL, $output->getOutput());
foreach ($envOutput as $line) {
if (strpos($line, 'export') !== false) {
list(, $export) = explode(' ', $line, 2);
list($key, $value) = explode('=', $export, 2);
$envs[$key] = str_replace('"', '', $value);
}
}
return $envs;
} | php | public static function getEnv($name)
{
$envs = [];
$output = self::runCommand('env', [$name]);
if (trim($output->getOutput()) == "$name is not running. Please start this with docker-machine start $name") {
throw new \Exception('Docker machine has not been started yet.');
}
$envOutput = explode(PHP_EOL, $output->getOutput());
foreach ($envOutput as $line) {
if (strpos($line, 'export') !== false) {
list(, $export) = explode(' ', $line, 2);
list($key, $value) = explode('=', $export, 2);
$envs[$key] = str_replace('"', '', $value);
}
}
return $envs;
} | Returns an array of the environment for the Docker client.
@param $name
@return array
@throws \Exception | https://github.com/mglaman/docker-helper/blob/b262a50dcdbc495487568f775a8f41da82ae2c03/src/Machine.php#L89-L105 |
K-Phoen/gaufrette-extras-bundle | Form/Type/ImageType.php | ImageType.buildView | public function buildView(FormView $view, FormInterface $form, array $options)
{
$parentData = $form->getParent()->getData();
if ($parentData !== null) {
$accessor = PropertyAccess::getPropertyAccessor();
// set an "image_url" variable that will be available when rendering this field
$url = $accessor->getValue($parentData, $options['image_path']);
if ($url !== null) {
$view->vars['image_url'] = $url;
}
}
if (empty($view->vars['image_url']) && $options['no_image_placeholder'] !== null) {
$view->vars['image_url'] = $options['no_image_placeholder'];
}
$view->vars['gaufrette'] = $options['gaufrette'];
$view->vars['image_alt'] = $options['image_alt'];
$view->vars['image_width'] = $options['image_width'];
$view->vars['image_height'] = $options['image_height'];
} | php | public function buildView(FormView $view, FormInterface $form, array $options)
{
$parentData = $form->getParent()->getData();
if ($parentData !== null) {
$accessor = PropertyAccess::getPropertyAccessor();
// set an "image_url" variable that will be available when rendering this field
$url = $accessor->getValue($parentData, $options['image_path']);
if ($url !== null) {
$view->vars['image_url'] = $url;
}
}
if (empty($view->vars['image_url']) && $options['no_image_placeholder'] !== null) {
$view->vars['image_url'] = $options['no_image_placeholder'];
}
$view->vars['gaufrette'] = $options['gaufrette'];
$view->vars['image_alt'] = $options['image_alt'];
$view->vars['image_width'] = $options['image_width'];
$view->vars['image_height'] = $options['image_height'];
} | Pass the image url to the view
@param FormView $view
@param FormInterface $form
@param array $options | https://github.com/K-Phoen/gaufrette-extras-bundle/blob/3f05779179117d5649184164544e1f22de28d706/Form/Type/ImageType.php#L46-L67 |
antaresproject/translations | src/Http/Controllers/Admin/SyncController.php | SyncController.index | public function index($area = null, $locale = null)
{
return $this->processor->index($this, !is_null($area) ? $area : area(), $locale);
} | php | public function index($area = null, $locale = null)
{
return $this->processor->index($this, !is_null($area) ? $area : area(), $locale);
} | index default action
@return \Illuminate\View\View | https://github.com/antaresproject/translations/blob/63097aeb97f18c5aeeef7dcf15f0c67959951685/src/Http/Controllers/Admin/SyncController.php#L57-L60 |
Phpillip/phpillip | src/Console/Application.php | Application.doRun | public function doRun(InputInterface $input, OutputInterface $output)
{
$this->kernel->boot();
$this->kernel->flush();
return parent::doRun($input, $output);
} | php | public function doRun(InputInterface $input, OutputInterface $output)
{
$this->kernel->boot();
$this->kernel->flush();
return parent::doRun($input, $output);
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Application.php#L54-L60 |
Phpillip/phpillip | src/Console/Application.php | Application.getDefaultCommands | protected function getDefaultCommands()
{
return array_merge(
parent::getDefaultCommands(),
[
new Command\BuildCommand(),
new Command\ExposeCommand(),
new Command\ServeCommand(),
new Command\WatchCommand(),
],
array_map(function ($className) {
return new $className;
}, $this->getKernel()['commands'])
);
} | php | protected function getDefaultCommands()
{
return array_merge(
parent::getDefaultCommands(),
[
new Command\BuildCommand(),
new Command\ExposeCommand(),
new Command\ServeCommand(),
new Command\WatchCommand(),
],
array_map(function ($className) {
return new $className;
}, $this->getKernel()['commands'])
);
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Application.php#L65-L79 |
newup/core | src/Console/Commandable.php | Commandable.setApplication | public function setApplication(ApplicationContract $application = null)
{
$this->application = $application;
if ($application) {
$this->setHelperSet($application->getHelperSet());
} else {
$this->helperSet = null;
}
} | php | public function setApplication(ApplicationContract $application = null)
{
$this->application = $application;
if ($application) {
$this->setHelperSet($application->getHelperSet());
} else {
$this->helperSet = null;
}
} | Sets the ApplicationContract instance.
@param ApplicationContract|null $application | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commandable.php#L50-L58 |
newup/core | src/Console/Commandable.php | Commandable.askWithCompletion | public function askWithCompletion($question, array $choices, $default = null)
{
$helper = $this->getHelperSet()->get('question');
$question = new Question("<question>$question</question> ", $default);
$question->setAutocompleterValues($choices);
return $helper->ask($this->input, $this->output, $question);
} | php | public function askWithCompletion($question, array $choices, $default = null)
{
$helper = $this->getHelperSet()->get('question');
$question = new Question("<question>$question</question> ", $default);
$question->setAutocompleterValues($choices);
return $helper->ask($this->input, $this->output, $question);
} | Prompt the user for input with auto completion.
@param string $question
@param array $choices
@param string $default
@return string | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commandable.php#L160-L169 |
newup/core | src/Console/Commandable.php | Commandable.secret | public function secret($question, $fallback = true)
{
$helper = $this->getHelperSet()->get('question');
$question = new Question("<question>$question</question> ");
$question->setHidden(true)->setHiddenFallback($fallback);
return $helper->ask($this->input, $this->output, $question);
} | php | public function secret($question, $fallback = true)
{
$helper = $this->getHelperSet()->get('question');
$question = new Question("<question>$question</question> ");
$question->setHidden(true)->setHiddenFallback($fallback);
return $helper->ask($this->input, $this->output, $question);
} | Prompt the user for input but hide the answer from the console.
@param string $question
@param bool $fallback
@return string | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commandable.php#L178-L187 |
newup/core | src/Console/Commandable.php | Commandable.choice | public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null)
{
$helper = $this->getHelperSet()->get('question');
$question = new ChoiceQuestion("<question>$question</question> ", $choices, $default);
$question->setMaxAttempts($attempts)->setMultiselect($multiple);
return $helper->ask($this->input, $this->output, $question);
} | php | public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null)
{
$helper = $this->getHelperSet()->get('question');
$question = new ChoiceQuestion("<question>$question</question> ", $choices, $default);
$question->setMaxAttempts($attempts)->setMultiselect($multiple);
return $helper->ask($this->input, $this->output, $question);
} | Give the user a single choice from an array of answers.
@param string $question
@param array $choices
@param string $default
@param mixed $attempts
@param bool $multiple
@return bool | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commandable.php#L199-L208 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.group | public function group($items)
{
$group = [];
foreach ((array) $items as $item) {
$group[$item] = $this->formatCmd($item);
}
$this->group = $group;
return $this;
} | php | public function group($items)
{
$group = [];
foreach ((array) $items as $item) {
$group[$item] = $this->formatCmd($item);
}
$this->group = $group;
return $this;
} | ######################### aggregation ############################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L76-L87 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.order | public function order($items)
{
$this->order = [];
if (!empty($items)) {
$this->addOrder($items);
}
return $this;
} | php | public function order($items)
{
$this->order = [];
if (!empty($items)) {
$this->addOrder($items);
}
return $this;
} | ######################### ordering ############################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L124-L133 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.select | public function select($items)
{
$this->select = [];
if (!empty($items)) {
$this->addSelect($items);
}
return $this;
} | php | public function select($items)
{
$this->select = [];
if (!empty($items)) {
$this->addSelect($items);
}
return $this;
} | ######################### projection ############################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L155-L164 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.where | public function where($conditions, $parameters = [])
{
$this->where = [];
if (!empty($conditions)) {
$this->addWhere($conditions, $parameters);
}
return $this;
} | php | public function where($conditions, $parameters = [])
{
$this->where = [];
if (!empty($conditions)) {
$this->addWhere($conditions, $parameters);
}
return $this;
} | ######################### where condition ############################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L215-L224 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.having | public function having($conditions, $parameters = [])
{
$this->having = [];
if (!empty($conditions)) {
$this->addHaving($conditions, $parameters);
}
return $this;
} | php | public function having($conditions, $parameters = [])
{
$this->having = [];
if (!empty($conditions)) {
$this->addHaving($conditions, $parameters);
}
return $this;
} | ######################### having condition ############################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L251-L260 |
Vyki/mva-dbm | src/Mva/Dbm/Query/QueryBuilder.php | QueryBuilder.buildSelectQuery | public function buildSelectQuery()
{
if ($aggregate = $this->getAggregate()) {
return [$this->buildAggreregateQuery(), [], []];
}
$options = [];
if ($limit = $this->getLimit()) {
$options[IQuery::LIMIT] = $limit;
}
if ($offset = $this->getOffset()) {
$options[IQuery::OFFSET] = $offset;
}
if (($sort = $this->getOrder()) && !empty($sort)) {
$options[IQuery::ORDER] = $sort;
}
return [$this->getSelect(), $this->getWhere(), $options];
} | php | public function buildSelectQuery()
{
if ($aggregate = $this->getAggregate()) {
return [$this->buildAggreregateQuery(), [], []];
}
$options = [];
if ($limit = $this->getLimit()) {
$options[IQuery::LIMIT] = $limit;
}
if ($offset = $this->getOffset()) {
$options[IQuery::OFFSET] = $offset;
}
if (($sort = $this->getOrder()) && !empty($sort)) {
$options[IQuery::ORDER] = $sort;
}
return [$this->getSelect(), $this->getWhere(), $options];
} | ################## builders ################## | https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryBuilder.php#L287-L308 |
brainexe/core | src/DependencyInjection/CompilerPass/Cron.php | Cron.process | public function process(ContainerBuilder $container)
{
$allCrons = [];
$taggedServices = $container->findTaggedServiceIds(self::TAG);
foreach (array_keys($taggedServices) as $serviceId) {
/** @var CronInterface $cron */
$definition = $container->getDefinition($serviceId);
$cron = $definition->getClass();
$allCrons = array_merge($allCrons, $cron::getCrons());
}
$this->dumpVariableToCache(self::CACHE_FILE, $allCrons);
} | php | public function process(ContainerBuilder $container)
{
$allCrons = [];
$taggedServices = $container->findTaggedServiceIds(self::TAG);
foreach (array_keys($taggedServices) as $serviceId) {
/** @var CronInterface $cron */
$definition = $container->getDefinition($serviceId);
$cron = $definition->getClass();
$allCrons = array_merge($allCrons, $cron::getCrons());
}
$this->dumpVariableToCache(self::CACHE_FILE, $allCrons);
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/DependencyInjection/CompilerPass/Cron.php#L24-L37 |
borobudur-php/borobudur | src/Borobudur/Component/Collection/Collection.php | Collection.chunk | public function chunk(int $size): CollectionInterface
{
if ($size <= 0) {
return new static();
}
$chunks = [];
foreach (array_chunk($this->data->getValues(), $size, true) as $chunk) {
$chunks[] = new static($chunk);
}
return new static($chunks);
} | php | public function chunk(int $size): CollectionInterface
{
if ($size <= 0) {
return new static();
}
$chunks = [];
foreach (array_chunk($this->data->getValues(), $size, true) as $chunk) {
$chunks[] = new static($chunk);
}
return new static($chunks);
} | {@inheritdoc}
@return CollectionInterface|static | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Collection/Collection.php#L39-L52 |
borobudur-php/borobudur | src/Borobudur/Component/Collection/Collection.php | Collection.set | public function set(int $key, $value): void
{
$this->data->set($key, $value);
} | php | public function set(int $key, $value): void
{
$this->data->set($key, $value);
} | {@inheritdoc} | https://github.com/borobudur-php/borobudur/blob/6ab0d97e1819ba0b96dc4c3bca3a7c9b1217bd44/src/Borobudur/Component/Collection/Collection.php#L113-L116 |
as3io/modlr | src/Metadata/Traits/MixinsTrait.php | MixinsTrait.addMixin | public function addMixin(MixinMetadata $mixin)
{
if (isset($this->mixins[$mixin->name])) {
return $this;
}
$this->applyMixinProperties($mixin);
$this->mixins[$mixin->name] = $mixin;
return $this;
} | php | public function addMixin(MixinMetadata $mixin)
{
if (isset($this->mixins[$mixin->name])) {
return $this;
}
$this->applyMixinProperties($mixin);
$this->mixins[$mixin->name] = $mixin;
return $this;
} | Adds a mixin (and applies its properties) to this object.
@param MixinMetadata $mixin
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/Traits/MixinsTrait.php#L28-L37 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Subscriber_Create | public function Subscriber_Create($subscription_state, $division, $attributes) {
$data = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
$ret = $this->_call_api('post', "{$this->_url}/subscribers", $data);
return $ret;
} | php | public function Subscriber_Create($subscription_state, $division, $attributes) {
$data = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
$ret = $this->_call_api('post', "{$this->_url}/subscribers", $data);
return $ret;
} | Create a new subscriber.
@param mixed $subscription_state [optional] Any of {"UNSUBSCRIBED", "SUBSCRIBED", "REFERRED"}
@param mixed $division [optional] The division display name. If this is specified the subscriber will be
subscribed to this division.
@param array $attributes Valid attributes in the payload include any subscriber attributes defined for this
company. In order to create a subscriber, all of the attributes which comprise the
unique subscriber key for the company are required, and a valid value must be provided
for each required attribute. Attributes which are not in the unique key are optional.
NOTE: emailFormat, aka emailProgram, is an optional setting, but if it is not set, then
when editing the user in the UI it will default to TEXT.
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L72-L77 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Subscriber_Update | public function Subscriber_Update($user_id, $subscription_state, $division, $attributes, $allow_resubscribe = true,
$append = false) {
$data = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
if (is_null($allow_resubscribe) === false) {
$data->allowResubscribe = $allow_resubscribe;
}
if (is_null($append) === false) {
$data->append = $append;
}
$ret = $this->_call_api('put', "{$this->_url}/subscribers/$user_id", $data);
return $ret;
} | php | public function Subscriber_Update($user_id, $subscription_state, $division, $attributes, $allow_resubscribe = true,
$append = false) {
$data = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
if (is_null($allow_resubscribe) === false) {
$data->allowResubscribe = $allow_resubscribe;
}
if (is_null($append) === false) {
$data->append = $append;
}
$ret = $this->_call_api('put', "{$this->_url}/subscribers/$user_id", $data);
return $ret;
} | Update an existing subscriber.
@param int $user_id The id of the subscriber to update
@param mixed $subscription_state [optional] Any of {"UNSUBSCRIBED", "SUBSCRIBED", "REFERRED", "DEAD", "REVIVED"}
@param mixed $division [optional] The division display name. If this is specified the subscriber will be
subscribed to this division.
@param array $attributes Valid attributes in the payload include any subscriber attributes defined for this
company. In order to create a subscriber, all of the attributes which comprise the
unique subscriber key for the company are required, and a valid value must be provided
for each required attribute. Attributes which are not in the unique key are optional.
NOTE: emailFormat, aka emailProgram, is an optional setting, but if it is not set, then
when editing the user in the UI it will default to TEXT.
@param bool $allow_resubscribe [optional] Flag to explicitly indicate you wish to resubscribe a subscriber. allowResubscribe
must be set to true when transitioning from an UNSUBSCRIBED to SUBSCRIBED state.
@param bool $append [optional] If true all multi-value attributes get updated like an append or merge, if false
(the default) all are replaced
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L99-L114 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Subscriber_Get_Id | public function Subscriber_Get_Id($attributes) {
try {
$ret = $this->Subscriber_Lookup($attributes);
$uri = $ret->uri;
$id = (int) substr(strrchr($uri, '/'), 1);
} catch (\Exception $e) {
if( $e->getCode() === 404){
$id = false;
} else {
throw $e;
}
}
return $id;
} | php | public function Subscriber_Get_Id($attributes) {
try {
$ret = $this->Subscriber_Lookup($attributes);
$uri = $ret->uri;
$id = (int) substr(strrchr($uri, '/'), 1);
} catch (\Exception $e) {
if( $e->getCode() === 404){
$id = false;
} else {
throw $e;
}
}
return $id;
} | Look up the id of an existing subscriber.
@param array $attributes An array of attribute to look up the subscriber with
@return mixed Either the subscriber id, or false if the subscriber is not found
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L136-L150 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Subscriber_Retrieve | public function Subscriber_Retrieve($attributes, $division) {
$ret = false;
$subscriberId = $this->Subscriber_Get_Id($attributes);
if ($subscriberId !== false) {
$ret = $this->_call_api('get', "{$this->_url}/subscribers/$subscriberId", array('division' => $division));
}
return $ret;
} | php | public function Subscriber_Retrieve($attributes, $division) {
$ret = false;
$subscriberId = $this->Subscriber_Get_Id($attributes);
if ($subscriberId !== false) {
$ret = $this->_call_api('get', "{$this->_url}/subscribers/$subscriberId", array('division' => $division));
}
return $ret;
} | Retrieve all information about a subscriber, including attributes, division subscription status, etc.
@param array $attributes An array of attribute to look up the subscriber with
@param mixed $division The division display name. The division from which to get the subscribers information
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L174-L182 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Subscribe_And_Send | public function Subscribe_And_Send($subscription_state, $division, $attributes, $allow_resubscribe, $masterId) {
$data = new \stdClass();
$subscriber = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
if (is_bool($allow_resubscribe) === true) {
$subscriber->allowResubscribe = $allow_resubscribe;
}
$data->subscriber = $subscriber;
$subscriberMessage = new \stdClass();
$subscriberMessage->masterId = $masterId;
$data->subscriberMessage = $subscriberMessage;
$ret = $this->_call_api('post', "{$this->_url}/composite/subscribeAndSend", $data);
return $ret;
} | php | public function Subscribe_And_Send($subscription_state, $division, $attributes, $allow_resubscribe, $masterId) {
$data = new \stdClass();
$subscriber = $this->_package_subscriber_elements($subscription_state, $division, $attributes);
if (is_bool($allow_resubscribe) === true) {
$subscriber->allowResubscribe = $allow_resubscribe;
}
$data->subscriber = $subscriber;
$subscriberMessage = new \stdClass();
$subscriberMessage->masterId = $masterId;
$data->subscriberMessage = $subscriberMessage;
$ret = $this->_call_api('post', "{$this->_url}/composite/subscribeAndSend", $data);
return $ret;
} | Subscribe and send
@param mixed $subscription_state Any of {"UNSUBSCRIBED", "SUBSCRIBED", "REFERRED", "DEAD", "REVIVED"} or null
@param mixed $division The division display name. If specified, the subscriber will be subscribed
to this division. If null, subscriber will not be subscribed to a division.
@param array $attributes Valid values are any attributes defined in the system.
@param bool $allow_resubscribe Flag to explicitly indicate you wish to resubscribe a subscriber. allowResubscribe
must be set to true when transitioning from an UNSUBSCRIBED to SUBSCRIBED state.
@param int $masterId Must be a valid master defined for the company. The master is typically set up to be in a
disabled state.
@return
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L198-L214 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Status_Get | public function Status_Get($guid, $nowait = true) {
if ($nowait === true) {
$ret = $this->_call_api('get', "{$this->_url}/statusNoWait/$guid", array());
} else {
do {
$ret = $this->_call_api('get', "{$this->_url}/status/$guid", array());
switch($ret->statusCode) {
case 'COMPLETED':
case 'CANCELLED':
case 'ERROR':
$wait = false;
break;
case 'INPROGRESS':
case 'SUBMITTED':
case 'PAUSED':
$wait = true;
break;
default:
$wait = false; // Unknown status, don't wait forever
}
} while ( $wait === true);
}
return $ret;
} | php | public function Status_Get($guid, $nowait = true) {
if ($nowait === true) {
$ret = $this->_call_api('get', "{$this->_url}/statusNoWait/$guid", array());
} else {
do {
$ret = $this->_call_api('get', "{$this->_url}/status/$guid", array());
switch($ret->statusCode) {
case 'COMPLETED':
case 'CANCELLED':
case 'ERROR':
$wait = false;
break;
case 'INPROGRESS':
case 'SUBMITTED':
case 'PAUSED':
$wait = true;
break;
default:
$wait = false; // Unknown status, don't wait forever
}
} while ( $wait === true);
}
return $ret;
} | Get the status of an outstanding request.
@param int $guid The trackingId of the request to get status for
@param bool $nowait True if we should return without blocking. False if we should block until the request
reaches a completed state.
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L225-L251 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Create | public function Master_Create($envelope, $targeting, $scheduling) {
$ret = false;
$data = $this->_package_master_elements($envelope, $targeting, $scheduling);
if ($data !== false) {
$ret = $this->_call_api('post', "{$this->_url}/masters", $data);
}
return $ret;
} | php | public function Master_Create($envelope, $targeting, $scheduling) {
$ret = false;
$data = $this->_package_master_elements($envelope, $targeting, $scheduling);
if ($data !== false) {
$ret = $this->_call_api('post', "{$this->_url}/masters", $data);
}
return $ret;
} | Create a new Master
@param object $envelope The envelope to use for the new master
@param mixed $targeting [optional] Optional targeting parameters to use for the new master
@param mixed $scheduling [optional] Optional scheduling parameters to use for the new master
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L271-L280 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Update | public function Master_Update($masterId, $envelope, $targeting, $scheduling) {
$ret = false;
$data = $this->_package_master_elements($envelope, $targeting, $scheduling);
if ($data !== false) {
$ret = $this->_call_api('put', "{$this->_url}/masters/$masterId", $data);
}
return $ret;
} | php | public function Master_Update($masterId, $envelope, $targeting, $scheduling) {
$ret = false;
$data = $this->_package_master_elements($envelope, $targeting, $scheduling);
if ($data !== false) {
$ret = $this->_call_api('put', "{$this->_url}/masters/$masterId", $data);
}
return $ret;
} | Update an existing Master
@param int $masterId The id of the master to update
@param object $envelope The envelope to use for the new master
@param mixed $targeting [optional] Optional targeting parameters to use for the new master
@param mixed $scheduling [optional] Optional scheduling parameters to use for the new master
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L292-L301 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Get | public function Master_Get($masterId) {
$ret = false;
if (is_int($masterId) === true) {
try {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId", array());
$ret = $this->_Type_Safe_Yesmail_Master($ret);
$ret->id = (int) $masterId; // Add id to object for easy reference
} catch (\Exception $e) {
if( $e->getCode() === 404){
$ret = false;
} else {
throw $e;
}
}
}
return $ret;
} | php | public function Master_Get($masterId) {
$ret = false;
if (is_int($masterId) === true) {
try {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId", array());
$ret = $this->_Type_Safe_Yesmail_Master($ret);
$ret->id = (int) $masterId; // Add id to object for easy reference
} catch (\Exception $e) {
if( $e->getCode() === 404){
$ret = false;
} else {
throw $e;
}
}
}
return $ret;
} | Get an existing Master
@param int $masterId The id of the master to retrieve
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L337-L355 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Get_By_Name | public function Master_Get_By_Name($masterName) {
$ret = false;
if (is_string($masterName) === true) {
$pageSize = 50;
$begin = 1;
$end = $pageSize;
$filter = 'active';
$more = true;
while($more) {
$res = $this->_call_api('get', "{$this->_url}/masters", array('begin' => $begin, 'end' => $end,
'filter' => $filter));
foreach($res->masters as $result) {
if ($result->masterName === $masterName) {
$ret = $result;
break;
}
}
// NOTE: Do not change >= to === below. Yesmail API does not always return the correct number of records.
// Using >= makes us safe from their bad math.
$more = ($ret === false && count($res->masters) >= $pageSize ? true : false);
$begin += $pageSize;
$end += $pageSize;
}
}
if ($ret !== false) {
$ret = $this->Master_Get((int)$ret->masterId);
}
return $ret;
} | php | public function Master_Get_By_Name($masterName) {
$ret = false;
if (is_string($masterName) === true) {
$pageSize = 50;
$begin = 1;
$end = $pageSize;
$filter = 'active';
$more = true;
while($more) {
$res = $this->_call_api('get', "{$this->_url}/masters", array('begin' => $begin, 'end' => $end,
'filter' => $filter));
foreach($res->masters as $result) {
if ($result->masterName === $masterName) {
$ret = $result;
break;
}
}
// NOTE: Do not change >= to === below. Yesmail API does not always return the correct number of records.
// Using >= makes us safe from their bad math.
$more = ($ret === false && count($res->masters) >= $pageSize ? true : false);
$begin += $pageSize;
$end += $pageSize;
}
}
if ($ret !== false) {
$ret = $this->Master_Get((int)$ret->masterId);
}
return $ret;
} | Get an existing Master by name
@param int $masterName The name of the master to retrieve
@return mixed A JSON decoded PHP variable representing the HTTP response, or false if the master is not found
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L364-L397 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Post_Run_Count | public function Master_Post_Run_Count($masterId) {
$ret = false;
if (is_int($masterId) === true) {
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/RUN/countData", array());
}
return $ret;
} | php | public function Master_Post_Run_Count($masterId) {
$ret = false;
if (is_int($masterId) === true) {
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/RUN/countData", array());
}
return $ret;
} | Submit the master's ID and RUN the eAPI service URL to request the the count job for a specific master
Run this before doing Master_Post_Run_Count
@param int $master_id master's id to check the count for
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L407-L415 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Get_Count | public function Master_Get_Count($masterId) {
$ret = false;
if (is_int($masterId) === true) {
do {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId/countData", array());
// Sleep for 15 seconds so we don't keep hammering the api
sleep(15);
}
while (!$this->Status_Is_Completed($ret->status));
}
return $ret;
} | php | public function Master_Get_Count($masterId) {
$ret = false;
if (is_int($masterId) === true) {
do {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId/countData", array());
// Sleep for 15 seconds so we don't keep hammering the api
sleep(15);
}
while (!$this->Status_Is_Completed($ret->status));
}
return $ret;
} | Get the number of active subscribers based on master's id.
Run this after doing Master_Post_Run_Count
@param int $master_id master's id to check the count for
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L425-L438 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Assets_Get | public function Master_Assets_Get($masterId) {
$ret = false;
if (is_int($masterId) === true) {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId/assets", array());
}
return $ret;
} | php | public function Master_Assets_Get($masterId) {
$ret = false;
if (is_int($masterId) === true) {
$ret = $this->_call_api('get', "{$this->_url}/masters/$masterId/assets", array());
}
return $ret;
} | Get the assets that belong to a Master
@param int $masterId The id of the master who's assets are being requested
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L484-L492 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Asset_Add | public function Master_Asset_Add($masterId, $assetName, $assetBase64Data) {
$ret = false;
if (is_int($masterId) === true && is_string($assetName) === true && is_string($assetBase64Data) === true) {
$data = array('assetName' => $assetName , 'assetBase64Data' => $assetBase64Data);
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/assets", $data);
}
return $ret;
} | php | public function Master_Asset_Add($masterId, $assetName, $assetBase64Data) {
$ret = false;
if (is_int($masterId) === true && is_string($assetName) === true && is_string($assetBase64Data) === true) {
$data = array('assetName' => $assetName , 'assetBase64Data' => $assetBase64Data);
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/assets", $data);
}
return $ret;
} | Add new asset(s) to a Master
@param int $masterId The id of the master to add the asset(s) to
@param string $assetName Valid file extensions are: .txt, .html, .htm, .gif, .jpg, .png, or .zip
@param string $assetBase64Data Should be a base-64 encoded string of the content or archive (zip file) being uploaded.
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L503-L512 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.Master_Preview | public function Master_Preview($masterId, $contentType, $distributionList, $userId, $emails) {
$ret = false;
$contentTypes = array('HTML', 'PLAIN', 'BOTH', 'USERPREFERENCE');
if (in_array($contentType, $contentTypes) === true) {
if (is_string($distributionList) === true xor (is_int($userId) === true && is_array($emails) === true)) {
$data = new \stdClass();
$data->contentType = $contentType;
if (is_string($distributionList) === true) {
$data->distributionList = $distributionList;
} else {
$data->manualList = new \stdClass();
$data->manualList->userId = $userId;
$data->manualList->emails = $emails;
}
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/sendPreviews?validate", $data);
}
}
return $ret;
} | php | public function Master_Preview($masterId, $contentType, $distributionList, $userId, $emails) {
$ret = false;
$contentTypes = array('HTML', 'PLAIN', 'BOTH', 'USERPREFERENCE');
if (in_array($contentType, $contentTypes) === true) {
if (is_string($distributionList) === true xor (is_int($userId) === true && is_array($emails) === true)) {
$data = new \stdClass();
$data->contentType = $contentType;
if (is_string($distributionList) === true) {
$data->distributionList = $distributionList;
} else {
$data->manualList = new \stdClass();
$data->manualList->userId = $userId;
$data->manualList->emails = $emails;
}
$ret = $this->_call_api('post', "{$this->_url}/masters/$masterId/sendPreviews?validate", $data);
}
}
return $ret;
} | Provides a way to preview a message by sending it to a group of email addresses, following the same semantics as
the preview functionality within the Enterprise Application.
@param int $masterId The id of the master to preview
@param string $contentType HTML - Use HTML content in the email
PLAIN - Use plain text content in the email.
BOTH - Send two emails, one using HTML content and another using the plain text version.
If the user is configured to only accept one type of email, only one will be sent.
USERPREFERENCE - Send either HTML or plain text email based on the preference
indicated by the user being targeted.
@param string $distributionList The name of a distribution list to email to. Mutually exclusive with manualList
@param int $userId A child element of manualList, templating of the email uses this user's attributes.
@param array $emails A child element of manualList, this is a space-delimited list of email addresses.
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access public | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L545-L567 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.ListManagement_Get_Lists | public function ListManagement_Get_Lists($type) {
$ret = false;
if (is_string($type) === true) {
$type = rawurlencode($type);
$ret = $this->_call_api('get', "{$this->_url}/lists/$type", array());
}
return $ret;
} | php | public function ListManagement_Get_Lists($type) {
$ret = false;
if (is_string($type) === true) {
$type = rawurlencode($type);
$ret = $this->_call_api('get', "{$this->_url}/lists/$type", array());
}
return $ret;
} | Get a list of lists given a list type
@param string $type The type of lists to get. Should be either LISTLOADLIST or DISTRIBUTIONLIST
@return mixed A JSON decoded PHP variable representing the HTTP response | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L575-L584 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.ListManagement_Get_List | public function ListManagement_Get_List($name, $type) {
$ret = false;
if (is_string($name) === true && is_string($type) === true) {
$name = rawurlencode($name);
$type = rawurlencode($type);
$ret = $this->_call_api('get', "{$this->_url}/lists/$type/$name", array());
}
return $ret;
} | php | public function ListManagement_Get_List($name, $type) {
$ret = false;
if (is_string($name) === true && is_string($type) === true) {
$name = rawurlencode($name);
$type = rawurlencode($type);
$ret = $this->_call_api('get', "{$this->_url}/lists/$type/$name", array());
}
return $ret;
} | Get a quick summary of the list: its name, type, subtype if relevant, resource uri, and its list id.
@param string $name The name of the list to get.
@param string $type The type of list to get. Should be either LISTLOADLIST or DISTRIBUTIONLIST.
@return mixed A JSON decoded PHP variable representing the HTTP response | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L594-L604 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.ListManagement_Update_List | public function ListManagement_Update_List($modifyList) {
$ret = false;
if ($modifyList instanceof \Yesmail\YesmailListManagementModifyList && $modifyList->is_valid() === true) {
$name = rawurlencode($modifyList->name);
$type = rawurlencode($modifyList->type);
$ret = $this->_call_api('put', "{$this->_url}/lists/$type/$name", $modifyList->subscriberList);
}
return $ret;
} | php | public function ListManagement_Update_List($modifyList) {
$ret = false;
if ($modifyList instanceof \Yesmail\YesmailListManagementModifyList && $modifyList->is_valid() === true) {
$name = rawurlencode($modifyList->name);
$type = rawurlencode($modifyList->type);
$ret = $this->_call_api('put', "{$this->_url}/lists/$type/$name", $modifyList->subscriberList);
}
return $ret;
} | Either remove or append the subscribers identified in the payload. For subscriberIds and emails that are
submitted as part of a request that cannot be mapped back to existing subscriber data are ignored and a total
count of the number added users is returned as part of the status message.
@param object $modifyList
@return mixed A JSON decoded PHP variable representing the HTTP response | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L614-L624 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail.ListManagement_Create_List | public function ListManagement_Create_List($modifyList) {
$ret = false;
if ($modifyList instanceof \Yesmail\YesmailListManagementModifyList && $modifyList->is_valid() === true) {
$ret = $this->_call_api('post', "{$this->_url}/lists/{$modifyList->type}", $modifyList);
}
return $ret;
} | php | public function ListManagement_Create_List($modifyList) {
$ret = false;
if ($modifyList instanceof \Yesmail\YesmailListManagementModifyList && $modifyList->is_valid() === true) {
$ret = $this->_call_api('post', "{$this->_url}/lists/{$modifyList->type}", $modifyList);
}
return $ret;
} | Create a new list of the given type
@param object $modifyList
@return mixed A JSON decoded PHP variable representing the HTTP response | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L632-L640 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail._package_master_elements | protected function _package_master_elements($envelope, $targeting, $scheduling) {
$ret = false;
if ($envelope instanceof \Yesmail\YesmailMasterEnvelope && $envelope->is_valid() === true) {
$ret = new \stdClass();
$ret->envelope = $envelope;
if ($targeting instanceof \Yesmail\YesmailMasterTargeting && $targeting->is_valid() === true) {
$ret->targeting = $targeting;
}
if ($scheduling instanceof \Yesmail\YesmailMasterScheduling && $scheduling->is_valid() === true) {
$ret->scheduling = $scheduling;
}
}
return $ret;
} | php | protected function _package_master_elements($envelope, $targeting, $scheduling) {
$ret = false;
if ($envelope instanceof \Yesmail\YesmailMasterEnvelope && $envelope->is_valid() === true) {
$ret = new \stdClass();
$ret->envelope = $envelope;
if ($targeting instanceof \Yesmail\YesmailMasterTargeting && $targeting->is_valid() === true) {
$ret->targeting = $targeting;
}
if ($scheduling instanceof \Yesmail\YesmailMasterScheduling && $scheduling->is_valid() === true) {
$ret->scheduling = $scheduling;
}
}
return $ret;
} | Package a Master's envelope, targeting, and scheduling for sending in a request
@param object $envelope The Master's envelope
@param mixed $targeting [optional] Optional targeting parameters for the new master
@param mixed $scheduling [optional] Optional scheduling parameters for the new master
@return mixed Either a stdClass object containing the Master's elements, or false upon failure | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L681-L698 |
PopSugar/php-yesmail-api | src/Yesmail/Yesmail.php | Yesmail._call_api | protected function _call_api( $method, $url, $params ) {
$raw_response = $this->_client->$method($url, $params);
$info = $this->_client->get_info();
if ($info['http_code'] != null) {
switch ($info["http_code"]) {
case 200:
case 202:
$response = json_decode($raw_response);
break;
/*
case 400:
throw new MalformedRequestException();
case 401:
throw new AuthenticationFailedException();
case 404:
throw new ResourceNotFoundException();
case 500:
throw new InternalServerErrorException();
case 503:
throw new ServiceTemporarilyUnavailableException();
*/
default:
throw new \Exception("Error: {$info['http_code']}", $info['http_code']);
}
}
return $response;
} | php | protected function _call_api( $method, $url, $params ) {
$raw_response = $this->_client->$method($url, $params);
$info = $this->_client->get_info();
if ($info['http_code'] != null) {
switch ($info["http_code"]) {
case 200:
case 202:
$response = json_decode($raw_response);
break;
/*
case 400:
throw new MalformedRequestException();
case 401:
throw new AuthenticationFailedException();
case 404:
throw new ResourceNotFoundException();
case 500:
throw new InternalServerErrorException();
case 503:
throw new ServiceTemporarilyUnavailableException();
*/
default:
throw new \Exception("Error: {$info['http_code']}", $info['http_code']);
}
}
return $response;
} | Make a call to the Yesmail API
@param string $method Any of {'get', 'put', 'post', 'delete'}
@param string $url The url of the API call
@param mixed $params An object or array of parameters to submit in the request
@return mixed A JSON decoded PHP variable representing the HTTP response.
@access protected
@throws Exception | https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/Yesmail.php#L735-L762 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.getQualitySetting | public static function getQualitySetting($defaultQuality, $data = [])
{
if (!empty($data['quality'])) {
return $data['quality'];
}
return \Yii::$app->settings->get('media_configuration', 'quality', $defaultQuality);
} | php | public static function getQualitySetting($defaultQuality, $data = [])
{
if (!empty($data['quality'])) {
return $data['quality'];
}
return \Yii::$app->settings->get('media_configuration', 'quality', $defaultQuality);
} | @param $defaultQuality
@param array $data
@return mixed | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L44-L50 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.getFileNameSave | public static function getFileNameSave($file_name)
{
FileHelper::createDirectory(self::getUploadDir() . '/' . date('Y/m/d'));
return self::getUploadDir() . '/' . $file_name;
} | php | public static function getFileNameSave($file_name)
{
FileHelper::createDirectory(self::getUploadDir() . '/' . date('Y/m/d'));
return self::getUploadDir() . '/' . $file_name;
} | @param $file_name
@return string
@throws \yii\base\Exception | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L71-L75 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.createNewMedia | public static function createNewMedia($file_name, $fileName_save, $url, $data = [])
{
$media = new Media([
'name' => $file_name,
'path' => $url,
'type' => FileHelper::getMimeType($fileName_save),
'file_size' => filesize($fileName_save),
'dimensions' => getimagesize($fileName_save)[0] . 'x' . getimagesize($fileName_save)[1],
]);
if (!empty($data['title'])) {
$media->title = $data['title'];
}
if (!empty($data['caption'])) {
$media->caption = $data['caption'];
}
if (!empty($data['alt'])) {
$media->alt = $data['alt'];
}
if (!empty($data['description'])) {
$media->description = $data['description'];
}
if (!\Yii::$app->user->isGuest) {
$media->created_by = \Yii::$app->user->id;
}
$media->save();
} | php | public static function createNewMedia($file_name, $fileName_save, $url, $data = [])
{
$media = new Media([
'name' => $file_name,
'path' => $url,
'type' => FileHelper::getMimeType($fileName_save),
'file_size' => filesize($fileName_save),
'dimensions' => getimagesize($fileName_save)[0] . 'x' . getimagesize($fileName_save)[1],
]);
if (!empty($data['title'])) {
$media->title = $data['title'];
}
if (!empty($data['caption'])) {
$media->caption = $data['caption'];
}
if (!empty($data['alt'])) {
$media->alt = $data['alt'];
}
if (!empty($data['description'])) {
$media->description = $data['description'];
}
if (!\Yii::$app->user->isGuest) {
$media->created_by = \Yii::$app->user->id;
}
$media->save();
} | @param $file_name
@param $fileName_save
@param $url
@param array $data
@throws \yii\base\InvalidConfigException | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L85-L110 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.generateThumbnail | public static function generateThumbnail($fileName, $data = [])
{
FileHelper::createDirectory( \Yii::getAlias('@thumbnail') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@thumbnail') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'thumbnail_size_width', 150);
$size_height = get_setting_value('media_configuration', 'thumbnail_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
FileHelper::createDirectory(\Yii::getAlias('@medium') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@medium') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'medium_size_width', 150);
$size_height = get_setting_value('media_configuration', 'medium_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
FileHelper::createDirectory(\Yii::getAlias('@large') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@large') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'large_size_width', 150);
$size_height = get_setting_value('media_configuration', 'large_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
} | php | public static function generateThumbnail($fileName, $data = [])
{
FileHelper::createDirectory( \Yii::getAlias('@thumbnail') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@thumbnail') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'thumbnail_size_width', 150);
$size_height = get_setting_value('media_configuration', 'thumbnail_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
FileHelper::createDirectory(\Yii::getAlias('@medium') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@medium') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'medium_size_width', 150);
$size_height = get_setting_value('media_configuration', 'medium_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
FileHelper::createDirectory(\Yii::getAlias('@large') . '/' . date('Y/m/d'));
$thumbnail_save = \Yii::getAlias('@large') . '/' . $fileName;
$size_width = get_setting_value('media_configuration', 'large_size_width', 150);
$size_height = get_setting_value('media_configuration', 'large_size_height', 150);
Image::getImagine()
->open(self::getFileNameSave($fileName))
->thumbnail(new Box($size_width, $size_height))
->save($thumbnail_save , ['quality' => self::getQualitySetting(50, $data)]);
} | @param $fileName
@param array $data
@throws \yii\base\Exception | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L118-L146 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.doUploadSingle | protected function doUploadSingle($form_name = 'img', $data = [])
{
$this->imageFile = UploadedFile::getInstanceByName($form_name);
$quality = self::getQualitySetting(50, $data);
if ($this->imageFile) {
$fileName = date('Y/m/d') . '/' . date('his') . '-' . $this->imageFile->baseName. '.' . $this->imageFile->extension;
$fileName_save = self::getFileNameSave($fileName);
$this->imageFile->saveAs($fileName_save);
Image::getImagine()->open($fileName_save)->save($fileName_save, ['quality' => $quality]);
self::generateThumbnail($fileName, $data);
$url = 'uploads/' . $fileName;
self::createNewMedia($fileName, $fileName_save, $url, $data);
return $url;
} else {
return null;
}
} | php | protected function doUploadSingle($form_name = 'img', $data = [])
{
$this->imageFile = UploadedFile::getInstanceByName($form_name);
$quality = self::getQualitySetting(50, $data);
if ($this->imageFile) {
$fileName = date('Y/m/d') . '/' . date('his') . '-' . $this->imageFile->baseName. '.' . $this->imageFile->extension;
$fileName_save = self::getFileNameSave($fileName);
$this->imageFile->saveAs($fileName_save);
Image::getImagine()->open($fileName_save)->save($fileName_save, ['quality' => $quality]);
self::generateThumbnail($fileName, $data);
$url = 'uploads/' . $fileName;
self::createNewMedia($fileName, $fileName_save, $url, $data);
return $url;
} else {
return null;
}
} | @param string $form_name
@param array $data
@return null|string
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L156-L172 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.doUploadMultiple | protected function doUploadMultiple($form_name = 'img', $data = [])
{
$this->imageFiles = UploadedFile::getInstancesByName($form_name);
$quality = self::getQualitySetting(50, $data);
if ($this->imageFiles) {
$url = [];
foreach ($this->imageFiles as $file) {
$model = new UploadImgForm();
$model->imageFile = $file;
$fileName = date('Y/m/d') . '/' . date('his') . '-' . $model->imageFile->baseName. '.' . $model->imageFile->extension;
$fileName_save = self::getFileNameSave($fileName);
$model->imageFile->saveAs($fileName_save);
Image::getImagine()->open($fileName_save)->save($fileName_save, ['quality' => $quality]);
self::generateThumbnail($fileName, $data);
$url[] = 'uploads/' . $fileName;
self::createNewMedia($fileName, $fileName_save, 'uploads/' . $fileName, $data);
}
return $url;
} else {
return null;
}
} | php | protected function doUploadMultiple($form_name = 'img', $data = [])
{
$this->imageFiles = UploadedFile::getInstancesByName($form_name);
$quality = self::getQualitySetting(50, $data);
if ($this->imageFiles) {
$url = [];
foreach ($this->imageFiles as $file) {
$model = new UploadImgForm();
$model->imageFile = $file;
$fileName = date('Y/m/d') . '/' . date('his') . '-' . $model->imageFile->baseName. '.' . $model->imageFile->extension;
$fileName_save = self::getFileNameSave($fileName);
$model->imageFile->saveAs($fileName_save);
Image::getImagine()->open($fileName_save)->save($fileName_save, ['quality' => $quality]);
self::generateThumbnail($fileName, $data);
$url[] = 'uploads/' . $fileName;
self::createNewMedia($fileName, $fileName_save, 'uploads/' . $fileName, $data);
}
return $url;
} else {
return null;
}
} | @param string $form_name
@param array $data
@return array|null
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L182-L203 |
thienhungho/yii2-media-management | src/modules/Uploads/UploadImgForm.php | UploadImgForm.upload | public static function upload($form_name = 'img', $multiple = false, $data = [])
{
$model = new UploadImgForm();
if ($multiple == false) {
return $model->doUploadSingle($form_name, $data);
} else {
return $model->doUploadMultiple($form_name, $data);
}
} | php | public static function upload($form_name = 'img', $multiple = false, $data = [])
{
$model = new UploadImgForm();
if ($multiple == false) {
return $model->doUploadSingle($form_name, $data);
} else {
return $model->doUploadMultiple($form_name, $data);
}
} | @param string $form_name
@param bool $multiple
@param array $data
@return array|null|string
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | https://github.com/thienhungho/yii2-media-management/blob/e6107502e2781fc82347141d5e83ac8c119771da/src/modules/Uploads/UploadImgForm.php#L214-L222 |
pmdevelopment/tool-bundle | Twig/TimeExtension.php | TimeExtension.getSecondsAsText | public function getSecondsAsText($seconds, $decimals = 2, $decPoint = ',', $thousandsSep = '.')
{
$seconds = floatval($seconds);
if (60 > $seconds) {
return sprintf('%ss', number_format($seconds, $decimals, $decPoint, $thousandsSep));
}
$minutes = floor($seconds / 60);
if (3600 > $seconds) {
return sprintf('%sm %ss', $minutes, number_format($seconds - ($minutes * 60), 0, $decPoint, $thousandsSep));
}
$hours = floor($minutes / 60);
$minutes = $minutes - ($hours * 60);
return sprintf('%sh %sm %ss', $hours, $minutes, number_format($seconds - ($minutes * 60) - ($hours * 3600), 0, $decPoint, $thousandsSep));
} | php | public function getSecondsAsText($seconds, $decimals = 2, $decPoint = ',', $thousandsSep = '.')
{
$seconds = floatval($seconds);
if (60 > $seconds) {
return sprintf('%ss', number_format($seconds, $decimals, $decPoint, $thousandsSep));
}
$minutes = floor($seconds / 60);
if (3600 > $seconds) {
return sprintf('%sm %ss', $minutes, number_format($seconds - ($minutes * 60), 0, $decPoint, $thousandsSep));
}
$hours = floor($minutes / 60);
$minutes = $minutes - ($hours * 60);
return sprintf('%sh %sm %ss', $hours, $minutes, number_format($seconds - ($minutes * 60) - ($hours * 3600), 0, $decPoint, $thousandsSep));
} | Get Seconds As Text
@param float $seconds
@param int $decimals
@param string $decPoint
@param string $thousandsSep
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/TimeExtension.php#L82-L100 |
pmdevelopment/tool-bundle | Twig/TimeExtension.php | TimeExtension.getSecondsAsTextExtended | public function getSecondsAsTextExtended($seconds)
{
$seconds = floatval($seconds);
$result = [];
$steps = [
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1,
];
foreach ($steps as $stepName => $stepDivider) {
$stepCount = floor($seconds / $stepDivider);
if (0 < $stepCount) {
$result[] = sprintf('%d %s', $stepCount, $this->getTranslator()->transChoice($stepName, $stepCount));
$seconds = $seconds - ($stepCount * $stepDivider);
}
}
return implode(' ', $result);
} | php | public function getSecondsAsTextExtended($seconds)
{
$seconds = floatval($seconds);
$result = [];
$steps = [
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1,
];
foreach ($steps as $stepName => $stepDivider) {
$stepCount = floor($seconds / $stepDivider);
if (0 < $stepCount) {
$result[] = sprintf('%d %s', $stepCount, $this->getTranslator()->transChoice($stepName, $stepCount));
$seconds = $seconds - ($stepCount * $stepDivider);
}
}
return implode(' ', $result);
} | Get Seconds As Text Extended
@param float $seconds
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/TimeExtension.php#L109-L130 |
pmdevelopment/tool-bundle | Twig/TimeExtension.php | TimeExtension.getMinutesAsHours | public function getMinutesAsHours($minutes)
{
$hours = floor($minutes / 60);
$minutes = $minutes - ($hours * 60);
return sprintf('%s:%s', $hours, str_pad($minutes, 2, '0', STR_PAD_LEFT));
} | php | public function getMinutesAsHours($minutes)
{
$hours = floor($minutes / 60);
$minutes = $minutes - ($hours * 60);
return sprintf('%s:%s', $hours, str_pad($minutes, 2, '0', STR_PAD_LEFT));
} | Get Minutes as Minutes (hh:ii)
@param int $minutes
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/TimeExtension.php#L139-L145 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.setMethod | public function setMethod($method)
{
if (!in_array($method, HttpMethods::getValues())) {
throw new Exceptions\InvalidArgumentException(
"Invalid request method."
);
}
$this->method = $method;
return $this;
} | php | public function setMethod($method)
{
if (!in_array($method, HttpMethods::getValues())) {
throw new Exceptions\InvalidArgumentException(
"Invalid request method."
);
}
$this->method = $method;
return $this;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L134-L144 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.addHeader | public function addHeader($header, $value = null)
{
if (null !== $value) {
$this->headers[$header] = $value;
} else {
$this->headers[] = $header;
}
return $this;
} | php | public function addHeader($header, $value = null)
{
if (null !== $value) {
$this->headers[$header] = $value;
} else {
$this->headers[] = $header;
}
return $this;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L158-L167 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.setBasicAuth | public function setBasicAuth($user, $pass)
{
$this->auth["user"] = (string)$user;
$this->auth["pass"] = (string)$pass;
return $this;
} | php | public function setBasicAuth($user, $pass)
{
$this->auth["user"] = (string)$user;
$this->auth["pass"] = (string)$pass;
return $this;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L181-L186 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.request | public function request($url)
{
$this->url = $url;
$this->response = [
"time" => time(),
"method" => $this->method,
"version" => null,
"code" => 0,
"body" => null,
"info" => [],
"headers" => []
];
$this->validate();
$this->prepareCurl();
$this->prepareHeaders();
$this->prepareData();
$this->exec();
$this->complete->invoke();
return new WebResponse($this->response);
} | php | public function request($url)
{
$this->url = $url;
$this->response = [
"time" => time(),
"method" => $this->method,
"version" => null,
"code" => 0,
"body" => null,
"info" => [],
"headers" => []
];
$this->validate();
$this->prepareCurl();
$this->prepareHeaders();
$this->prepareData();
$this->exec();
$this->complete->invoke();
return new WebResponse($this->response);
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L191-L212 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.post | public function post($url, $data)
{
$this->setMethod(HttpMethods::POST);
$this->setData($data);
return $this->request($url);
} | php | public function post($url, $data)
{
$this->setMethod(HttpMethods::POST);
$this->setData($data);
return $this->request($url);
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L226-L231 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.getHeadersParser | public function getHeadersParser()
{
if (null === $this->headersParser) {
$this->headersParser = new Parsers\Headers();
}
return $this->headersParser;
} | php | public function getHeadersParser()
{
if (null === $this->headersParser) {
$this->headersParser = new Parsers\Headers();
}
return $this->headersParser;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L253-L259 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.getHeadersBuilder | public function getHeadersBuilder()
{
if (null === $this->headersBuilder) {
$this->headersBuilder = new Builders\Headers();
}
return $this->headersBuilder;
} | php | public function getHeadersBuilder()
{
if (null === $this->headersBuilder) {
$this->headersBuilder = new Builders\Headers();
}
return $this->headersBuilder;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L273-L279 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.setLogger | public function setLogger(LoggerInterface $logger, $logFormat = self::DEFAULT_LOG_FORMAT)
{
$this->logger = $logger;
$this->logFormat = $logFormat;
return $this;
} | php | public function setLogger(LoggerInterface $logger, $logFormat = self::DEFAULT_LOG_FORMAT)
{
$this->logger = $logger;
$this->logFormat = $logFormat;
return $this;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L284-L290 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.validate | protected function validate()
{
if ($this->method === HttpMethods::POST && empty($this->data)) {
throw new Exceptions\WebException(
"Using method POST without data."
);
}
} | php | protected function validate()
{
if ($this->method === HttpMethods::POST && empty($this->data)) {
throw new Exceptions\WebException(
"Using method POST without data."
);
}
} | Validates the request values for correctness
@throws Exceptions\WebException When an incorrect value is found | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L297-L304 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.prepareCurl | protected function prepareCurl()
{
$this->curl = curl_init();
$this->complete = Complete::factory(function() {
if ($this->curl) {
curl_close($this->curl);
}
$this->curl = null;
$this->complete = null;
});
foreach(self::$curlOptions as $option => $value) {
curl_setopt($this->curl, $option, $value);
}
if ($this->method === HttpMethods::POST) {
curl_setopt($this->curl, CURLOPT_POST, true);
}
if (!empty($this->auth)) {
curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
"%s:%s",
$this->auth["user"],
$this->auth["pass"]
));
}
} | php | protected function prepareCurl()
{
$this->curl = curl_init();
$this->complete = Complete::factory(function() {
if ($this->curl) {
curl_close($this->curl);
}
$this->curl = null;
$this->complete = null;
});
foreach(self::$curlOptions as $option => $value) {
curl_setopt($this->curl, $option, $value);
}
if ($this->method === HttpMethods::POST) {
curl_setopt($this->curl, CURLOPT_POST, true);
}
if (!empty($this->auth)) {
curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
"%s:%s",
$this->auth["user"],
$this->auth["pass"]
));
}
} | Initializes the curl resource | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L309-L333 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.prepareData | protected function prepareData()
{
if (!empty($this->data)) {
if ($this->method === HttpMethods::GET) {
$this->url = Utils::appendUrlQuery($this->url, $this->data);
} else if ($this->method === HttpMethods::POST) {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
}
}
} | php | protected function prepareData()
{
if (!empty($this->data)) {
if ($this->method === HttpMethods::GET) {
$this->url = Utils::appendUrlQuery($this->url, $this->data);
} else if ($this->method === HttpMethods::POST) {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
}
}
} | Adds the data value to the curl request | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L338-L347 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.prepareHeaders | protected function prepareHeaders()
{
// Need to let curl set the content type when posting. Our own content type
// value would overwrite that.
if ($this->method === HttpMethods::POST && !empty($this->headers["Content-Type"])) {
unset($this->headers["Content-Type"]);
}
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->userAgent);
if (!empty($this->headers)) {
$headers = $this->getHeadersBuilder()->normalize($this->headers);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
}
} | php | protected function prepareHeaders()
{
// Need to let curl set the content type when posting. Our own content type
// value would overwrite that.
if ($this->method === HttpMethods::POST && !empty($this->headers["Content-Type"])) {
unset($this->headers["Content-Type"]);
}
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->userAgent);
if (!empty($this->headers)) {
$headers = $this->getHeadersBuilder()->normalize($this->headers);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
}
} | Adds the set headers to the curl request | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L352-L365 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.exec | protected function exec()
{
curl_setopt($this->curl, CURLOPT_URL, $this->url);
$response_text = curl_exec($this->curl);
$this->info = curl_getinfo($this->curl);
$this->logInformation();
if (false === $response_text) {
throw new Exceptions\WebException(
curl_error($this->curl),
curl_errno($this->curl)
);
}
/** @var $options string */
$this->response["info"] = $this->info;
$this->response["code"] = $this->response["info"]["http_code"];
$this->response["body"] = substr(
$response_text,
$this->response["info"]["header_size"]
);
$this->response["headers"] = substr(
$response_text,
0,
$this->response["info"]["header_size"]
);
$this->response["headers"] = $this->getHeadersParser()->parse(
$this->response["headers"],
$options
);
$this->response["version"] = explode(" ", $options, 3)[0];
} | php | protected function exec()
{
curl_setopt($this->curl, CURLOPT_URL, $this->url);
$response_text = curl_exec($this->curl);
$this->info = curl_getinfo($this->curl);
$this->logInformation();
if (false === $response_text) {
throw new Exceptions\WebException(
curl_error($this->curl),
curl_errno($this->curl)
);
}
/** @var $options string */
$this->response["info"] = $this->info;
$this->response["code"] = $this->response["info"]["http_code"];
$this->response["body"] = substr(
$response_text,
$this->response["info"]["header_size"]
);
$this->response["headers"] = substr(
$response_text,
0,
$this->response["info"]["header_size"]
);
$this->response["headers"] = $this->getHeadersParser()->parse(
$this->response["headers"],
$options
);
$this->response["version"] = explode(" ", $options, 3)[0];
} | Executes the configured request | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L370-L401 |
headzoo/web-tools | src/Headzoo/Web/Tools/WebClient.php | WebClient.logInformation | protected function logInformation()
{
if ($this->logger) {
$level = $this->info["http_code"] > 0 && $this->info["http_code"] < 400
? LogLevel::INFO
: LogLevel::ERROR;
$this->info["method"] = $this->method;
$this->logger->log($level, $this->logFormat, $this->info);
}
} | php | protected function logInformation()
{
if ($this->logger) {
$level = $this->info["http_code"] > 0 && $this->info["http_code"] < 400
? LogLevel::INFO
: LogLevel::ERROR;
$this->info["method"] = $this->method;
$this->logger->log($level, $this->logFormat, $this->info);
}
} | Logs request information when logging is enabled | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/WebClient.php#L406-L415 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.Allow | public function Allow ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
$this->allowIPs[$formatted[0]] = $formatted[1];
return TRUE;
} | php | public function Allow ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
$this->allowIPs[$formatted[0]] = $formatted[1];
return TRUE;
} | Add an IP address range to allow
Return FALSE is the IP range is invalid
@see formatRange ()
@param string $range IP range to allow
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L37-L50 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.Deny | public function Deny ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
$this->denyIPs[$formatted[0]] = $formatted[1];
return TRUE;
} | php | public function Deny ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
$this->denyIPs[$formatted[0]] = $formatted[1];
return TRUE;
} | Add an IP address range to deny
Return FALSE is the IP range is invalid
@see formatRange ()
@param string $range IP range to deny
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L61-L74 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.removeAllowed | public function removeAllowed ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
unset ($this->allowIPs[$formatted[0]]);
return TRUE;
} | php | public function removeAllowed ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
unset ($this->allowIPs[$formatted[0]]);
return TRUE;
} | Remove an allowed IP address range
Return FALSE is the IP range is invalid
@param string $range IP range to remove
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L84-L97 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.removeDenied | public function removeDenied ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
unset ($this->denyIPs[$formatted[0]]);
return TRUE;
} | php | public function removeDenied ($range)
{
$formatted = $this->formatRange ($range);
if (!$formatted)
{
return FALSE;
}
unset ($this->denyIPs[$formatted[0]]);
return TRUE;
} | Remove a denied IP address range
Return FALSE is the IP range is invalid
@param string $range IP range to remove
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L107-L120 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.formatRange | public function formatRange ($range)
{
// CIDR
if (strpos ($range, '/') !== FALSE)
{
// Get the IP and netmask
list ($ip, $netmask) = explode ('/', $range, 2);
// Split decimal and pad to ensure we have 4 octets
$ip = implode ('.', array_pad (explode ('.', $ip), 4, 0));
// If the netmask is a dotted decimal format
if (strpos ($netmask, '.') !== FALSE)
{
// Convert wildcards
$netmask = str_replace ('*', '0', $netmask);
// Convert to long
$ipLong = ip2long ($ip);
$netmaskLong = ip2long ($netmask);
// Check IPs are valid
if ($ipLong === FALSE || $netmaskLong === FALSE)
{
return FALSE;
}
// Return range
return array (
$ip . '/' . $netmask,
array (
(float)sprintf ("%u", $ipLong),
(float)sprintf ("%u", $netmaskLong)
)
);
}
// Else netmask is a CIDR block
else
{
// Convert netmask block to bit-mask
// Bitwise NOT on wildcard
$wildcard = pow (2, (32 - (int)$netmask)) - 1;
$netmaskDec = ~$wildcard;
// Return range
return array (
$ip . '/' . $netmask,
array (
(float)sprintf ("%u", ip2long ($ip)),
$netmaskDec
)
);
}
// Return TRUE
return TRUE;
}
// Wildcard or Start-End
elseif (strpos ($range, '*') !== FALSE || strpos ($range, '-') !== FALSE)
{
// Wildcard
if (strpos ($range, '*') !== FALSE)
{
$lower = str_replace ('*', '0', $range);
$upper = str_replace ('*', '255', $range);
$name = $lower . '-' . $upper;
}
// Start-End
else
{
list ($lower, $upper) = explode ('-', $range, 2);
$name = $range;
}
// Convert to long
$lowerLong = ip2long ($lower);
$upperLong = ip2long ($upper);
// Check IPs are valid
if ($lowerLong === FALSE || $upperLong === FALSE)
{
return FALSE;
}
// Return range
return array (
$name,
array (
(float)sprintf ("%u", $lowerLong),
(float)sprintf ("%u", $upperLong)
)
);
}
// Else a single IP
if (strpos ($range, '.') !== FALSE)
{
// Return range
return array (
$range,
(float)sprintf ("%u", ip2long ($range))
);
}
// No range to return
return FALSE;
} | php | public function formatRange ($range)
{
// CIDR
if (strpos ($range, '/') !== FALSE)
{
// Get the IP and netmask
list ($ip, $netmask) = explode ('/', $range, 2);
// Split decimal and pad to ensure we have 4 octets
$ip = implode ('.', array_pad (explode ('.', $ip), 4, 0));
// If the netmask is a dotted decimal format
if (strpos ($netmask, '.') !== FALSE)
{
// Convert wildcards
$netmask = str_replace ('*', '0', $netmask);
// Convert to long
$ipLong = ip2long ($ip);
$netmaskLong = ip2long ($netmask);
// Check IPs are valid
if ($ipLong === FALSE || $netmaskLong === FALSE)
{
return FALSE;
}
// Return range
return array (
$ip . '/' . $netmask,
array (
(float)sprintf ("%u", $ipLong),
(float)sprintf ("%u", $netmaskLong)
)
);
}
// Else netmask is a CIDR block
else
{
// Convert netmask block to bit-mask
// Bitwise NOT on wildcard
$wildcard = pow (2, (32 - (int)$netmask)) - 1;
$netmaskDec = ~$wildcard;
// Return range
return array (
$ip . '/' . $netmask,
array (
(float)sprintf ("%u", ip2long ($ip)),
$netmaskDec
)
);
}
// Return TRUE
return TRUE;
}
// Wildcard or Start-End
elseif (strpos ($range, '*') !== FALSE || strpos ($range, '-') !== FALSE)
{
// Wildcard
if (strpos ($range, '*') !== FALSE)
{
$lower = str_replace ('*', '0', $range);
$upper = str_replace ('*', '255', $range);
$name = $lower . '-' . $upper;
}
// Start-End
else
{
list ($lower, $upper) = explode ('-', $range, 2);
$name = $range;
}
// Convert to long
$lowerLong = ip2long ($lower);
$upperLong = ip2long ($upper);
// Check IPs are valid
if ($lowerLong === FALSE || $upperLong === FALSE)
{
return FALSE;
}
// Return range
return array (
$name,
array (
(float)sprintf ("%u", $lowerLong),
(float)sprintf ("%u", $upperLong)
)
);
}
// Else a single IP
if (strpos ($range, '.') !== FALSE)
{
// Return range
return array (
$range,
(float)sprintf ("%u", ip2long ($range))
);
}
// No range to return
return FALSE;
} | Format an IP address range
Valid IP ranges can be:
Single: 192.168.1.1
CIDR: 192.168.1/24, 192.168.1.0/24 or 192.168.1.0/255.255.255.0
Wildcard: 192.168.1.*
Start-End: 192.168.1.0-192.168.1.255
@param string $range Valid IP range
@return FALSE|array (name, range) | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L182-L325 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.isInside | protected function isInside ($ip, $name, $range)
{
// Single IP
if (!is_array ($range))
{
if ($ip == $range)
{
return TRUE;
}
}
// CIDR
elseif (strpos ($name, '/') !== FALSE)
{
if (($ip & $range[1]) == ($range[0] & $range[1]))
{
return TRUE;
}
}
// Start-End
elseif (strpos ($name, '-') !== FALSE)
{
if (($ip >= $range[0]) && ($ip <= $range[1]))
{
return TRUE;
}
}
// Not inside any range
return FALSE;
} | php | protected function isInside ($ip, $name, $range)
{
// Single IP
if (!is_array ($range))
{
if ($ip == $range)
{
return TRUE;
}
}
// CIDR
elseif (strpos ($name, '/') !== FALSE)
{
if (($ip & $range[1]) == ($range[0] & $range[1]))
{
return TRUE;
}
}
// Start-End
elseif (strpos ($name, '-') !== FALSE)
{
if (($ip >= $range[0]) && ($ip <= $range[1]))
{
return TRUE;
}
}
// Not inside any range
return FALSE;
} | Return whether an IP is inside a range
@param intger $ip IP decimal to check
@param string $name IP Range name
@param string|array $range Valid IP range
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L336-L373 |
andyburton/Sonic-Framework | src/Resource/IP.php | IP.isAllowed | public function isAllowed ($ip, $priority = 'deny,allow')
{
// Convert IP to decimal
$ipDec = (float)sprintf ("%u", ip2long ($ip));
// Check
foreach (explode (',', $priority) as $type)
{
switch ($type)
{
// Check if the IP is allowed
case 'allow':
foreach ($this->allowIPs as $name => $range)
{
if ($this->isInside ($ipDec, $name, $range))
{
return TRUE;
}
}
break;
// Check if IP is denied
case 'deny':
foreach ($this->denyIPs as $name => $range)
{
if ($this->isInside ($ipDec, $name, $range))
{
return FALSE;
}
}
break;
}
}
// Not allowed by default
return FALSE;
} | php | public function isAllowed ($ip, $priority = 'deny,allow')
{
// Convert IP to decimal
$ipDec = (float)sprintf ("%u", ip2long ($ip));
// Check
foreach (explode (',', $priority) as $type)
{
switch ($type)
{
// Check if the IP is allowed
case 'allow':
foreach ($this->allowIPs as $name => $range)
{
if ($this->isInside ($ipDec, $name, $range))
{
return TRUE;
}
}
break;
// Check if IP is denied
case 'deny':
foreach ($this->denyIPs as $name => $range)
{
if ($this->isInside ($ipDec, $name, $range))
{
return FALSE;
}
}
break;
}
}
// Not allowed by default
return FALSE;
} | Return whether an IP is allowed
@param string $ip IPv4 address
@param string $priority Order priority, default deny,allow
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/IP.php#L383-L434 |
cothema/cmsbe | src/presenters/BasePresenter.php | BasePresenter.checkRequirements | public function checkRequirements($element)
{
try {
parent::checkRequirements($element);
if (!$this->requirementsChecker->isAllowed($element)) {
throw new Application\ForbiddenRequestException;
}
} catch (Application\ForbiddenRequestException $e) {
$this->flashMessage('Pro vstup do požadované sekce musíte být přihlášen/a s příslušným oprávněním.');
if (!$this->user->isLoggedIn()) {
$this->redirect(
'Sign:in',
['backSignInUrl' => $this->getHttpRequest()->url->path]
);
} elseif (!$this->isLinkCurrent('Homepage:')) {
$this->redirect('Homepage:');
} else {
$this->redirect('Sign:in');
}
}
} | php | public function checkRequirements($element)
{
try {
parent::checkRequirements($element);
if (!$this->requirementsChecker->isAllowed($element)) {
throw new Application\ForbiddenRequestException;
}
} catch (Application\ForbiddenRequestException $e) {
$this->flashMessage('Pro vstup do požadované sekce musíte být přihlášen/a s příslušným oprávněním.');
if (!$this->user->isLoggedIn()) {
$this->redirect(
'Sign:in',
['backSignInUrl' => $this->getHttpRequest()->url->path]
);
} elseif (!$this->isLinkCurrent('Homepage:')) {
$this->redirect('Homepage:');
} else {
$this->redirect('Sign:in');
}
}
} | Checks authorization.
@param string $element
@return void
@throws Application\ForbiddenRequestException | https://github.com/cothema/cmsbe/blob/a5e162d421f6c52382d658891ee5b01e7bc6c7db/src/presenters/BasePresenter.php#L49-L71 |
cothema/cmsbe | src/presenters/BasePresenter.php | BasePresenter.getActualUserFromDb | private function getActualUserFromDb()
{
$dao = $this->em->getRepository(CModel\User\User::class);
return $dao->find($this->getUser()->id);
} | php | private function getActualUserFromDb()
{
$dao = $this->em->getRepository(CModel\User\User::class);
return $dao->find($this->getUser()->id);
} | /*
@param mixed $role if array = OR (one of) | https://github.com/cothema/cmsbe/blob/a5e162d421f6c52382d658891ee5b01e7bc6c7db/src/presenters/BasePresenter.php#L637-L641 |
alphacomm/alpharpc | src/AlphaRPC/Console/Command/WorkerStatus.php | WorkerStatus.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$full = $input->getOption('full');
$this->output = $output;
$this->output->writeln('');
try {
$status = $this->getStatus();
$this->row('Worker', 'Service', 'Current Service', 'Ready', 'Valid');
foreach ($status as $worker) {
$actions = $worker['actionList'];
$this->row(
bin2hex($worker['id']),
array_shift($actions),
$worker['current'],
$worker['ready'] ? 'yes' : 'no',
$worker['valid'] ? 'yes' : 'no'
);
$i = 0;
while (count($actions) > 0 && ($i < 3 || $full)) {
$i++;
$this->row('', array_shift($actions), '', '', '');
}
if (count($actions) > 0) {
$this->row('', '... and '.count($actions).' other services.', '', '', '');
}
}
} catch (\Exception $e) {
$this->output->writeln('<error>An error occured: '.$e->getMessage().'</error>');
}
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$full = $input->getOption('full');
$this->output = $output;
$this->output->writeln('');
try {
$status = $this->getStatus();
$this->row('Worker', 'Service', 'Current Service', 'Ready', 'Valid');
foreach ($status as $worker) {
$actions = $worker['actionList'];
$this->row(
bin2hex($worker['id']),
array_shift($actions),
$worker['current'],
$worker['ready'] ? 'yes' : 'no',
$worker['valid'] ? 'yes' : 'no'
);
$i = 0;
while (count($actions) > 0 && ($i < 3 || $full)) {
$i++;
$this->row('', array_shift($actions), '', '', '');
}
if (count($actions) > 0) {
$this->row('', '... and '.count($actions).' other services.', '', '', '');
}
}
} catch (\Exception $e) {
$this->output->writeln('<error>An error occured: '.$e->getMessage().'</error>');
}
} | {@inheritdoc} | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Console/Command/WorkerStatus.php#L65-L98 |
alphacomm/alpharpc | src/AlphaRPC/Console/Command/WorkerStatus.php | WorkerStatus.row | protected function row($worker, $service, $current, $ready, $valid)
{
$mask = "| %-10.10s | %-40.40s | %-40.40s | %-5s | %-5s |";
$text = sprintf($mask, $worker, $service, $current, $ready, $valid);
$this->output->writeln($text);
} | php | protected function row($worker, $service, $current, $ready, $valid)
{
$mask = "| %-10.10s | %-40.40s | %-40.40s | %-5s | %-5s |";
$text = sprintf($mask, $worker, $service, $current, $ready, $valid);
$this->output->writeln($text);
} | Print a single line with information.
@param $worker
@param $service
@param $current
@param $ready
@param $valid | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Console/Command/WorkerStatus.php#L120-L125 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.getPatients | public static function getPatients($month = null, $day = null, $wardId = 0) {
return PatientCRUD::getPatientsDateRange ( Utils::getStartDate ( $month, $day ), Utils::getEndDate ( $month, $day ), $wardId );
} | php | public static function getPatients($month = null, $day = null, $wardId = 0) {
return PatientCRUD::getPatientsDateRange ( Utils::getStartDate ( $month, $day ), Utils::getEndDate ( $month, $day ), $wardId );
} | getPatients
@param int $day
dayOfTheMonth
@param int $month
month
@return Patient array | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L45-L47 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.getPatientsDateRange | public static function getPatientsDateRange($date1, $date2, $wardId = 0) {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$params = array (
'from' => $date1,
'to' => $date2,
'oddzialId' => $wardId
);
$q = $entityManager->createQuery ( 'select p FROM Hospitalplugin\Entities\Patient p WHERE p.dataKategoryzacji BETWEEN :from AND :to and p.oddzialId = :oddzialId ORDER BY p.name' )->setParameters ( $params )->setFirstResult ( 0 )->setMaxResults ( 1000 );
$patients = $q->getResult ();
return $patients;
} | php | public static function getPatientsDateRange($date1, $date2, $wardId = 0) {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$params = array (
'from' => $date1,
'to' => $date2,
'oddzialId' => $wardId
);
$q = $entityManager->createQuery ( 'select p FROM Hospitalplugin\Entities\Patient p WHERE p.dataKategoryzacji BETWEEN :from AND :to and p.oddzialId = :oddzialId ORDER BY p.name' )->setParameters ( $params )->setFirstResult ( 0 )->setMaxResults ( 1000 );
$patients = $q->getResult ();
return $patients;
} | getPatientsDateRange
TODO(AM) testy na przypadki graniczne - pacjenci z data przed polnoca, po polnocy, godzina przed obecna, po obecnej
@param int $day
dayOfTheMonth
@param int $month
month
@return Patient array | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L61-L71 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.getPatient | public static function getPatient($id, $type = '') {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient' . $type;
$patient = $entityManager->getRepository ( $type )->findOneBy ( array (
'id' => $id
) );
return Utils::cast ( $type, ( object ) $patient, 0 );
} | php | public static function getPatient($id, $type = '') {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient' . $type;
$patient = $entityManager->getRepository ( $type )->findOneBy ( array (
'id' => $id
) );
return Utils::cast ( $type, ( object ) $patient, 0 );
} | getPatient
@param $id $id
int
@return Patient Patient | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L81-L88 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.setPatientCategories | public static function setPatientCategories($obj, $type) {
$entityManager = DoctrineBootstrap::getEntityManager ();
$patient = PatientCRUD::getPatient ( $obj->id, $type );
foreach ( get_object_vars ( $obj ) as $key => $value ) {
call_user_func ( array (
$patient,
'set' . ucwords ( $key )
), $value );
}
$entityManager->merge ( $patient );
$entityManager->flush ();
return $patient;
} | php | public static function setPatientCategories($obj, $type) {
$entityManager = DoctrineBootstrap::getEntityManager ();
$patient = PatientCRUD::getPatient ( $obj->id, $type );
foreach ( get_object_vars ( $obj ) as $key => $value ) {
call_user_func ( array (
$patient,
'set' . ucwords ( $key )
), $value );
}
$entityManager->merge ( $patient );
$entityManager->flush ();
return $patient;
} | setPatientCategories
@param Patient $obj
@return Patient | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L97-L109 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.createPatient | public static function createPatient($type, $name, $pesel) {
$entityManager = DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient' . $type;
$patient = new $type ();
$patient->setName ( $name );
$patient->setPesel ( $pesel );
$entityManager->persist ( $patient );
$entityManager->flush ();
return $patient;
} | php | public static function createPatient($type, $name, $pesel) {
$entityManager = DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient' . $type;
$patient = new $type ();
$patient->setName ( $name );
$patient->setPesel ( $pesel );
$entityManager->persist ( $patient );
$entityManager->flush ();
return $patient;
} | setPatientCategories
@param Patient $obj
@return Patient | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L118-L127 |
amarcinkowski/hospitalplugin | src/Entities/PatientCRUD.php | PatientCRUD.deletePatient | public static function deletePatient($id, $userId = 0) {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient';
$patient = $entityManager->getRepository ( $type )->findOneBy ( array (
'id' => $id
) );
$entityManager->remove ( $patient );
$log = strval($patient);
$audit = new PatientDeleted();
$audit->deletedAt = new \DateTime ();
$audit->deletedByUserId = $userId;
$audit->log = $log;
$entityManager->persist ( $audit );
$entityManager->flush ();
} | php | public static function deletePatient($id, $userId = 0) {
$entityManager = ( object ) DoctrineBootstrap::getEntityManager ();
$type = 'Hospitalplugin\Entities\Patient';
$patient = $entityManager->getRepository ( $type )->findOneBy ( array (
'id' => $id
) );
$entityManager->remove ( $patient );
$log = strval($patient);
$audit = new PatientDeleted();
$audit->deletedAt = new \DateTime ();
$audit->deletedByUserId = $userId;
$audit->log = $log;
$entityManager->persist ( $audit );
$entityManager->flush ();
} | deletePatient
@param $id $id
int | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/PatientCRUD.php#L135-L149 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.parseValidKeys | protected static function parseValidKeys()
{
if (self::$validOptions !== null) {
return;
}
$refl = new ReflectionClass('\ZMQ');
$const = $refl->getConstants();
self::$validOptions = array();
foreach ($const as $key => $value) {
if (substr($key, 0, 8) == 'SOCKOPT_') {
self::$validOptions[$value] = '\ZMQ::'.$key;
}
}
} | php | protected static function parseValidKeys()
{
if (self::$validOptions !== null) {
return;
}
$refl = new ReflectionClass('\ZMQ');
$const = $refl->getConstants();
self::$validOptions = array();
foreach ($const as $key => $value) {
if (substr($key, 0, 8) == 'SOCKOPT_') {
self::$validOptions[$value] = '\ZMQ::'.$key;
}
}
} | Fills the attribute validOptions containing a list of options that
can be set.
@return null | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L73-L87 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.isOptionKeyValid | public function isOptionKeyValid($key)
{
self::parseValidKeys();
if (isset(self::$validOptions[$key])) {
return true;
}
return false;
} | php | public function isOptionKeyValid($key)
{
self::parseValidKeys();
if (isset(self::$validOptions[$key])) {
return true;
}
return false;
} | Checks if the given option key is valid for ZMQ.
@param mixed $key
@return boolean | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L96-L105 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.addOption | public function addOption($key, $value)
{
if (!$this->isOptionKeyValid($key)) {
throw new \RuntimeException('Invalid socket option '.$key.'.');
}
$this->options[$key] = $value;
return $this;
} | php | public function addOption($key, $value)
{
if (!$this->isOptionKeyValid($key)) {
throw new \RuntimeException('Invalid socket option '.$key.'.');
}
$this->options[$key] = $value;
return $this;
} | Overrides a default ZMQ option.
@param int $key
@param mixed $value
@return \AlphaRPC\Common\Socket\Factory
@throws \RuntimeException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L116-L125 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.addOptions | public function addOptions($options)
{
foreach ($options as $key => $value) {
$this->addOption($key, $value);
}
return $this;
} | php | public function addOptions($options)
{
foreach ($options as $key => $value) {
$this->addOption($key, $value);
}
return $this;
} | Adds ZMQ socket options.
@param array $options
@return \AlphaRPC\Common\Socket\Factory
@throws \RuntimeException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L135-L142 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createPublisher | public function createPublisher($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_PUB, $mode, $dsn, $options);
} | php | public function createPublisher($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_PUB, $mode, $dsn, $options);
} | Creates a publiser socket.
@param string $mode
@param string|array $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L167-L170 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createSubscriber | public function createSubscriber($mode, $dsn = null, $subscribe = '', $options = array())
{
$options[ZMQ::SOCKOPT_SUBSCRIBE] = $subscribe;
return $this->createSocket(ZMQ::SOCKET_SUB, $mode, $dsn, $options);
} | php | public function createSubscriber($mode, $dsn = null, $subscribe = '', $options = array())
{
$options[ZMQ::SOCKOPT_SUBSCRIBE] = $subscribe;
return $this->createSocket(ZMQ::SOCKET_SUB, $mode, $dsn, $options);
} | Creates a subscriber socket.
@param string $mode
@param string $subscribe
@param string|array $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L182-L187 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createRequest | public function createRequest($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_REQ, $mode, $dsn, $options);
} | php | public function createRequest($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_REQ, $mode, $dsn, $options);
} | Creates a request socket.
@param string $mode
@param string|array $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L198-L201 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createReply | public function createReply($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_REP, $mode, $dsn, $options);
} | php | public function createReply($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_REP, $mode, $dsn, $options);
} | Creates a reply socket.
@param string $mode
@param string|array $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L212-L215 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createRouter | public function createRouter($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_ROUTER, $mode, $dsn, $options);
} | php | public function createRouter($mode, $dsn = null, $options = array())
{
return $this->createSocket(ZMQ::SOCKET_ROUTER, $mode, $dsn, $options);
} | Creates a router socket.
@param string $mode
@param string|array $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L226-L229 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.createSocket | protected function createSocket($type, $mode, $dsn = null, $options = array())
{
$context = $this->getContext();
$socket = new Socket($context, $type);
$options = $this->options + $options;
foreach ($options as $key => $value) {
$socket->setSockOpt($key, $value);
}
$this->connect($socket, $mode, $dsn);
return $socket;
} | php | protected function createSocket($type, $mode, $dsn = null, $options = array())
{
$context = $this->getContext();
$socket = new Socket($context, $type);
$options = $this->options + $options;
foreach ($options as $key => $value) {
$socket->setSockOpt($key, $value);
}
$this->connect($socket, $mode, $dsn);
return $socket;
} | Creates a socket.
@param int $type
@param string $mode
@param string $dsn
@param array $options
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L241-L254 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Factory.php | Factory.connect | public function connect(ZMQSocket $socket, $mode, $dsn)
{
if ($mode == self::MODE_CONSTRUCT) {
return $this;
}
$func = null;
if ($mode == self::MODE_BIND) {
$func = 'bind';
} elseif ($mode == self::MODE_CONNECT) {
$func = 'connect';
}
if (is_string($dsn)) {
$dsn = array($dsn);
}
if (!is_array($dsn)) {
throw new \RuntimeException('DSN should be a string or an array.');
}
foreach ($dsn as $d) {
if (!is_string($d)) {
throw new \RuntimeException('Non-string in DSN array detected.');
}
$socket->$func($d);
}
} | php | public function connect(ZMQSocket $socket, $mode, $dsn)
{
if ($mode == self::MODE_CONSTRUCT) {
return $this;
}
$func = null;
if ($mode == self::MODE_BIND) {
$func = 'bind';
} elseif ($mode == self::MODE_CONNECT) {
$func = 'connect';
}
if (is_string($dsn)) {
$dsn = array($dsn);
}
if (!is_array($dsn)) {
throw new \RuntimeException('DSN should be a string or an array.');
}
foreach ($dsn as $d) {
if (!is_string($d)) {
throw new \RuntimeException('Non-string in DSN array detected.');
}
$socket->$func($d);
}
} | Connects or binds a socket based on mode.
@param ZMQSocket $socket
@param string $mode
@param string|array $dsn
@return \AlphaRPC\Common\Socket\Factory
@throws \RuntimeException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Factory.php#L266-L293 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.findRecord | public function findRecord($typeKey, $identifier, array $fields = [], array $inclusions = [])
{
$model = $this->getStore()->find($typeKey, $identifier);
$payload = $this->serialize($model);
return $this->createRestResponse(200, $payload);
} | php | public function findRecord($typeKey, $identifier, array $fields = [], array $inclusions = [])
{
$model = $this->getStore()->find($typeKey, $identifier);
$payload = $this->serialize($model);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L78-L83 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.findAll | public function findAll($typeKey, array $identifiers = [], array $fields = [], array $sort = [], array $pagination = [], array $inclusions = [])
{
$collection = $this->getStore()->findAll($typeKey, $identifiers, $fields, $sort, $pagination['offset'], $pagination['limit']);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | php | public function findAll($typeKey, array $identifiers = [], array $fields = [], array $sort = [], array $pagination = [], array $inclusions = [])
{
$collection = $this->getStore()->findAll($typeKey, $identifiers, $fields, $sort, $pagination['offset'], $pagination['limit']);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L88-L93 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.findQuery | public function findQuery($typeKey, array $criteria, array $fields = [], array $sort = [], array $pagination = [], array $inclusions = [])
{
$collection = $this->getStore()->findQuery($typeKey, $criteria, $fields, $sort, $pagination['offset'], $pagination['limit']);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | php | public function findQuery($typeKey, array $criteria, array $fields = [], array $sort = [], array $pagination = [], array $inclusions = [])
{
$collection = $this->getStore()->findQuery($typeKey, $criteria, $fields, $sort, $pagination['offset'], $pagination['limit']);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L98-L103 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.findRelationship | public function findRelationship($typeKey, $identifier, $fieldKey)
{
$model = $this->getStore()->find($typeKey, $identifier);
if (false === $model->isRelationship($fieldKey)) {
throw AdapterException::badRequest(sprintf('The relationship field "%s" does not exist on model "%s"', $fieldKey, $typeKey));
}
$rel = $model->get($fieldKey);
$payload = (true === $model->isHasOne($fieldKey)) ? $this->serialize($rel) : $this->serializeArray($rel);
return $this->createRestResponse(200, $payload);
} | php | public function findRelationship($typeKey, $identifier, $fieldKey)
{
$model = $this->getStore()->find($typeKey, $identifier);
if (false === $model->isRelationship($fieldKey)) {
throw AdapterException::badRequest(sprintf('The relationship field "%s" does not exist on model "%s"', $fieldKey, $typeKey));
}
$rel = $model->get($fieldKey);
$payload = (true === $model->isHasOne($fieldKey)) ? $this->serialize($rel) : $this->serializeArray($rel);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L108-L117 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.createRecord | public function createRecord($typeKey, Rest\RestPayload $payload) //, array $fields = [], array $inclusions = [])
{
$normalized = $this->normalize($payload);
$this->validateCreatePayload($typeKey, $normalized);
$model = $this->getStore()->create($normalized['type']);
$model->apply($normalized['properties']);
$model->save();
$payload = $this->serialize($model);
return $this->createRestResponse(201, $payload);
} | php | public function createRecord($typeKey, Rest\RestPayload $payload) //, array $fields = [], array $inclusions = [])
{
$normalized = $this->normalize($payload);
$this->validateCreatePayload($typeKey, $normalized);
$model = $this->getStore()->create($normalized['type']);
$model->apply($normalized['properties']);
$model->save();
$payload = $this->serialize($model);
return $this->createRestResponse(201, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L122-L132 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.updateRecord | public function updateRecord($typeKey, $identifier, Rest\RestPayload $payload) // , array $fields = [], array $inclusions = [])
{
$normalized = $this->normalize($payload);
$this->validateUpdatePayload($typeKey, $identifier, $normalized);
$model = $this->getStore()->find($typeKey, $normalized['id']);
$model->apply($normalized['properties']);
$model->save();
$payload = $this->serialize($model);
return $this->createRestResponse(200, $payload);
} | php | public function updateRecord($typeKey, $identifier, Rest\RestPayload $payload) // , array $fields = [], array $inclusions = [])
{
$normalized = $this->normalize($payload);
$this->validateUpdatePayload($typeKey, $identifier, $normalized);
$model = $this->getStore()->find($typeKey, $normalized['id']);
$model->apply($normalized['properties']);
$model->save();
$payload = $this->serialize($model);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L137-L147 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.deleteRecord | public function deleteRecord($typeKey, $identifier)
{
$this->getStore()->delete($typeKey, $identifier);
return $this->createRestResponse(204);
} | php | public function deleteRecord($typeKey, $identifier)
{
$this->getStore()->delete($typeKey, $identifier);
return $this->createRestResponse(204);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L152-L156 |
as3io/modlr | src/Api/AbstractAdapter.php | AbstractAdapter.autocomplete | public function autocomplete($typeKey, $attributeKey, $searchValue, array $pagination = [])
{
$collection = $this->getStore()->searchAutocomplete($typeKey, $attributeKey, $searchValue);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | php | public function autocomplete($typeKey, $attributeKey, $searchValue, array $pagination = [])
{
$collection = $this->getStore()->searchAutocomplete($typeKey, $attributeKey, $searchValue);
$payload = $this->serializeCollection($collection);
return $this->createRestResponse(200, $payload);
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Api/AbstractAdapter.php#L161-L166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.