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
|
---|---|---|---|---|---|---|---|
bruno-barros/w.eloquent-framework | src/weloquent/Support/Breadcrumb.php | Breadcrumb.getCurrentTaxonomy | protected function getCurrentTaxonomy()
{
if (!isset($this->args['taxonomies']) || empty($this->args['taxonomies']))
{
$this->args['taxonomies'] = $this->getDefaultTaxonomies();
}
foreach ($this->args['taxonomies'] as $tax)
{
if ($tax = get_term_by('slug', get_query_var($tax), $tax))
{
return $tax;
break;
}
}
return null;
} | php | protected function getCurrentTaxonomy()
{
if (!isset($this->args['taxonomies']) || empty($this->args['taxonomies']))
{
$this->args['taxonomies'] = $this->getDefaultTaxonomies();
}
foreach ($this->args['taxonomies'] as $tax)
{
if ($tax = get_term_by('slug', get_query_var($tax), $tax))
{
return $tax;
break;
}
}
return null;
} | Find a custom taxonomy
@return mixed|null | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Breadcrumb.php#L217-L234 |
bruno-barros/w.eloquent-framework | src/weloquent/Support/Breadcrumb.php | Breadcrumb.getOverloaded | protected function getOverloaded($postType)
{
if (!isset($this->args['overload'][$postType]))
{
return null;
}
return $this->args['overload'][$postType];
} | php | protected function getOverloaded($postType)
{
if (!isset($this->args['overload'][$postType]))
{
return null;
}
return $this->args['overload'][$postType];
} | return the fake post type
@param $postType
@return null | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Breadcrumb.php#L242-L250 |
fxpio/fxp-doctrine-console | Adapter/ServiceManagerAdapter.php | ServiceManagerAdapter.create | public function create($instance)
{
$this->validate('create');
$this->validateObject($instance);
$this->manager->{$this->createMethod}($instance);
} | php | public function create($instance)
{
$this->validate('create');
$this->validateObject($instance);
$this->manager->{$this->createMethod}($instance);
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L99-L104 |
fxpio/fxp-doctrine-console | Adapter/ServiceManagerAdapter.php | ServiceManagerAdapter.get | public function get($identifier)
{
$this->validate('get');
$instance = $this->manager->{$this->getMethod}([$this->getIdentifierField() => $identifier]);
if (null === $instance) {
throw new \InvalidArgumentException(sprintf('The %s with the identifier "%s" does not exist', $this->getShortName(), $identifier));
}
return $instance;
} | php | public function get($identifier)
{
$this->validate('get');
$instance = $this->manager->{$this->getMethod}([$this->getIdentifierField() => $identifier]);
if (null === $instance) {
throw new \InvalidArgumentException(sprintf('The %s with the identifier "%s" does not exist', $this->getShortName(), $identifier));
}
return $instance;
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L109-L120 |
fxpio/fxp-doctrine-console | Adapter/ServiceManagerAdapter.php | ServiceManagerAdapter.update | public function update($instance)
{
$this->validate('update');
$this->validateObject($instance);
$this->manager->{$this->updateMethod}($instance);
} | php | public function update($instance)
{
$this->validate('update');
$this->validateObject($instance);
$this->manager->{$this->updateMethod}($instance);
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L125-L130 |
fxpio/fxp-doctrine-console | Adapter/ServiceManagerAdapter.php | ServiceManagerAdapter.validate | private function validate($method)
{
$actionMethod = $method.'Method';
$ref = new \ReflectionClass($this->manager);
if (null === $this->$actionMethod || !$ref->hasMethod($this->$actionMethod)) {
throw new \RuntimeException(sprintf('The "%s" method for "%s" adapter is does not supported', $method, $this->getClass()));
}
} | php | private function validate($method)
{
$actionMethod = $method.'Method';
$ref = new \ReflectionClass($this->manager);
if (null === $this->$actionMethod || !$ref->hasMethod($this->$actionMethod)) {
throw new \RuntimeException(sprintf('The "%s" method for "%s" adapter is does not supported', $method, $this->getClass()));
}
} | Validate the adapter method.
@param string $method The method name
@throws \RuntimeException When the method does not supported | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L254-L262 |
fxpio/fxp-doctrine-console | Adapter/ServiceManagerAdapter.php | ServiceManagerAdapter.validateObject | public function validateObject($instance)
{
if (null !== $this->validator) {
$violations = $this->validator->validate($instance);
if (!empty($violations)) {
throw new ValidationException($violations);
}
}
} | php | public function validateObject($instance)
{
if (null !== $this->validator) {
$violations = $this->validator->validate($instance);
if (!empty($violations)) {
throw new ValidationException($violations);
}
}
} | Validate the object instance.
@param object $instance The object instance
@throws ValidationException When an error exist | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Adapter/ServiceManagerAdapter.php#L271-L280 |
gregorybesson/AdfabCore | src/AdfabCore/php/elFinderConnector.class.php | elFinderConnector.run | public function run()
{
$isPost = $_SERVER["REQUEST_METHOD"] == 'POST';
$src = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET;
$cmd = isset($src['cmd']) ? $src['cmd'] : '';
$args = array();
if (!function_exists('json_encode')) {
$error = $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_JSON);
$this->output(array('error' => '{"error":["'.implode('","', $error).'"]}', 'raw' => true));
}
if (!$this->elFinder->loaded()) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_VOL), 'debug' => $this->elFinder->mountErrors));
}
// telepat_mode: on
if (!$cmd && $isPost) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UPLOAD, elFinder::ERROR_UPLOAD_TOTAL_SIZE), 'header' => 'Content-Type: text/html'));
}
// telepat_mode: off
if (!$this->elFinder->commandExists($cmd)) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD)));
}
// collect required arguments to exec command
foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) {
$arg = $name == 'FILES'
? $_FILES
: (isset($src[$name]) ? $src[$name] : '');
if (!is_array($arg)) {
$arg = trim($arg);
}
if ($req && (!isset($arg) || $arg === '')) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
$args[$name] = $arg;
}
$args['debug'] = isset($src['debug']) ? !!$src['debug'] : false;
$this->output($this->elFinder->exec($cmd, $args));
} | php | public function run()
{
$isPost = $_SERVER["REQUEST_METHOD"] == 'POST';
$src = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET;
$cmd = isset($src['cmd']) ? $src['cmd'] : '';
$args = array();
if (!function_exists('json_encode')) {
$error = $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_JSON);
$this->output(array('error' => '{"error":["'.implode('","', $error).'"]}', 'raw' => true));
}
if (!$this->elFinder->loaded()) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_VOL), 'debug' => $this->elFinder->mountErrors));
}
// telepat_mode: on
if (!$cmd && $isPost) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UPLOAD, elFinder::ERROR_UPLOAD_TOTAL_SIZE), 'header' => 'Content-Type: text/html'));
}
// telepat_mode: off
if (!$this->elFinder->commandExists($cmd)) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD)));
}
// collect required arguments to exec command
foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) {
$arg = $name == 'FILES'
? $_FILES
: (isset($src[$name]) ? $src[$name] : '');
if (!is_array($arg)) {
$arg = trim($arg);
}
if ($req && (!isset($arg) || $arg === '')) {
$this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd)));
}
$args[$name] = $arg;
}
$args['debug'] = isset($src['debug']) ? !!$src['debug'] : false;
$this->output($this->elFinder->exec($cmd, $args));
} | Execute elFinder command and output result
@return void
@author Dmitry (dio) Levashov | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/php/elFinderConnector.class.php#L51-L95 |
phpextra/event-manager-silex-provider | src/PHPExtra/EventManager/Silex/Event/PostDispatchEvent.php | PostDispatchEvent.setControllerResult | public function setControllerResult($result)
{
$event = $this->getSymfonyEvent();
if ($event instanceof GetResponseForControllerResultEvent) {
$event->setControllerResult($result);
}
return $this;
} | php | public function setControllerResult($result)
{
$event = $this->getSymfonyEvent();
if ($event instanceof GetResponseForControllerResultEvent) {
$event->setControllerResult($result);
}
return $this;
} | @param $result
@return $this | https://github.com/phpextra/event-manager-silex-provider/blob/9952b237feffa5a469dd2976317736a570526249/src/PHPExtra/EventManager/Silex/Event/PostDispatchEvent.php#L40-L48 |
as3io/symfony-data-importer | src/Import/Importer.php | Importer.hasSegment | final public function hasSegment($key)
{
foreach ($this->getSegments() as $segment) {
if ($segment->getKey() === $key) {
return true;
}
}
return false;
} | php | final public function hasSegment($key)
{
foreach ($this->getSegments() as $segment) {
if ($segment->getKey() === $key) {
return true;
}
}
return false;
} | {@inheritdoc} | https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Importer.php#L95-L103 |
as3io/symfony-data-importer | src/Import/Importer.php | Importer.getSegment | final public function getSegment($key)
{
foreach ($this->getSegments() as $segment) {
if ($key === $segment->getKey()) {
return $segment;
}
}
throw new Exception\ImporterException(sprintf('Could not retrieve segment "%s"!', $key));
} | php | final public function getSegment($key)
{
foreach ($this->getSegments() as $segment) {
if ($key === $segment->getKey()) {
return $segment;
}
}
throw new Exception\ImporterException(sprintf('Could not retrieve segment "%s"!', $key));
} | {@inheritdoc} | https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Importer.php#L108-L116 |
as3io/symfony-data-importer | src/Import/Importer.php | Importer.modify | final public function modify($segmentKey, $limit = 200, $skip = 0)
{
throw new \BadMethodCallException('deprecated');
return $this->getSegment($segmentKey)->modify($limit, $skip);
} | php | final public function modify($segmentKey, $limit = 200, $skip = 0)
{
throw new \BadMethodCallException('deprecated');
return $this->getSegment($segmentKey)->modify($limit, $skip);
} | {@inheritdoc} | https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Import/Importer.php#L150-L154 |
BenGorFile/SymfonyFilesystemBridge | src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php | SymfonyFilesystem.delete | public function delete(FileName $aName)
{
$this->filesystem->remove($this->path . $aName->filename());
} | php | public function delete(FileName $aName)
{
$this->filesystem->remove($this->path . $aName->filename());
} | {@inheritdoc} | https://github.com/BenGorFile/SymfonyFilesystemBridge/blob/8347b769a17e43b6f45718701859283c4afd88eb/src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php#L56-L59 |
BenGorFile/SymfonyFilesystemBridge | src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php | SymfonyFilesystem.has | public function has(FileName $aName)
{
return $this->filesystem->exists($this->path . $aName->filename());
} | php | public function has(FileName $aName)
{
return $this->filesystem->exists($this->path . $aName->filename());
} | {@inheritdoc} | https://github.com/BenGorFile/SymfonyFilesystemBridge/blob/8347b769a17e43b6f45718701859283c4afd88eb/src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php#L64-L67 |
BenGorFile/SymfonyFilesystemBridge | src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php | SymfonyFilesystem.overwrite | public function overwrite(FileName $aName, $aContent)
{
$this->filesystem->dumpFile($this->path . $aName->filename(), $aContent);
} | php | public function overwrite(FileName $aName, $aContent)
{
$this->filesystem->dumpFile($this->path . $aName->filename(), $aContent);
} | {@inheritdoc} | https://github.com/BenGorFile/SymfonyFilesystemBridge/blob/8347b769a17e43b6f45718701859283c4afd88eb/src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php#L72-L75 |
BenGorFile/SymfonyFilesystemBridge | src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php | SymfonyFilesystem.write | public function write(FileName $aName, $aContent)
{
if ($this->has($aName)) {
throw new \Exception(
sprintf(
'Already exists a file with the same name that %s. ' .
'Maybe, you want to use "overwrite" method instead.',
$aName->filename()
)
);
}
$this->filesystem->dumpFile($this->path . $aName->filename(), $aContent);
} | php | public function write(FileName $aName, $aContent)
{
if ($this->has($aName)) {
throw new \Exception(
sprintf(
'Already exists a file with the same name that %s. ' .
'Maybe, you want to use "overwrite" method instead.',
$aName->filename()
)
);
}
$this->filesystem->dumpFile($this->path . $aName->filename(), $aContent);
} | {@inheritdoc} | https://github.com/BenGorFile/SymfonyFilesystemBridge/blob/8347b769a17e43b6f45718701859283c4afd88eb/src/BenGorFile/SymfonyFilesystemBridge/Infrastructure/Domain/Model/SymfonyFilesystem.php#L96-L108 |
Fuzzyma/contao-eloquent-bundle | Hooks/DCAEloquentifier.php | DCAEloquentifier.createOptionsCallback | public static function createOptionsCallback($strTable, $fieldName)
{
return function ($dc) use ($strTable, $fieldName) {
$eloquent = $GLOBALS['TL_DCA'][$strTable]['fields'][$fieldName]['eloquent'];
// get all possible values from our relation
$collection = $eloquent['model']::orderBy('id', 'ASC')->get();
// Build our options array
return array_map(
function ($arr) use ($eloquent) {
// Replace the placeholder in the label with values from the model
$label = preg_replace_callback('/%(\w+)%/', function ($match) use ($arr) {
// when there is no %key% in model, we return an empty string
if (isset($arr[$match[1]])) {
return $arr[$match[1]];
} else {
return '';
}
}, $eloquent['label']);
// if the label is empty we display at least the id
return $label ? : $arr['id'];
}, $collection->keyBy('id')->toArray());
};
} | php | public static function createOptionsCallback($strTable, $fieldName)
{
return function ($dc) use ($strTable, $fieldName) {
$eloquent = $GLOBALS['TL_DCA'][$strTable]['fields'][$fieldName]['eloquent'];
// get all possible values from our relation
$collection = $eloquent['model']::orderBy('id', 'ASC')->get();
// Build our options array
return array_map(
function ($arr) use ($eloquent) {
// Replace the placeholder in the label with values from the model
$label = preg_replace_callback('/%(\w+)%/', function ($match) use ($arr) {
// when there is no %key% in model, we return an empty string
if (isset($arr[$match[1]])) {
return $arr[$match[1]];
} else {
return '';
}
}, $eloquent['label']);
// if the label is empty we display at least the id
return $label ? : $arr['id'];
}, $collection->keyBy('id')->toArray());
};
} | 'options_callback' => \VlipgoBundle\Hooks\DCAEloquentifier::createOptionsCallback('tl_content', 'type') | https://github.com/Fuzzyma/contao-eloquent-bundle/blob/d5af2a3f48807db278ec3c92df463171f9514179/Hooks/DCAEloquentifier.php#L61-L94 |
Fuzzyma/contao-eloquent-bundle | Hooks/DCAEloquentifier.php | DCAEloquentifier.relationFromField | public static function relationFromField($fieldName, $method = null)
{
if ($method) return $method;
if (substr($fieldName, -3) == '_id') {
return substr($fieldName, 0, -3);
}
if (substr($fieldName, -4) == '_ids') {
return substr($fieldName, 0, -4) . 's';
}
return $fieldName;
} | php | public static function relationFromField($fieldName, $method = null)
{
if ($method) return $method;
if (substr($fieldName, -3) == '_id') {
return substr($fieldName, 0, -3);
}
if (substr($fieldName, -4) == '_ids') {
return substr($fieldName, 0, -4) . 's';
}
return $fieldName;
} | Consider this as a bit of magic
This method will return a "guessed" method name which is used from the relation
Since there is no way in Eloquent to "read" the relations from a model, we have to work with what we get
This method only does something when no method was set in the dca
It takes one $field of the dca and removes the _id
So 'topic_id' will be 'topic' and 'topic_ids' will be 'topics'.
If no _id is present, it just uses the $fieldName as method name for the relation | https://github.com/Fuzzyma/contao-eloquent-bundle/blob/d5af2a3f48807db278ec3c92df463171f9514179/Hooks/DCAEloquentifier.php#L270-L283 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation.selectAll | public function selectAll($primary_key_value)
{
return $this->_select($this->_table_name, array_keys($this->_table_schema), $primary_key_value);
} | php | public function selectAll($primary_key_value)
{
return $this->_select($this->_table_name, array_keys($this->_table_schema), $primary_key_value);
} | /*
Special Case Query Wrappers | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L55-L58 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._constructSchema | private function _constructSchema($rows)
{
// Compile the schema in an array of column => info
$schema = array();
foreach($rows as $row)
{
$schema[$row['column_name']] = $row;
}
return $schema;
} | php | private function _constructSchema($rows)
{
// Compile the schema in an array of column => info
$schema = array();
foreach($rows as $row)
{
$schema[$row['column_name']] = $row;
}
return $schema;
} | **********************
Format Table Information
********************** | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L175-L186 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._calculateInputPlaceholders | private function _calculateInputPlaceholders($columns)
{
// Make sure that we have at least one element
if (!is_array($columns) || empty($columns) || count($columns) < 1)
{
Utility::throwException('Columns provided to calculate input placeholders are invalid.');
}
// Given the input array, just create an array that ranges from 1 to the number of items
$numeric_array = range(1, count($columns));
// For each value, precede the value with a dollar sign
$numeric_array = array_map(
function($num)
{
return '$' . $num;
},
$numeric_array
);
// Return the keyed array, with each parameter named by column
return array_combine($columns, $numeric_array);
} | php | private function _calculateInputPlaceholders($columns)
{
// Make sure that we have at least one element
if (!is_array($columns) || empty($columns) || count($columns) < 1)
{
Utility::throwException('Columns provided to calculate input placeholders are invalid.');
}
// Given the input array, just create an array that ranges from 1 to the number of items
$numeric_array = range(1, count($columns));
// For each value, precede the value with a dollar sign
$numeric_array = array_map(
function($num)
{
return '$' . $num;
},
$numeric_array
);
// Return the keyed array, with each parameter named by column
return array_combine($columns, $numeric_array);
} | ********************
Prepare SQL Statements
******************** | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L233-L255 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._getPrimaryKeyFromInput | private function _getPrimaryKeyFromInput($table_name, $keyed_array)
{
// Get the primary key
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Find the primary key
if (empty($keyed_array) || !array_key_exists($table_primary_key, $keyed_array))
{
Utility::throwException('Primary key value not found in input.');
}
return $keyed_array[$table_primary_key];
} | php | private function _getPrimaryKeyFromInput($table_name, $keyed_array)
{
// Get the primary key
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Find the primary key
if (empty($keyed_array) || !array_key_exists($table_primary_key, $keyed_array))
{
Utility::throwException('Primary key value not found in input.');
}
return $keyed_array[$table_primary_key];
} | *************
Parse SQL Input
************* | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L281-L293 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._select | private function _select($table_name, $columns, $primary_key_value)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns
$parameter_columns = Validation::validateTableColumns($table_name, $table_schema, $columns);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// Construct the primary key requirement
$primary_key_value = intval($primary_key_value);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the SELECT sql
$sql = '
SELECT ' . implode(', ', $parameter_columns) . '
FROM ' . $table_name . '
WHERE ' . $table_primary_key . ' = $1;
';
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, array($primary_key_value));
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | php | private function _select($table_name, $columns, $primary_key_value)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns
$parameter_columns = Validation::validateTableColumns($table_name, $table_schema, $columns);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// Construct the primary key requirement
$primary_key_value = intval($primary_key_value);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the SELECT sql
$sql = '
SELECT ' . implode(', ', $parameter_columns) . '
FROM ' . $table_name . '
WHERE ' . $table_primary_key . ' = $1;
';
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, array($primary_key_value));
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | (array) $columns - an array of columns
(int) $primary_key_value - integer representing the primary key value | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L303-L339 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._insert | private function _insert($table_name, $keyed_array)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns and values
list($parameter_columns, $parameter_values) = Validation::validateTableInput($table_name, $table_schema, $table_primary_key, $keyed_array);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// List the number of parameters - Function creates an array of range 1..n and prepends '$' to each number
$parameter_placeholders = self::_calculateInputPlaceholders($parameter_columns);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the INSERT statement
$sql = '
INSERT INTO ' . $table_name . ' (' . implode(', ', $parameter_columns) . ')
VALUES (' . implode(', ', $parameter_placeholders) . ')
RETURNING *;
';
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, $parameter_values);
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | php | private function _insert($table_name, $keyed_array)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns and values
list($parameter_columns, $parameter_values) = Validation::validateTableInput($table_name, $table_schema, $table_primary_key, $keyed_array);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// List the number of parameters - Function creates an array of range 1..n and prepends '$' to each number
$parameter_placeholders = self::_calculateInputPlaceholders($parameter_columns);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the INSERT statement
$sql = '
INSERT INTO ' . $table_name . ' (' . implode(', ', $parameter_columns) . ')
VALUES (' . implode(', ', $parameter_placeholders) . ')
RETURNING *;
';
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, $parameter_values);
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | (array) $keyed_array - a dictionary of columns => values | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L344-L380 |
Cybourgeoisie/Geppetto | src/geppetto/Foundation.php | Foundation._update | private function _update($table_name, $keyed_array)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns and values
list($parameter_columns, $parameter_values) = Validation::validateTableInput($table_name, $table_schema, $table_primary_key, $keyed_array);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// List the number of parameters - Function creates an array of range 1..n and prepends '$' to each number
$parameter_placeholders = self::_calculateInputPlaceholders($parameter_columns);
// Construct the proper UPDATE parameters statement
array_walk($parameter_placeholders,
function(&$value, $key)
{
$value = $key . ' = ' . $value;
}
);
// Construct the primary key requirement
$primary_key_placeholder = '$' . (count($parameter_placeholders) + 1);
$primary_key_value = self::_getPrimaryKeyFromInput($table_name, $keyed_array);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the UPDATE statement
$sql = '
UPDATE ' . $table_name . ' SET
' . implode(', ', $parameter_placeholders) . '
WHERE ' . $table_primary_key . ' = ' . $primary_key_placeholder . '
RETURNING *;
';
// Append the primary key value to the parameter values
$parameter_values[] = $primary_key_value;
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, $parameter_values);
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | php | private function _update($table_name, $keyed_array)
{
// Get the schema and primary key
$table_schema = self::_getTableSchema($table_name);
$table_primary_key = self::_getTablePrimaryKey($table_name);
// Get the columns and values
list($parameter_columns, $parameter_values) = Validation::validateTableInput($table_name, $table_schema, $table_primary_key, $keyed_array);
// Escape the column names
$parameter_columns = self::_escapeColumnNames($parameter_columns);
// List the number of parameters - Function creates an array of range 1..n and prepends '$' to each number
$parameter_placeholders = self::_calculateInputPlaceholders($parameter_columns);
// Construct the proper UPDATE parameters statement
array_walk($parameter_placeholders,
function(&$value, $key)
{
$value = $key . ' = ' . $value;
}
);
// Construct the primary key requirement
$primary_key_placeholder = '$' . (count($parameter_placeholders) + 1);
$primary_key_value = self::_getPrimaryKeyFromInput($table_name, $keyed_array);
// Clean the table name
$table_name = self::_getCleanTableName($table_name);
// Construct the UPDATE statement
$sql = '
UPDATE ' . $table_name . ' SET
' . implode(', ', $parameter_placeholders) . '
WHERE ' . $table_primary_key . ' = ' . $primary_key_placeholder . '
RETURNING *;
';
// Append the primary key value to the parameter values
$parameter_values[] = $primary_key_value;
// Sanitize and run the query
$rows = Utility::pgQueryParams($sql, $parameter_values);
// Validate result, check that primary key is set
if (empty($rows) || !array_key_exists('0', $rows) || !array_key_exists($table_primary_key, $rows[0]))
{
Utility::throwException('Record not found for ' . $table_name . ' with a primary key value of ' . $primary_key_value);
}
// Return the only record
return $rows[0];
} | (array) $keyed_array - a dictionary of columns => values | https://github.com/Cybourgeoisie/Geppetto/blob/6c50f3452c36e3d86b33508df170b16c246bbcfa/src/geppetto/Foundation.php#L385-L437 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Entity/Orm/Zone.php | Zone.setZoneType | public function setZoneType(ZoneTypeInterface $zoneType)
{
$this->zoneTypeId = $zoneType->getId();
return parent::setZoneType($zoneType);
} | php | public function setZoneType(ZoneTypeInterface $zoneType)
{
$this->zoneTypeId = $zoneType->getId();
return parent::setZoneType($zoneType);
} | Override to store database required fields data.
{@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Entity/Orm/Zone.php#L49-L54 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Entity/Orm/Zone.php | Zone.setComponents | public function setComponents(ComponentCollection $components)
{
return parent::setComponents($components->map(function (Component $component) {
return $component->setZone($this);
}));
} | php | public function setComponents(ComponentCollection $components)
{
return parent::setComponents($components->map(function (Component $component) {
return $component->setZone($this);
}));
} | Doctrine needs to cross reference fks.
{@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Entity/Orm/Zone.php#L75-L80 |
addwiki/guzzle-mediawiki-client | src/MediawikiApiClient.php | MediawikiApiClient.factory | public static function factory($config = array())
{
$required = array('base_url');
$config = Collection::fromConfig($config, array(), $required);
$client = new self($config->get('base_url'));
$cookiePlugin = new CookiePlugin(new ArrayCookieJar());
$client->addSubscriber($cookiePlugin);
$client->setConfig($config);
$client->setUserAgent('addwiki-guzzle-mediawiki-client');
$client->setDescription(ServiceDescription::factory( dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'mediawiki.json'));
return $client;
} | php | public static function factory($config = array())
{
$required = array('base_url');
$config = Collection::fromConfig($config, array(), $required);
$client = new self($config->get('base_url'));
$cookiePlugin = new CookiePlugin(new ArrayCookieJar());
$client->addSubscriber($cookiePlugin);
$client->setConfig($config);
$client->setUserAgent('addwiki-guzzle-mediawiki-client');
$client->setDescription(ServiceDescription::factory( dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'mediawiki.json'));
return $client;
} | Factory method to create a new MediawikiApiClient
@param array|Collection $config Configuration data. Array keys:
base_url - Base URL of web service
@throws InvalidArgumentException
@return MediawikiApiClient | https://github.com/addwiki/guzzle-mediawiki-client/blob/60dc2c27d40196f90d1e5eef8cf0fc90b6b4d440/src/MediawikiApiClient.php#L65-L80 |
rzajac/php-test-helper | src/Database/DbGet.php | DbGet.factory | public static function factory(array $dbConfig): DbItf
{
/** @var DbItf[] $instances */
static $instances = [];
$key = md5(json_encode($dbConfig));
if (isset($instances[$key])) {
return $instances[$key];
}
switch ($dbConfig[DbItf::DB_CFG_DRIVER]) {
case DbItf::DB_DRIVER_MYSQL:
$instances[$key] = new MySQL();
$dbConfig[DbItf::DB_CFG_PORT] = (int)$dbConfig[DbItf::DB_CFG_PORT];
break;
default:
throw new DatabaseEx('Unknown database driver name: ' . $dbConfig[DbItf::DB_CFG_DRIVER]);
}
$instances[$key]->dbSetup($dbConfig);
if ($dbConfig[DbItf::DB_CFG_CONNECT]) {
$instances[$key]->dbConnect();
}
return $instances[$key];
} | php | public static function factory(array $dbConfig): DbItf
{
/** @var DbItf[] $instances */
static $instances = [];
$key = md5(json_encode($dbConfig));
if (isset($instances[$key])) {
return $instances[$key];
}
switch ($dbConfig[DbItf::DB_CFG_DRIVER]) {
case DbItf::DB_DRIVER_MYSQL:
$instances[$key] = new MySQL();
$dbConfig[DbItf::DB_CFG_PORT] = (int)$dbConfig[DbItf::DB_CFG_PORT];
break;
default:
throw new DatabaseEx('Unknown database driver name: ' . $dbConfig[DbItf::DB_CFG_DRIVER]);
}
$instances[$key]->dbSetup($dbConfig);
if ($dbConfig[DbItf::DB_CFG_CONNECT]) {
$instances[$key]->dbConnect();
}
return $instances[$key];
} | Database factory.
It returns the same instance for the same config.
@param array $dbConfig The database configuration
@throws DatabaseEx
@return DbItf | https://github.com/rzajac/php-test-helper/blob/37280e9ff639b25cf9413909cc080c5d8deb311c/src/Database/DbGet.php#L39-L67 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.calculateChangeSet | public function calculateChangeSet()
{
if (false === $this->isDirty()) {
return [];
}
return [
'old' => empty($this->original) ? null : $this->original,
'new' => empty($this->models) ? null : $this->models,
];
} | php | public function calculateChangeSet()
{
if (false === $this->isDirty()) {
return [];
}
return [
'old' => empty($this->original) ? null : $this->original,
'new' => empty($this->models) ? null : $this->models,
];
} | Calculates the change set of this collection.
@return array | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L105-L114 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.clear | public function clear()
{
$this->models = [];
$this->modelKeyMap = [];
$this->added = [];
$this->removed = $this->original;
return $this;
} | php | public function clear()
{
$this->models = [];
$this->modelKeyMap = [];
$this->added = [];
$this->removed = $this->original;
return $this;
} | Clears/empties the collection.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L121-L128 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.has | public function has(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->models[$key]);
} | php | public function has(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->models[$key]);
} | Determines if the Model is included in the collection.
@param AbstractModel $model The model to check.
@return bool | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L184-L188 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.hasDirtyModels | public function hasDirtyModels()
{
foreach ($this->models as $model) {
if (true === $model->isDirty()) {
return true;
}
}
return false;
} | php | public function hasDirtyModels()
{
foreach ($this->models as $model) {
if (true === $model->isDirty()) {
return true;
}
}
return false;
} | Determines if any models in this collection are dirty (have changes).
@return bool | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L195-L203 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.push | public function push(AbstractModel $model)
{
$this->validateAdd($model);
if (true === $this->willAdd($model)) {
return $this;
}
if (true === $this->willRemove($model)) {
$this->evict('removed', $model);
$this->set('models', $model);
return $this;
}
if (true === $this->hasOriginal($model)) {
return $this;
}
$this->set('added', $model);
$this->set('models', $model);
return $this;
} | php | public function push(AbstractModel $model)
{
$this->validateAdd($model);
if (true === $this->willAdd($model)) {
return $this;
}
if (true === $this->willRemove($model)) {
$this->evict('removed', $model);
$this->set('models', $model);
return $this;
}
if (true === $this->hasOriginal($model)) {
return $this;
}
$this->set('added', $model);
$this->set('models', $model);
return $this;
} | Pushes a Model into the collection.
@param AbstractModel $model The model to push.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L257-L274 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.rollback | public function rollback()
{
$this->models = $this->original;
$this->added = [];
$this->removed = [];
return $this;
} | php | public function rollback()
{
$this->models = $this->original;
$this->added = [];
$this->removed = [];
return $this;
} | Rollsback the collection it it's original state.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L315-L321 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.willAdd | public function willAdd(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->added[$key]);
} | php | public function willAdd(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->added[$key]);
} | Determines if the model is scheduled for addition to the collection.
@param AbstractModel $model The model to check.
@return bool | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L337-L341 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.willRemove | public function willRemove(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->removed[$key]);
} | php | public function willRemove(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->removed[$key]);
} | Determines if the model is scheduled for removal from the collection.
@param AbstractModel $model The model to check.
@return bool | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L349-L353 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.add | protected function add(AbstractModel $model)
{
if (true === $this->has($model)) {
return $this;
}
$this->validateAdd($model);
if (true === $model->getState()->is('empty')) {
$this->loaded = false;
}
$key = $model->getCompositeKey();
$this->models[$key] = $model;
$this->modelKeyMap[] = $key;
if (false === $this->hasOriginal($model)) {
$this->original[$key] = $model;
}
return $this;
} | php | protected function add(AbstractModel $model)
{
if (true === $this->has($model)) {
return $this;
}
$this->validateAdd($model);
if (true === $model->getState()->is('empty')) {
$this->loaded = false;
}
$key = $model->getCompositeKey();
$this->models[$key] = $model;
$this->modelKeyMap[] = $key;
if (false === $this->hasOriginal($model)) {
$this->original[$key] = $model;
}
return $this;
} | Adds an model to this collection.
Is used during initial collection construction.
@param AbstractModel $model
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L362-L380 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.evict | protected function evict($property, AbstractModel $model)
{
$key = $model->getCompositeKey();
if (isset($this->{$property})) {
unset($this->{$property}[$key]);
}
if ('models' === $property) {
$keys = array_flip($this->modelKeyMap);
if (isset($keys[$key])) {
unset($keys[$key]);
$this->modelKeyMap = array_keys($keys);
$this->totalCount--;
}
}
return $this;
} | php | protected function evict($property, AbstractModel $model)
{
$key = $model->getCompositeKey();
if (isset($this->{$property})) {
unset($this->{$property}[$key]);
}
if ('models' === $property) {
$keys = array_flip($this->modelKeyMap);
if (isset($keys[$key])) {
unset($keys[$key]);
$this->modelKeyMap = array_keys($keys);
$this->totalCount--;
}
}
return $this;
} | Evicts a model from a collection property (original, added, removed, models).
@param string $property The property key
@param AbstractModel $model The model to set.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L389-L405 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.hasOriginal | protected function hasOriginal(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->original[$key]);
} | php | protected function hasOriginal(AbstractModel $model)
{
$key = $model->getCompositeKey();
return isset($this->original[$key]);
} | Determines if the model is included in the original set.
@param AbstractModel $model The model to check.
@return bool | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L413-L417 |
as3io/modlr | src/Models/Collections/AbstractCollection.php | AbstractCollection.set | protected function set($property, AbstractModel $model)
{
$key = $model->getCompositeKey();
$this->{$property}[$key] = $model;
if ('models' === $property) {
$keys = array_flip($this->modelKeyMap);
if (!isset($keys[$key])) {
$this->modelKeyMap[] = $key;
$this->totalCount++;
}
}
return $this;
} | php | protected function set($property, AbstractModel $model)
{
$key = $model->getCompositeKey();
$this->{$property}[$key] = $model;
if ('models' === $property) {
$keys = array_flip($this->modelKeyMap);
if (!isset($keys[$key])) {
$this->modelKeyMap[] = $key;
$this->totalCount++;
}
}
return $this;
} | Sets a model to a collection property (original, added, removed, models).
@param string $property The property key
@param AbstractModel $model The model to set.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/AbstractCollection.php#L426-L439 |
pmdevelopment/tool-bundle | Twig/CssVersionExtension.php | CssVersionExtension.cssVersion | public function cssVersion($fileName)
{
$filePath = sprintf("%s/../web%s", $this->kernelRootDir, $fileName);
if (true === file_exists($filePath)) {
return sprintf("%s?v=%s", $fileName, substr(md5_file($filePath), 0, 5));
}
return sprintf("%s?v=%s", $fileName, substr(sha1(microtime()), 0, 6));
} | php | public function cssVersion($fileName)
{
$filePath = sprintf("%s/../web%s", $this->kernelRootDir, $fileName);
if (true === file_exists($filePath)) {
return sprintf("%s?v=%s", $fileName, substr(md5_file($filePath), 0, 5));
}
return sprintf("%s?v=%s", $fileName, substr(sha1(microtime()), 0, 6));
} | CSS Version
@param string $fileName
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/CssVersionExtension.php#L53-L62 |
phPoirot/Client-OAuth2 | mod/Services/Authenticators/ServiceAuthenticatorToken.php | ServiceAuthenticatorToken.newService | function newService()
{
### Attain Login Continue If Has
/** @var iHttpRequest $request */
$request = \IOC::GetIoC()->get('/HttpRequest');
$tokenAuthIdentifier = new IdentifierHttpToken;
$tokenAuthIdentifier
->setRequest($request)
->setTokenAssertion( \Module\OAuth2Client\Actions::AssertToken()->assertion() )
;
// In Cases That we request and token has no owner_identifier
// client_credentials token in example
//
/*
$authenticator = new Authenticator(
$tokenAuthIdentifier
);
*/
// So I Disable This Here; this cause problem
$authenticator = new Authenticator(
new IdentifierWrapIdentityMap(
$tokenAuthIdentifier
, new IdentityFulfillmentLazy( $this->getIdentityProvider() , 'owner_identifier' )
)
);
return $authenticator;
} | php | function newService()
{
### Attain Login Continue If Has
/** @var iHttpRequest $request */
$request = \IOC::GetIoC()->get('/HttpRequest');
$tokenAuthIdentifier = new IdentifierHttpToken;
$tokenAuthIdentifier
->setRequest($request)
->setTokenAssertion( \Module\OAuth2Client\Actions::AssertToken()->assertion() )
;
// In Cases That we request and token has no owner_identifier
// client_credentials token in example
//
/*
$authenticator = new Authenticator(
$tokenAuthIdentifier
);
*/
// So I Disable This Here; this cause problem
$authenticator = new Authenticator(
new IdentifierWrapIdentityMap(
$tokenAuthIdentifier
, new IdentityFulfillmentLazy( $this->getIdentityProvider() , 'owner_identifier' )
)
);
return $authenticator;
} | Create Service
@return Authenticator | https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Services/Authenticators/ServiceAuthenticatorToken.php#L38-L68 |
nasumilu/geometry | src/Builder/SerializerBuilder.php | SerializerBuilder.buildGeometry | public function buildGeometry(BuilderEvent $event) {
$argument = $event->getArgument();
$format = $this->finder->findFormat($argument);
if (null !== $format) {
$geometry = $this->serializer->deserialize($argument, Geometry::class, $format);
$event->setGeometry($geometry, true);
}
} | php | public function buildGeometry(BuilderEvent $event) {
$argument = $event->getArgument();
$format = $this->finder->findFormat($argument);
if (null !== $format) {
$geometry = $this->serializer->deserialize($argument, Geometry::class, $format);
$event->setGeometry($geometry, true);
}
} | {@inheritDoc} | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/Builder/SerializerBuilder.php#L73-L80 |
PhoxPHP/Glider | src/Connection/PlatformResolver.php | PlatformResolver.resolvePlatform | public function resolvePlatform(EventManager $eventManager)
{
$eventManager->attachSubscriber(new ConnectionAttemptSubscriber());
if (!$this->connectionManager instanceof ConnectionInterface) {
throw new RuntimeException('Connection must implement \ConnectionInterface');
}
$reflector = new \ReflectionClass($this->connectionManager);
$connections = $reflector->getProperty('platformConnector');
$connections->setAccessible('public');
$connections = $connections->getValue($this->connectionManager);
$resolvedProvider = $this->getPlatformProvider($connections, $eventManager);
if (!$resolvedProvider) {
$resolvedProvider = $this->getPlatformProvider(
$this->connectionManager->getAlternativeId(ConnectionManager::USE_ALT_KEY), $eventManager
);
}
if (!is_null($resolvedProvider) && $resolvedProvider == false) {
throw new RuntimeException('Unable to resolve database platform.');
}
// If connection was successfully established, dispatch `connect.created` event.
$this->platformProvider->eventManager->dispatchEvent('connect.created');
return $resolvedProvider;
} | php | public function resolvePlatform(EventManager $eventManager)
{
$eventManager->attachSubscriber(new ConnectionAttemptSubscriber());
if (!$this->connectionManager instanceof ConnectionInterface) {
throw new RuntimeException('Connection must implement \ConnectionInterface');
}
$reflector = new \ReflectionClass($this->connectionManager);
$connections = $reflector->getProperty('platformConnector');
$connections->setAccessible('public');
$connections = $connections->getValue($this->connectionManager);
$resolvedProvider = $this->getPlatformProvider($connections, $eventManager);
if (!$resolvedProvider) {
$resolvedProvider = $this->getPlatformProvider(
$this->connectionManager->getAlternativeId(ConnectionManager::USE_ALT_KEY), $eventManager
);
}
if (!is_null($resolvedProvider) && $resolvedProvider == false) {
throw new RuntimeException('Unable to resolve database platform.');
}
// If connection was successfully established, dispatch `connect.created` event.
$this->platformProvider->eventManager->dispatchEvent('connect.created');
return $resolvedProvider;
} | Resolve provided connection's platform.
@param $eventManager <Kit\Glider\Events\EventManager>
@access public
@return <Object> <Kit\Glider\Platform\Contract\PlatformProvider> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/PlatformResolver.php#L89-L116 |
PhoxPHP/Glider | src/Connection/PlatformResolver.php | PlatformResolver.getPlatformProvider | private function getPlatformProvider($platform=[], EventManager $eventManager)
{
if (is_null($platform)) {
return false;
}
$platformId = key($platform);
$platform = current($platform);
if (!isset($platform['provider'])) {
$this->connectionFailed = ':noPlatform';
return false;
}
$provider = $platform['provider'];
if (!class_exists($provider)) {
$this->connectionFailed = ':noConnectorProvider';
return false;
}
$this->preparedConnection = $platform;
$platformProvider = new $provider($this, new EventManager());
if (!$platformProvider instanceof PlatformProvider) {
return false;
}
if (isset($platform['domain']) && !Domain::matches($platform['domain'])) {
$eventManager->dispatchEvent('domain.notallowed', [$platformId => $platform]);
return false;
}
$this->platformProvider = $platformProvider;
$providerConnector = $this->platformProvider;
return $providerConnector;
} | php | private function getPlatformProvider($platform=[], EventManager $eventManager)
{
if (is_null($platform)) {
return false;
}
$platformId = key($platform);
$platform = current($platform);
if (!isset($platform['provider'])) {
$this->connectionFailed = ':noPlatform';
return false;
}
$provider = $platform['provider'];
if (!class_exists($provider)) {
$this->connectionFailed = ':noConnectorProvider';
return false;
}
$this->preparedConnection = $platform;
$platformProvider = new $provider($this, new EventManager());
if (!$platformProvider instanceof PlatformProvider) {
return false;
}
if (isset($platform['domain']) && !Domain::matches($platform['domain'])) {
$eventManager->dispatchEvent('domain.notallowed', [$platformId => $platform]);
return false;
}
$this->platformProvider = $platformProvider;
$providerConnector = $this->platformProvider;
return $providerConnector;
} | Resolves a connector's provider and returns it's object.
@param $eventManager <Kit\Glider\Events\EventManager >
@param $platform <Array>
@access private
@return <Mixed> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/PlatformResolver.php#L126-L159 |
axypro/codecs-base64vlq | Base64.php | Base64.encode | public function encode($numbers)
{
$chars = [];
$alphabet = $this->alphabet;
foreach ($numbers as $number) {
if (isset($alphabet[$number])) {
$chars[] = $alphabet[$number];
} else {
throw new InvalidBase64Input($number);
}
}
return implode('', $chars);
} | php | public function encode($numbers)
{
$chars = [];
$alphabet = $this->alphabet;
foreach ($numbers as $number) {
if (isset($alphabet[$number])) {
$chars[] = $alphabet[$number];
} else {
throw new InvalidBase64Input($number);
}
}
return implode('', $chars);
} | Encodes a block of numbers to a base64-string
@param int[]|int $numbers
@return string
@throws \axy\codecs\base64vlq\errors\InvalidBase64Input | https://github.com/axypro/codecs-base64vlq/blob/0d658b7fafdabb824fa1c91c0f6977ebac707dad/Base64.php#L44-L56 |
axypro/codecs-base64vlq | Base64.php | Base64.decode | public function decode($based)
{
if (!is_array($based)) {
$based = str_split($based);
}
$numbers = [];
$char2int = $this->char2int;
foreach ($based as $char) {
if (isset($char2int[$char])) {
$numbers[] = $char2int[$char];
} else {
throw new InvalidBase64($based);
}
}
return $numbers;
} | php | public function decode($based)
{
if (!is_array($based)) {
$based = str_split($based);
}
$numbers = [];
$char2int = $this->char2int;
foreach ($based as $char) {
if (isset($char2int[$char])) {
$numbers[] = $char2int[$char];
} else {
throw new InvalidBase64($based);
}
}
return $numbers;
} | Decodes a base64-string to a block of numbers
@param string|string[] $based
the base64-string or the array of characters
@return int[]
@throws \axy\codecs\base64vlq\errors\InvalidBase64 | https://github.com/axypro/codecs-base64vlq/blob/0d658b7fafdabb824fa1c91c0f6977ebac707dad/Base64.php#L66-L81 |
pascalchevrel/vcs | src/VCS/Base.php | Base.parseLog | public function parseLog($log)
{
$commits = $tags = [];
for ($i = 0, $lines = count($log); $i < $lines; $i++) {
$tmp = explode(': ', $log[$i]);
$tmp = array_map('trim', $tmp);
if ($tmp[0] == 'changeset') {
$commit = $tmp[1];
}
if ($tmp[0] == 'user') {
$email = $this->extractEmail($tmp[1]);
$author = $this->extractAuthor($tmp[1]);
}
if ($tmp[0] == 'date') {
$date = trim($tmp[1]);
}
if ($tmp[0] == 'tag') {
$tags[] = trim($tmp[1]);
}
if ($tmp[0] == 'summary') {
$commits[] = [
'commit' => trim($commit),
'author' => trim($author),
'email' => trim($email),
'date' => DateTime::createFromFormat('D M j H:i:s Y O', $date),
'summary' => trim($tmp[1]),
'tags' => $tags,
'vcs' => trim($this->repository_type),
];
$tags = [];
}
}
return $commits;
} | php | public function parseLog($log)
{
$commits = $tags = [];
for ($i = 0, $lines = count($log); $i < $lines; $i++) {
$tmp = explode(': ', $log[$i]);
$tmp = array_map('trim', $tmp);
if ($tmp[0] == 'changeset') {
$commit = $tmp[1];
}
if ($tmp[0] == 'user') {
$email = $this->extractEmail($tmp[1]);
$author = $this->extractAuthor($tmp[1]);
}
if ($tmp[0] == 'date') {
$date = trim($tmp[1]);
}
if ($tmp[0] == 'tag') {
$tags[] = trim($tmp[1]);
}
if ($tmp[0] == 'summary') {
$commits[] = [
'commit' => trim($commit),
'author' => trim($author),
'email' => trim($email),
'date' => DateTime::createFromFormat('D M j H:i:s Y O', $date),
'summary' => trim($tmp[1]),
'tags' => $tags,
'vcs' => trim($this->repository_type),
];
$tags = [];
}
}
return $commits;
} | Parse the log provided as a string
@param string $log VCS log
@return array structured data extracted from the log | https://github.com/pascalchevrel/vcs/blob/23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa/src/VCS/Base.php#L33-L73 |
pascalchevrel/vcs | src/VCS/Base.php | Base.extractAuthor | public function extractAuthor($string)
{
preg_match_all('/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i', $string, $matches);
$string = str_replace($matches[0], '', $string);
$string = str_replace(['<', '>', '()'], '', $string);
$string = trim($string);
return empty($string) ? 'Unknown' : $string;
} | php | public function extractAuthor($string)
{
preg_match_all('/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i', $string, $matches);
$string = str_replace($matches[0], '', $string);
$string = str_replace(['<', '>', '()'], '', $string);
$string = trim($string);
return empty($string) ? 'Unknown' : $string;
} | Extract the Author name from the string, remove emails if they exist
@param string $string String to analyze
@return string Author name | https://github.com/pascalchevrel/vcs/blob/23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa/src/VCS/Base.php#L95-L103 |
schpill/thin | src/Html/Sizer.php | Sizer.resize | public function resize($newWidth, $newHeight, $option = 'auto')
{
// Get optimal width and height - based on $option.
$option_array = $this->get_dimensions($newWidth, $newHeight, $option);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
// Resample - create image canvas of x, y size.
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
$imageBackground = imagecreatetruecolor($this->width, $this->height);
// Retain transparency for PNG and GIF files.
$background_colour = imagecolorallocate(
$imageBackground,
arrayGet($this->config, 'background_color.r'),
arrayGet($this->config, 'background_color.g'),
arrayGet($this->config, 'background_color.b')
);
imagefilledrectangle($imageBackground, 0, 0, $this->width, $this->height, $background_colour);
imagecopy($imageBackground, $this->image, 0, 0, 0, 0, $this->width, $this->height);
// imagecolortransparent($this->imageResized, imagecolorallocatealpha($this->imageResized, 255, 255, 255, 127));
// imagealphablending($this->imageResized, false);
// imagesavealpha($this->imageResized, true);
// convert transparency to white when converting from PNG to JPG.
// PNG to PNG should retain transparency as per normal.
// imagefill($this->imageResized, 0, 0, IMG_COLOR_TRANSPARENT);
// Create the new image.
imagecopyresampled($this->imageResized, $imageBackground, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// if option is 'crop' or 'fit', then crop too.
if ($option == 'crop' || $option == 'fit') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
// Return $this to allow calls to be chained.
return $this;
} | php | public function resize($newWidth, $newHeight, $option = 'auto')
{
// Get optimal width and height - based on $option.
$option_array = $this->get_dimensions($newWidth, $newHeight, $option);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
// Resample - create image canvas of x, y size.
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
$imageBackground = imagecreatetruecolor($this->width, $this->height);
// Retain transparency for PNG and GIF files.
$background_colour = imagecolorallocate(
$imageBackground,
arrayGet($this->config, 'background_color.r'),
arrayGet($this->config, 'background_color.g'),
arrayGet($this->config, 'background_color.b')
);
imagefilledrectangle($imageBackground, 0, 0, $this->width, $this->height, $background_colour);
imagecopy($imageBackground, $this->image, 0, 0, 0, 0, $this->width, $this->height);
// imagecolortransparent($this->imageResized, imagecolorallocatealpha($this->imageResized, 255, 255, 255, 127));
// imagealphablending($this->imageResized, false);
// imagesavealpha($this->imageResized, true);
// convert transparency to white when converting from PNG to JPG.
// PNG to PNG should retain transparency as per normal.
// imagefill($this->imageResized, 0, 0, IMG_COLOR_TRANSPARENT);
// Create the new image.
imagecopyresampled($this->imageResized, $imageBackground, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// if option is 'crop' or 'fit', then crop too.
if ($option == 'crop' || $option == 'fit') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
// Return $this to allow calls to be chained.
return $this;
} | Resizes and/or crops an image.
@param int $newWidth The width of the image
@param int $newHeight The height of the image
@param string $option Either exact, portrait, landscape, auto or crop.
@return [type] | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L82-L122 |
schpill/thin | src/Html/Sizer.php | Sizer.save | public function save($savePath, $imageQuality = 95)
{
// If the image wasn't resized, fetch original image.
if (!$this->imageResized) {
$this->imageResized = $this->image;
}
// Get extension of the output file.
$extension = Inflector::lower(File::extension($savePath));
// Create and save an image based on it's extension.
switch($extension)
{
case 'jpg':
case 'jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;
case 'gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;
case 'png':
// Scale quality from 0-100 to 0-9.
$scaleQuality = round(($imageQuality / 100) * 9);
// Invert quality setting as 0 is best, not 9.
$invertScaleQuality = 9 - $scaleQuality;
if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;
default:
return false;
break;
}
// Remove the resource for the resized image.
imagedestroy($this->imageResized);
return true;
} | php | public function save($savePath, $imageQuality = 95)
{
// If the image wasn't resized, fetch original image.
if (!$this->imageResized) {
$this->imageResized = $this->image;
}
// Get extension of the output file.
$extension = Inflector::lower(File::extension($savePath));
// Create and save an image based on it's extension.
switch($extension)
{
case 'jpg':
case 'jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;
case 'gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;
case 'png':
// Scale quality from 0-100 to 0-9.
$scaleQuality = round(($imageQuality / 100) * 9);
// Invert quality setting as 0 is best, not 9.
$invertScaleQuality = 9 - $scaleQuality;
if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;
default:
return false;
break;
}
// Remove the resource for the resized image.
imagedestroy($this->imageResized);
return true;
} | Save the image based on its file type.
@param string $savePath Where to save the image
@param int $imageQuality The output quality of the image
@return boolean | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L130-L177 |
schpill/thin | src/Html/Sizer.php | Sizer.openImage | private function openImage($file)
{
// If $file isn't an array, we'll turn it into one.
if (!is_array($file)) {
$file_dimensions = getimagesize($file);
$file = array(
'type' => Inflector::lower($file_dimensions['mime']),
'tmp_name' => $file
);
}
$mime = $file['type'];
$file_path = $file['tmp_name'];
// Confirm that the file actually exists.
if (!file_exists($file_path)) {
throw new Exception('Could not find file: ' . $file_path . '. It doesn\'t seem to exist.');
}
switch ($mime) {
case 'image/pjpeg': // IE6
case File::mime('jpg'): $img = @imagecreatefromjpeg($file_path); break;
case File::mime('gif'): $img = @imagecreatefromgif($file_path); break;
case File::mime('png'): $img = @imagecreatefrompng($file_path); break;
default: $img = false; break;
}
return $img;
} | php | private function openImage($file)
{
// If $file isn't an array, we'll turn it into one.
if (!is_array($file)) {
$file_dimensions = getimagesize($file);
$file = array(
'type' => Inflector::lower($file_dimensions['mime']),
'tmp_name' => $file
);
}
$mime = $file['type'];
$file_path = $file['tmp_name'];
// Confirm that the file actually exists.
if (!file_exists($file_path)) {
throw new Exception('Could not find file: ' . $file_path . '. It doesn\'t seem to exist.');
}
switch ($mime) {
case 'image/pjpeg': // IE6
case File::mime('jpg'): $img = @imagecreatefromjpeg($file_path); break;
case File::mime('gif'): $img = @imagecreatefromgif($file_path); break;
case File::mime('png'): $img = @imagecreatefrompng($file_path); break;
default: $img = false; break;
}
return $img;
} | Open a file, detect its mime-type and create an image resrource from it.
@param array $file Attributes of file from the $_FILES array
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L184-L213 |
schpill/thin | src/Html/Sizer.php | Sizer.get_dimensions | private function get_dimensions($newWidth, $newHeight, $option)
{
switch ($option) {
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight = $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$option_array = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
case 'fit':
$option_array = $this->getSizeByFit($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
case 'crop':
$option_array = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
}
return array(
'optimalWidth' => $optimalWidth,
'optimalHeight' => $optimalHeight
);
} | php | private function get_dimensions($newWidth, $newHeight, $option)
{
switch ($option) {
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight = $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$option_array = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
case 'fit':
$option_array = $this->getSizeByFit($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
case 'crop':
$option_array = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $option_array['optimalWidth'];
$optimalHeight = $option_array['optimalHeight'];
break;
}
return array(
'optimalWidth' => $optimalWidth,
'optimalHeight' => $optimalHeight
);
} | Return the image dimensions based on the option that was chosen.
@param int $newWidth The width of the image
@param int $newHeight The height of the image
@param string $option Either exact, portrait, landscape, auto or crop.
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L222-L258 |
schpill/thin | src/Html/Sizer.php | Sizer.getSizeByAuto | private function getSizeByAuto($newWidth, $newHeight)
{
// Image to be resized is wider (landscape).
if ($this->height < $this->width) {
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
} else if ($this->height > $this->width) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
} else {
if ($newHeight < $newWidth)
{
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
} else {
// Sqaure being resized to a square.
$optimalWidth = $newWidth;
$optimalHeight = $newHeight;
}
}
return array(
'optimalWidth' => $optimalWidth,
'optimalHeight' => $optimalHeight
);
} | php | private function getSizeByAuto($newWidth, $newHeight)
{
// Image to be resized is wider (landscape).
if ($this->height < $this->width) {
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
} else if ($this->height > $this->width) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
} else {
if ($newHeight < $newWidth)
{
$optimalWidth = $newWidth;
$optimalHeight = $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight = $newHeight;
} else {
// Sqaure being resized to a square.
$optimalWidth = $newWidth;
$optimalHeight = $newHeight;
}
}
return array(
'optimalWidth' => $optimalWidth,
'optimalHeight' => $optimalHeight
);
} | Checks to see if an image is portrait or landscape and resizes accordingly.
@param int $newWidth The width of the image
@param int $newHeight The height of the image
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L292-L320 |
schpill/thin | src/Html/Sizer.php | Sizer.getSizeByFit | private function getSizeByFit($newWidth, $newHeight)
{
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
$max = max($heightRatio, $widthRatio);
return array(
'optimalWidth' => $this->width / $max,
'optimalHeight' => $this->height / $max,
);
} | php | private function getSizeByFit($newWidth, $newHeight)
{
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
$max = max($heightRatio, $widthRatio);
return array(
'optimalWidth' => $this->width / $max,
'optimalHeight' => $this->height / $max,
);
} | Resizes an image so it fits entirely inside the given dimensions.
@param int $newWidth The width of the image
@param int $newHeight The height of the image
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L328-L340 |
schpill/thin | src/Html/Sizer.php | Sizer.crop | private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
$cropPoints = $this->getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight);
// Find center - this will be used for the crop.
$cropStartX = $cropPoints['x'];
$cropStartY = $cropPoints['y'];
$crop = $this->imageResized;
$destOffsetX = max(0, -$cropStartX);
$destOffsetY = max(0, -$cropStartY);
$cropStartX = max(0, $cropStartX);
$cropStartY = max(0, $cropStartY);
$destWidth = min($optimalWidth, $newWidth);
$destHeight = min($optimalHeight, $newHeight);
// Now crop from center to exact requested size.
$this->imageResized = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($crop, true);
imagealphablending($this->imageResized, false);
imagesavealpha($this->imageResized, true);
imagefilledrectangle(
$this->imageResized,
0,
0,
$newWidth,
$newHeight,
imagecolorallocatealpha(
$this->imageResized,
255,
255,
255,
127
)
);
imagecopyresampled($this->imageResized, $crop, $destOffsetX, $destOffsetY, $cropStartX, $cropStartY, $destWidth, $destHeight, $destWidth, $destHeight);
return true;
} | php | private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
$cropPoints = $this->getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight);
// Find center - this will be used for the crop.
$cropStartX = $cropPoints['x'];
$cropStartY = $cropPoints['y'];
$crop = $this->imageResized;
$destOffsetX = max(0, -$cropStartX);
$destOffsetY = max(0, -$cropStartY);
$cropStartX = max(0, $cropStartX);
$cropStartY = max(0, $cropStartY);
$destWidth = min($optimalWidth, $newWidth);
$destHeight = min($optimalHeight, $newHeight);
// Now crop from center to exact requested size.
$this->imageResized = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($crop, true);
imagealphablending($this->imageResized, false);
imagesavealpha($this->imageResized, true);
imagefilledrectangle(
$this->imageResized,
0,
0,
$newWidth,
$newHeight,
imagecolorallocatealpha(
$this->imageResized,
255,
255,
255,
127
)
);
imagecopyresampled($this->imageResized, $crop, $destOffsetX, $destOffsetY, $cropStartX, $cropStartY, $destWidth, $destHeight, $destWidth, $destHeight);
return true;
} | Crops an image from its center.
@param int $optimalWidth The width of the image
@param int $optimalHeight The height of the image
@param int $newWidth The new width
@param int $newHeight The new height
@return true | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L377-L419 |
schpill/thin | src/Html/Sizer.php | Sizer.getCropPoints | private function getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
$cropPoints = array();
$vertical_start = arrayGet($this->config, 'crop_vertical_start_point');
$horizontal_start = arrayGet($this->config, 'crop_horizontal_start_point');
// Where is our vertical starting crop point?
switch ($vertical_start) {
case 'top':
$cropPoints['y'] = 0;
break;
case 'center':
$cropPoints['y'] = ($optimalHeight / 2) - ($newHeight / 2);
break;
case 'bottom':
$cropPoints['y'] = $optimalHeight - $newHeight;
break;
default:
throw new Exception('Unknown value for crop_vertical_start_point: '. $vertical_start .'. Please check config file in the Resizer bundle.');
break;
}
// Where is our horizontal starting crop point?
switch ($horizontal_start) {
case 'left':
$cropPoints['x'] = 0;
break;
case 'center':
$cropPoints['x'] = ($optimalWidth / 2) - ($newWidth / 2);
break;
case 'right':
$cropPoints['x'] = $optimalWidth - $newWidth;
break;
default:
throw new Exception('Unknown value for crop_horizontal_start_point: '. $horizontal_start .'. Please check config file in the Resizer bundle.');
break;
}
return $cropPoints;
} | php | private function getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
$cropPoints = array();
$vertical_start = arrayGet($this->config, 'crop_vertical_start_point');
$horizontal_start = arrayGet($this->config, 'crop_horizontal_start_point');
// Where is our vertical starting crop point?
switch ($vertical_start) {
case 'top':
$cropPoints['y'] = 0;
break;
case 'center':
$cropPoints['y'] = ($optimalHeight / 2) - ($newHeight / 2);
break;
case 'bottom':
$cropPoints['y'] = $optimalHeight - $newHeight;
break;
default:
throw new Exception('Unknown value for crop_vertical_start_point: '. $vertical_start .'. Please check config file in the Resizer bundle.');
break;
}
// Where is our horizontal starting crop point?
switch ($horizontal_start) {
case 'left':
$cropPoints['x'] = 0;
break;
case 'center':
$cropPoints['x'] = ($optimalWidth / 2) - ($newWidth / 2);
break;
case 'right':
$cropPoints['x'] = $optimalWidth - $newWidth;
break;
default:
throw new Exception('Unknown value for crop_horizontal_start_point: '. $horizontal_start .'. Please check config file in the Resizer bundle.');
break;
}
return $cropPoints;
} | Gets the crop points based on the configuration either set in the file
or overridden by user in their own config file, or on the fly.
@param int $optimalWidth The width of the image
@param int $optimalHeight The height of the image
@param int $newWidth The new width
@param int $newHeight The new height
@return array Array containing the crop x and y points. | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L430-L472 |
keeko/framework | src/routing/AbstractRouter.php | AbstractRouter.unserializeParams | public function unserializeParams($params) {
$parts = explode($this->options['param-delimiter'], $params);
$params = [];
foreach ($parts as $part) {
$kv = explode('=', $part);
if ($kv[0] != '') {
$value = count($kv) > 1
? $kv[1] == $this->options['param-true'] ? true
: ($kv[1] == $this->options['param-false'] ? false : $kv[1]) : true;
$params = $this->setParam($params, $kv[0], $value);
}
}
return $params;
} | php | public function unserializeParams($params) {
$parts = explode($this->options['param-delimiter'], $params);
$params = [];
foreach ($parts as $part) {
$kv = explode('=', $part);
if ($kv[0] != '') {
$value = count($kv) > 1
? $kv[1] == $this->options['param-true'] ? true
: ($kv[1] == $this->options['param-false'] ? false : $kv[1]) : true;
$params = $this->setParam($params, $kv[0], $value);
}
}
return $params;
} | Unserializes Parameters
@param string $params
@return array the unserialized array | https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/routing/AbstractRouter.php#L102-L116 |
keeko/framework | src/routing/AbstractRouter.php | AbstractRouter.serializeParams | public function serializeParams($params) {
$serialized = '';
foreach ($params as $key => $val) {
$serialized .= $key;
if (is_bool($val) === true) {
$serialized .= '=' . $val ? $this->options['param-true'] : $this->options['param-false'];
} else if ($val != '') {
$serialized .= '=' . $val;
}
$serialized .= $this->options['param-delimiter'];
}
return $serialized;
} | php | public function serializeParams($params) {
$serialized = '';
foreach ($params as $key => $val) {
$serialized .= $key;
if (is_bool($val) === true) {
$serialized .= '=' . $val ? $this->options['param-true'] : $this->options['param-false'];
} else if ($val != '') {
$serialized .= '=' . $val;
}
$serialized .= $this->options['param-delimiter'];
}
return $serialized;
} | Serializes Parameters
@param array $params
@return string the serialized params | https://github.com/keeko/framework/blob/a2c5d76a4ab7bd658e81d88fb3c98eee115c06ac/src/routing/AbstractRouter.php#L146-L158 |
theloopyewe/ravelry-api.php | src/RavelryApi/TypeConversion.php | TypeConversion.toRavelryPostFile | public static function toRavelryPostFile($value, Parameter $parameter)
{
if (is_string($value)) {
$value = fopen($value, 'r');
}
if (!($value instanceof StreamInterface)) {
$value = \GuzzleHttp\Stream\create($value);
}
if ($value instanceof MetadataStreamInterface) {
$filename = $value->getMetadata('uri');
}
if (!$filename || substr($filename, 0, 6) === 'php://') {
$filename = $parameter->getWireName();
}
return new PostFile(
$parameter->getWireName(),
$value,
$filename,
[
'Content-Disposition' => sprintf(
'form-data; name="%s"; filename="%s"',
$parameter->getWireName(),
basename($filename)
),
]
);
} | php | public static function toRavelryPostFile($value, Parameter $parameter)
{
if (is_string($value)) {
$value = fopen($value, 'r');
}
if (!($value instanceof StreamInterface)) {
$value = \GuzzleHttp\Stream\create($value);
}
if ($value instanceof MetadataStreamInterface) {
$filename = $value->getMetadata('uri');
}
if (!$filename || substr($filename, 0, 6) === 'php://') {
$filename = $parameter->getWireName();
}
return new PostFile(
$parameter->getWireName(),
$value,
$filename,
[
'Content-Disposition' => sprintf(
'form-data; name="%s"; filename="%s"',
$parameter->getWireName(),
basename($filename)
),
]
);
} | This is duplicating logic from `GuzzleHttp\Post\PostFile` in order to
patch odd API server behavior. It also makes sure the value is a proper
stream reference.
See http://www.ravelry.com/discuss/ravelry-api/2936052/1-25#5 | https://github.com/theloopyewe/ravelry-api.php/blob/4dacae056e15cf5fd4e236b79843d0736db1e885/src/RavelryApi/TypeConversion.php#L108-L138 |
bruno-barros/w.eloquent-framework | src/weloquent/Support/TaxonomyTrait.php | TaxonomyTrait.getPostType | public function getPostType()
{
global $wp_query;
if(isset($wp_query->post) && $wp_query->post->post_type)
{
return $wp_query->post->post_type;
}
if (isset($wp_query->query) && isset($wp_query->query['post_type']))
{
return $wp_query->query['post_type'];
}
else if(isset($wp_query->query_vars) && isset($wp_query->query_vars['post_type']))
{
return $wp_query->query_vars['post_type'];
}
return false;
} | php | public function getPostType()
{
global $wp_query;
if(isset($wp_query->post) && $wp_query->post->post_type)
{
return $wp_query->post->post_type;
}
if (isset($wp_query->query) && isset($wp_query->query['post_type']))
{
return $wp_query->query['post_type'];
}
else if(isset($wp_query->query_vars) && isset($wp_query->query_vars['post_type']))
{
return $wp_query->query_vars['post_type'];
}
return false;
} | Return the post type slug if available
@return bool|string | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L17-L35 |
bruno-barros/w.eloquent-framework | src/weloquent/Support/TaxonomyTrait.php | TaxonomyTrait.getTax | public function getTax()
{
global $wp_query;
if (isset($wp_query->tax_query) && !empty($wp_query->tax_query))
{
return reset($wp_query->tax_query->queries)['taxonomy'];
}
return false;
} | php | public function getTax()
{
global $wp_query;
if (isset($wp_query->tax_query) && !empty($wp_query->tax_query))
{
return reset($wp_query->tax_query->queries)['taxonomy'];
}
return false;
} | Return the taxonomy slug if available
@return bool|mixed | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L42-L52 |
bruno-barros/w.eloquent-framework | src/weloquent/Support/TaxonomyTrait.php | TaxonomyTrait.getTerm | public function getTerm()
{
global $wp_query;
if (isset($wp_query->tax_query) && !empty($wp_query->tax_query))
{
$first = reset($wp_query->tax_query->queries);
return is_array($first) ? reset($first['terms']) : false;
}
return false;
} | php | public function getTerm()
{
global $wp_query;
if (isset($wp_query->tax_query) && !empty($wp_query->tax_query))
{
$first = reset($wp_query->tax_query->queries);
return is_array($first) ? reset($first['terms']) : false;
}
return false;
} | Return the taxonomy term if available
@return bool|mixed | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L59-L70 |
inhere/php-library-plus | libs/Network/Telnet.php | Telnet.watch | public function watch($command, $interval = 500)
{
$count = 0;
$activeTime = time();
$maxTime = (int)$this->config['max_watch_time'];
$intervalUs = $interval * 1000;
//echo "watch command: $command, refresh interval: {$interval}ms\n";
while (true) {
$count++;
$result = $this->command($command);
if (0 === strpos($result, 'ERR')) {
echo "$result\n";
echo "error command: $command. ";
break;
}
// clear screen before output
echo "\033[2JThe {$count} times watch {$command} result(refresh interval: {$interval}ms):\n{$result}\n";
if ($maxTime > 0 && time() - $activeTime >= $maxTime) {
echo 'watch time end. ';
break;
}
usleep($intervalUs);
}
echo "Quit\n";
} | php | public function watch($command, $interval = 500)
{
$count = 0;
$activeTime = time();
$maxTime = (int)$this->config['max_watch_time'];
$intervalUs = $interval * 1000;
//echo "watch command: $command, refresh interval: {$interval}ms\n";
while (true) {
$count++;
$result = $this->command($command);
if (0 === strpos($result, 'ERR')) {
echo "$result\n";
echo "error command: $command. ";
break;
}
// clear screen before output
echo "\033[2JThe {$count} times watch {$command} result(refresh interval: {$interval}ms):\n{$result}\n";
if ($maxTime > 0 && time() - $activeTime >= $maxTime) {
echo 'watch time end. ';
break;
}
usleep($intervalUs);
}
echo "Quit\n";
} | watch a command
@param string $command
@param integer $interval (ms) | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L179-L210 |
inhere/php-library-plus | libs/Network/Telnet.php | Telnet.interactive | public function interactive()
{
echo "welcome! please input command('quit' or 'exit' to Quit).\n ";
while (true) {
echo '> ';
if ($cmd = trim(fgets(\STDIN))) {
// echo "input command: $cmd\n";
if ($cmd === 'quit' || $cmd === 'exit') {
echo "Quit. Bye\n";
break;
}
echo $this->command($cmd) . PHP_EOL;
}
usleep(50000);
}
$this->close();
} | php | public function interactive()
{
echo "welcome! please input command('quit' or 'exit' to Quit).\n ";
while (true) {
echo '> ';
if ($cmd = trim(fgets(\STDIN))) {
// echo "input command: $cmd\n";
if ($cmd === 'quit' || $cmd === 'exit') {
echo "Quit. Bye\n";
break;
}
echo $this->command($cmd) . PHP_EOL;
}
usleep(50000);
}
$this->close();
} | into interactive environment | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L215-L235 |
inhere/php-library-plus | libs/Network/Telnet.php | Telnet.command | public function command($command, $readResult = true, $readSize = 1024)
{
$len = $this->write(trim($command) . "\r\n");
if ($readResult) {
return $this->read($readSize);
}
return $len;
} | php | public function command($command, $readResult = true, $readSize = 1024)
{
$len = $this->write(trim($command) . "\r\n");
if ($readResult) {
return $this->read($readSize);
}
return $len;
} | send command
@param string $command
@param bool $readResult
@param int $readSize
@return false|int|string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L244-L253 |
inhere/php-library-plus | libs/Network/Telnet.php | Telnet.write | public function write($buffer)
{
if ($this->driver === self::DRIVER_SOCKET) {
return socket_write($this->sock, $buffer, \strlen($buffer));
} else {
// $buffer = str_replace(chr(255), chr(255) . chr(255), $buffer);
return fwrite($this->sock, $buffer);
}
} | php | public function write($buffer)
{
if ($this->driver === self::DRIVER_SOCKET) {
return socket_write($this->sock, $buffer, \strlen($buffer));
} else {
// $buffer = str_replace(chr(255), chr(255) . chr(255), $buffer);
return fwrite($this->sock, $buffer);
}
} | write
@param string $buffer
@return int|false | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L260-L268 |
inhere/php-library-plus | libs/Network/Telnet.php | Telnet.read | public function read($size = 1024)
{
if ($this->driver === self::DRIVER_SOCKET) {
return socket_read($this->sock, $size);
} else {
return fread($this->sock, $size);
}
} | php | public function read($size = 1024)
{
if ($this->driver === self::DRIVER_SOCKET) {
return socket_read($this->sock, $size);
} else {
return fread($this->sock, $size);
}
} | read
@param integer $size
@return string|false | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L275-L282 |
amarcinkowski/hospitalplugin | src/Entities/WardCRUD.php | WardCRUD.getWardForUser | public static function getWardForUser($userId)
{
$entityManager = (object) DoctrineBootstrap::getEntityManager();
$user = $entityManager->getRepository('Hospitalplugin\Entities\User')->findOneById($userId);
return $user->getWard();
} | php | public static function getWardForUser($userId)
{
$entityManager = (object) DoctrineBootstrap::getEntityManager();
$user = $entityManager->getRepository('Hospitalplugin\Entities\User')->findOneById($userId);
return $user->getWard();
} | @param $userId int
@return Ward Ward ward | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Entities/WardCRUD.php#L53-L58 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.setId | public function setId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->id !== $v) {
$this->id = $v;
$this->modifiedColumns[SmartyFilterI18nTableMap::ID] = true;
}
if ($this->aSmartyFilter !== null && $this->aSmartyFilter->getId() !== $v) {
$this->aSmartyFilter = null;
}
return $this;
} | php | public function setId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->id !== $v) {
$this->id = $v;
$this->modifiedColumns[SmartyFilterI18nTableMap::ID] = true;
}
if ($this->aSmartyFilter !== null && $this->aSmartyFilter->getId() !== $v) {
$this->aSmartyFilter = null;
}
return $this;
} | Set the value of [id] column.
@param int $v new value
@return \SmartyFilter\Model\SmartyFilterI18n The current object (for fluent API support) | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L411-L428 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.ensureConsistency | public function ensureConsistency()
{
if ($this->aSmartyFilter !== null && $this->id !== $this->aSmartyFilter->getId()) {
$this->aSmartyFilter = null;
}
} | php | public function ensureConsistency()
{
if ($this->aSmartyFilter !== null && $this->id !== $this->aSmartyFilter->getId()) {
$this->aSmartyFilter = null;
}
} | Checks and repairs the internal consistency of the object.
This method is executed after an already-instantiated object is re-hydrated
from the database. It exists to check any foreign keys to make sure that
the objects related to the current object are correct based on foreign key.
You can override this method in the stub class, but you should always invoke
the base method from the overridden method (i.e. parent::ensureConsistency()),
in case your model changes.
@throws PropelException | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L570-L575 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.doSave | protected function doSave(ConnectionInterface $con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// We call the save method on the following object(s) if they
// were passed to this object by their corresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aSmartyFilter !== null) {
if ($this->aSmartyFilter->isModified() || $this->aSmartyFilter->isNew()) {
$affectedRows += $this->aSmartyFilter->save($con);
}
$this->setSmartyFilter($this->aSmartyFilter);
}
if ($this->isNew() || $this->isModified()) {
// persist changes
if ($this->isNew()) {
$this->doInsert($con);
} else {
$this->doUpdate($con);
}
$affectedRows += 1;
$this->resetModified();
}
$this->alreadyInSave = false;
}
return $affectedRows;
} | php | protected function doSave(ConnectionInterface $con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// We call the save method on the following object(s) if they
// were passed to this object by their corresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aSmartyFilter !== null) {
if ($this->aSmartyFilter->isModified() || $this->aSmartyFilter->isNew()) {
$affectedRows += $this->aSmartyFilter->save($con);
}
$this->setSmartyFilter($this->aSmartyFilter);
}
if ($this->isNew() || $this->isModified()) {
// persist changes
if ($this->isNew()) {
$this->doInsert($con);
} else {
$this->doUpdate($con);
}
$affectedRows += 1;
$this->resetModified();
}
$this->alreadyInSave = false;
}
return $affectedRows;
} | Performs the work of inserting or updating the row in the database.
If the object is new, it inserts it; otherwise an update is performed.
All related objects are also updated in this method.
@param ConnectionInterface $con
@return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
@throws PropelException
@see save() | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L720-L753 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.buildCriteria | public function buildCriteria()
{
$criteria = new Criteria(SmartyFilterI18nTableMap::DATABASE_NAME);
if ($this->isColumnModified(SmartyFilterI18nTableMap::ID)) {
$criteria->add(SmartyFilterI18nTableMap::ID, $this->id);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::LOCALE)) {
$criteria->add(SmartyFilterI18nTableMap::LOCALE, $this->locale);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::TITLE)) {
$criteria->add(SmartyFilterI18nTableMap::TITLE, $this->title);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::DESCRIPTION)) {
$criteria->add(SmartyFilterI18nTableMap::DESCRIPTION, $this->description);
}
return $criteria;
} | php | public function buildCriteria()
{
$criteria = new Criteria(SmartyFilterI18nTableMap::DATABASE_NAME);
if ($this->isColumnModified(SmartyFilterI18nTableMap::ID)) {
$criteria->add(SmartyFilterI18nTableMap::ID, $this->id);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::LOCALE)) {
$criteria->add(SmartyFilterI18nTableMap::LOCALE, $this->locale);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::TITLE)) {
$criteria->add(SmartyFilterI18nTableMap::TITLE, $this->title);
}
if ($this->isColumnModified(SmartyFilterI18nTableMap::DESCRIPTION)) {
$criteria->add(SmartyFilterI18nTableMap::DESCRIPTION, $this->description);
}
return $criteria;
} | Build a Criteria object containing the values of all modified columns in this object.
@return Criteria The Criteria object containing all modified values. | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L1004-L1022 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.setSmartyFilter | public function setSmartyFilter(ChildSmartyFilter $v = null)
{
if ($v === null) {
$this->setId(null);
} else {
$this->setId($v->getId());
}
$this->aSmartyFilter = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildSmartyFilter object, it will not be re-added.
if ($v !== null) {
$v->addSmartyFilterI18n($this);
}
return $this;
} | php | public function setSmartyFilter(ChildSmartyFilter $v = null)
{
if ($v === null) {
$this->setId(null);
} else {
$this->setId($v->getId());
}
$this->aSmartyFilter = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the ChildSmartyFilter object, it will not be re-added.
if ($v !== null) {
$v->addSmartyFilterI18n($this);
}
return $this;
} | Declares an association between this object and a ChildSmartyFilter object.
@param ChildSmartyFilter $v
@return \SmartyFilter\Model\SmartyFilterI18n The current object (for fluent API support)
@throws PropelException | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L1127-L1145 |
thelia-modules/SmartyFilter | Model/Base/SmartyFilterI18n.php | SmartyFilterI18n.getSmartyFilter | public function getSmartyFilter(ConnectionInterface $con = null)
{
if ($this->aSmartyFilter === null && ($this->id !== null)) {
$this->aSmartyFilter = ChildSmartyFilterQuery::create()->findPk($this->id, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aSmartyFilter->addSmartyFilterI18ns($this);
*/
}
return $this->aSmartyFilter;
} | php | public function getSmartyFilter(ConnectionInterface $con = null)
{
if ($this->aSmartyFilter === null && ($this->id !== null)) {
$this->aSmartyFilter = ChildSmartyFilterQuery::create()->findPk($this->id, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->aSmartyFilter->addSmartyFilterI18ns($this);
*/
}
return $this->aSmartyFilter;
} | Get the associated ChildSmartyFilter object
@param ConnectionInterface $con Optional Connection object.
@return ChildSmartyFilter The associated ChildSmartyFilter object.
@throws PropelException | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L1155-L1169 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Message/Type/APNS.php | APNS.validateRecipient | public function validateRecipient($token)
{
if (!ctype_xdigit($token)) {
throw new InvalidArgumentException(sprintf(
'Device token must be a hexadecimal digit. Token given: "%s"',
$token
));
}
if (strlen($token) != 64) {
throw new InvalidArgumentException(sprintf(
'Device token must be a 64 charsets, Token length given: %d.',
mb_strlen($token)
));
}
return true;
} | php | public function validateRecipient($token)
{
if (!ctype_xdigit($token)) {
throw new InvalidArgumentException(sprintf(
'Device token must be a hexadecimal digit. Token given: "%s"',
$token
));
}
if (strlen($token) != 64) {
throw new InvalidArgumentException(sprintf(
'Device token must be a 64 charsets, Token length given: %d.',
mb_strlen($token)
));
}
return true;
} | {@inheritdoc} | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Message/Type/APNS.php#L308-L324 |
cityware/city-format | src/Date.php | Date.dateOperations | public static function dateOperations($date, $operation, $where, $quant, $return_format = null) {
// Verifica erros
$warning = "<br>Warning! Date Operations Fail... ";
if (!$date || !$operation) {
return "{$warning} invalid or inexistent arguments<br>";
} else {
if (!($operation == "sub" || $operation == "-" || $operation == "sum" || $operation == "+")) {
return "<br>{$warning} Invalid Operation...<br>";
} else {
// Separa dia, mês e ano
list($day, $month, $year) = explode("/", $date);
// Determina a operação (Soma ou Subtração)
$op = ($operation == "sub" || $operation == "-") ? "-" : '';
$sum_month = null;
$sum_day = null;
$sum_year = null;
// Determina aonde será efetuada a operação (dia, mês, ano)
if ($where == "day") {
$sum_day = $op . $quant;
}
if ($where == "month") {
$sum_month = $op . $quant;
}
if ($where == "year") {
$sum_year = $op . $quant;
}
// Gera o timestamp
$date = mktime(0, 0, 0, $month + $sum_month, $day + $sum_day, $year + $sum_year);
// Retorna o timestamp ou extended
$dateReturn = ($return_format == "timestamp" || $return_format == "ts") ? $date : date("d/m/Y", "$date");
// Retorna a data
return $dateReturn;
}
}
} | php | public static function dateOperations($date, $operation, $where, $quant, $return_format = null) {
// Verifica erros
$warning = "<br>Warning! Date Operations Fail... ";
if (!$date || !$operation) {
return "{$warning} invalid or inexistent arguments<br>";
} else {
if (!($operation == "sub" || $operation == "-" || $operation == "sum" || $operation == "+")) {
return "<br>{$warning} Invalid Operation...<br>";
} else {
// Separa dia, mês e ano
list($day, $month, $year) = explode("/", $date);
// Determina a operação (Soma ou Subtração)
$op = ($operation == "sub" || $operation == "-") ? "-" : '';
$sum_month = null;
$sum_day = null;
$sum_year = null;
// Determina aonde será efetuada a operação (dia, mês, ano)
if ($where == "day") {
$sum_day = $op . $quant;
}
if ($where == "month") {
$sum_month = $op . $quant;
}
if ($where == "year") {
$sum_year = $op . $quant;
}
// Gera o timestamp
$date = mktime(0, 0, 0, $month + $sum_month, $day + $sum_day, $year + $sum_year);
// Retorna o timestamp ou extended
$dateReturn = ($return_format == "timestamp" || $return_format == "ts") ? $date : date("d/m/Y", "$date");
// Retorna a data
return $dateReturn;
}
}
} | Função que soma ou subtrai, dias, meses ou anos de uma data qualquer
- Ex:
$date = operations("06/01/2003", "sum", "day", "4") // Return 10/01/2003
$date = operations("06/01/2003", "sub", "day", "4") // Return 02/01/2003
$date = operations("06/01/2003", "sum", "month", "4") // Return 10/05/2003
@param date $date
@param string $operation
@param boolean $where
@param integer $quant
@param string $return_format
@return type | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L31-L71 |
cityware/city-format | src/Date.php | Date.formatDate | public static function formatDate($varValue, $varFormat) {
if (is_array($varValue)) {
$temp = $varValue;
} else {
if (strtolower($varValue) == 'get' or strtolower($varValue) == 'post') {
eval('$temp = &$_' . strtoupper($varValue) . ';');
} else {
$temp = array($varValue);
}
}
foreach ($temp as $key => $value) {
if (is_array($value)) {
foreach ($value as $key2 => $value2) {
$datetime = null;
$date = null;
if (preg_match('/^([0-9]{4})[-,\/]([0-9]{1,2})[-,\/]([0-9]{1,2})/', $value2)) {
$datetime = explode(' ', $value2);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key][$key2] = date($varFormat, strtotime($datetime[0])) . ' ' . $datetime[1];
} else {
$temp[$key][$key2] = date($varFormat, strtotime($datetime[0]));
}
} elseif (preg_match('/^([0-9]{1,2})[-,\/]([0-9]{1,2})[-,\/]([0-9]{4})/', $value2, $date)) {
$datetime = explode(' ', $value2);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key][$key2] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1])) . ' ' . $datetime[1];
} else {
$temp[$key][$key2] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1]));
}
}
}
} else {
$datetime = null;
$date = null;
if (preg_match('/^([0-9]{4})[-,\/]([0-9]{1,2})[-,\/]([0-9]{1,2})/', $value)) {
$datetime = explode(' ', $value);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key] = date($varFormat, strtotime($datetime[0])) . ' ' . $datetime[1];
} else {
$temp[$key] = date($varFormat, strtotime($datetime[0]));
}
} elseif (preg_match('/^([0-9]{1,2})[-,\/]([0-9]{1,2})[-,\/]([0-9]{4})/', $value, $date)) {
$datetime = explode(' ', $value);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1])) . ' ' . $datetime[1];
} else {
$temp[$key] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1]));
}
}
}
}
return $temp;
} | php | public static function formatDate($varValue, $varFormat) {
if (is_array($varValue)) {
$temp = $varValue;
} else {
if (strtolower($varValue) == 'get' or strtolower($varValue) == 'post') {
eval('$temp = &$_' . strtoupper($varValue) . ';');
} else {
$temp = array($varValue);
}
}
foreach ($temp as $key => $value) {
if (is_array($value)) {
foreach ($value as $key2 => $value2) {
$datetime = null;
$date = null;
if (preg_match('/^([0-9]{4})[-,\/]([0-9]{1,2})[-,\/]([0-9]{1,2})/', $value2)) {
$datetime = explode(' ', $value2);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key][$key2] = date($varFormat, strtotime($datetime[0])) . ' ' . $datetime[1];
} else {
$temp[$key][$key2] = date($varFormat, strtotime($datetime[0]));
}
} elseif (preg_match('/^([0-9]{1,2})[-,\/]([0-9]{1,2})[-,\/]([0-9]{4})/', $value2, $date)) {
$datetime = explode(' ', $value2);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key][$key2] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1])) . ' ' . $datetime[1];
} else {
$temp[$key][$key2] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1]));
}
}
}
} else {
$datetime = null;
$date = null;
if (preg_match('/^([0-9]{4})[-,\/]([0-9]{1,2})[-,\/]([0-9]{1,2})/', $value)) {
$datetime = explode(' ', $value);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key] = date($varFormat, strtotime($datetime[0])) . ' ' . $datetime[1];
} else {
$temp[$key] = date($varFormat, strtotime($datetime[0]));
}
} elseif (preg_match('/^([0-9]{1,2})[-,\/]([0-9]{1,2})[-,\/]([0-9]{4})/', $value, $date)) {
$datetime = explode(' ', $value);
if (is_array($datetime) and count($datetime) > 1) {
$temp[$key] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1])) . ' ' . $datetime[1];
} else {
$temp[$key] = date($varFormat, strtotime($date[3] . '-' . $date[2] . '-' . $date[1]));
}
}
}
}
return $temp;
} | Função de tratamento de campos com data
@param mixed $varValue (Array de Valores ou Nome de Variável Default [GET/POST])
@param string $varFormat (Formato da data no padrão PHP)
@return mixed | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L79-L133 |
cityware/city-format | src/Date.php | Date.secondsToTime | public static function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
$secondsInAMonth = 30 * $secondsInADay;
$secondsInAYear = 12 * $secondsInAMonth;
$years = floor($inputSeconds / $secondsInAYear);
$monthSeconds = $inputSeconds % $secondsInAYear;
$months = floor($monthSeconds / $secondsInAMonth);
$daySeconds = $monthSeconds % $secondsInAMonth;
$days = floor($daySeconds / $secondsInADay);
$hourSeconds = $daySeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
$aReturn = array(
'y' => (int) $years,
'm' => (int) $months,
'd' => (int) $days,
'h' => (int) $hours,
'i' => (int) $minutes,
's' => (int) $seconds
);
return $aReturn;
} | php | public static function secondsToTime($inputSeconds) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
$secondsInAMonth = 30 * $secondsInADay;
$secondsInAYear = 12 * $secondsInAMonth;
$years = floor($inputSeconds / $secondsInAYear);
$monthSeconds = $inputSeconds % $secondsInAYear;
$months = floor($monthSeconds / $secondsInAMonth);
$daySeconds = $monthSeconds % $secondsInAMonth;
$days = floor($daySeconds / $secondsInADay);
$hourSeconds = $daySeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
$aReturn = array(
'y' => (int) $years,
'm' => (int) $months,
'd' => (int) $days,
'h' => (int) $hours,
'i' => (int) $minutes,
's' => (int) $seconds
);
return $aReturn;
} | Função de conversão de segundos para Array(Anoa, Meses, Dias, Horas, Minutos, Segundos)
@param integer $inputSeconds
@return array | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L140-L173 |
cityware/city-format | src/Date.php | Date.convertTime | public static function convertTime($time, $conversion, $debub = false) {
list ($hora, $minuto, $segundo) = explode(":", $time);
switch (strtolower($conversion)) {
case 'h':
$resultH = $hora * 1;
$resultM = $minuto / 60;
$resultS = $segundo / 60;
break;
case 'm':
$resultH = $hora * 60;
$resultM = $minuto * 1;
$resultS = $segundo / 60;
break;
case 's':
$resultH = $hora * 60;
$resultM = $minuto * 60;
$resultS = $segundo * 1;
break;
}
$result = Cityware_Format_Mask::formataValor(($resultH + $resultM + $resultS), ".", 2, ".", "");
if ($debub) {
echo "Hora: " . $resultH . " Minuto: " . $resultM . " Segundo: " . $resultS . " Total: " . $result . "<br>";
}
return $result;
} | php | public static function convertTime($time, $conversion, $debub = false) {
list ($hora, $minuto, $segundo) = explode(":", $time);
switch (strtolower($conversion)) {
case 'h':
$resultH = $hora * 1;
$resultM = $minuto / 60;
$resultS = $segundo / 60;
break;
case 'm':
$resultH = $hora * 60;
$resultM = $minuto * 1;
$resultS = $segundo / 60;
break;
case 's':
$resultH = $hora * 60;
$resultM = $minuto * 60;
$resultS = $segundo * 1;
break;
}
$result = Cityware_Format_Mask::formataValor(($resultH + $resultM + $resultS), ".", 2, ".", "");
if ($debub) {
echo "Hora: " . $resultH . " Minuto: " . $resultM . " Segundo: " . $resultS . " Total: " . $result . "<br>";
}
return $result;
} | Conversão de hora para o formato que definir (Hora, Minuto, Segundo)
@param time $time
@param string $conversion
@param boolean $debub
@return double | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L182-L209 |
cityware/city-format | src/Date.php | Date.getMonthsRange | public static function getMonthsRange($startData, $endDate) {
$time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons
$time2 = strtotime($endDate);
//$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity
//$my2 = date('mY', $time2);
$year1 = date('Y', $time1);
$year2 = date('Y', $time2);
$years = range($year1, $year2);
$months = Array();
foreach ($years as $year) {
$months[$year] = array();
while ($time1 < $time2) {
if (date('Y', $time1) == $year) {
$months[$year][] = date('m', $time1);
$time1 = strtotime(date('Y-m-d', $time1) . ' +1 month');
} else {
break;
}
}
continue;
}
return $months;
} | php | public static function getMonthsRange($startData, $endDate) {
$time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons
$time2 = strtotime($endDate);
//$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity
//$my2 = date('mY', $time2);
$year1 = date('Y', $time1);
$year2 = date('Y', $time2);
$years = range($year1, $year2);
$months = Array();
foreach ($years as $year) {
$months[$year] = array();
while ($time1 < $time2) {
if (date('Y', $time1) == $year) {
$months[$year][] = date('m', $time1);
$time1 = strtotime(date('Y-m-d', $time1) . ' +1 month');
} else {
break;
}
}
continue;
}
return $months;
} | Cria um intervalo de Meses de acordo com a data inicial e final
@param date $startData
@param date $endDate
@return array | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L217-L240 |
cityware/city-format | src/Date.php | Date.rangeWeek | public static function rangeWeek($datestr) {
date_default_timezone_set(date_default_timezone_get());
$dt = strtotime($datestr);
$res['start'] = date('N', $dt) == 1 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('last monday', $dt));
$res['end'] = date('N', $dt) == 7 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('next sunday', $dt));
return $res;
} | php | public static function rangeWeek($datestr) {
date_default_timezone_set(date_default_timezone_get());
$dt = strtotime($datestr);
$res['start'] = date('N', $dt) == 1 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('last monday', $dt));
$res['end'] = date('N', $dt) == 7 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('next sunday', $dt));
return $res;
} | Função de geração de intervalo de semana
@param type $datestr
@return type | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L247-L254 |
cityware/city-format | src/Date.php | Date.createDateRangeArray | public static function createDateRangeArray($strDateFrom, $strDateTo) {
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange = array();
$iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
$iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
if ($iDateTo >= $iDateFrom) {
array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
while ($iDateFrom < $iDateTo) {
$iDateFrom+=86400; // add 24 hours
array_push($aryRange, date('Y-m-d', $iDateFrom));
}
}
return $aryRange;
} | php | public static function createDateRangeArray($strDateFrom, $strDateTo) {
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange = array();
$iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
$iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
if ($iDateTo >= $iDateFrom) {
array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
while ($iDateFrom < $iDateTo) {
$iDateFrom+=86400; // add 24 hours
array_push($aryRange, date('Y-m-d', $iDateFrom));
}
}
return $aryRange;
} | Função para criação de intervalo de datas
@param type $strDateFrom
@param type $strDateTo
@return array | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L262-L283 |
cityware/city-format | src/Date.php | Date.extensionMonth | public static function extensionMonth($month) {
$mes = null;
switch ($month) {
case '01':
case 1:
$mes = "Janeiro";
break;
case '02':
case 2:
$mes = "Fevereiro";
break;
case '03':
case 3:
$mes = "Março";
break;
case '04':
case 4:
$mes = "Abril";
break;
case '05':
case 5:
$mes = "Maio";
break;
case '06':
case 6:
$mes = "Junho";
break;
case '07':
case 7:
$mes = "Julho";
break;
case '08':
case 8:
$mes = "Agosto";
break;
case '09':
case 9:
$mes = "Setembro";
break;
case '10':
case 10:
$mes = "Outubro";
break;
case '11':
case 11:
$mes = "Novembro";
break;
case '12':
case 12:
$mes = "Dezembro";
break;
}
return $mes;
} | php | public static function extensionMonth($month) {
$mes = null;
switch ($month) {
case '01':
case 1:
$mes = "Janeiro";
break;
case '02':
case 2:
$mes = "Fevereiro";
break;
case '03':
case 3:
$mes = "Março";
break;
case '04':
case 4:
$mes = "Abril";
break;
case '05':
case 5:
$mes = "Maio";
break;
case '06':
case 6:
$mes = "Junho";
break;
case '07':
case 7:
$mes = "Julho";
break;
case '08':
case 8:
$mes = "Agosto";
break;
case '09':
case 9:
$mes = "Setembro";
break;
case '10':
case 10:
$mes = "Outubro";
break;
case '11':
case 11:
$mes = "Novembro";
break;
case '12':
case 12:
$mes = "Dezembro";
break;
}
return $mes;
} | Retorna o mês por extenso
@param integer $month
@return string | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L374-L428 |
cityware/city-format | src/Date.php | Date.extensionShortMonth | public static function extensionShortMonth($month) {
$mes = null;
switch ($month) {
case '01':
case 1:
$mes = "Jan";
break;
case '02':
case 2:
$mes = "Fev";
break;
case '03':
case 3:
$mes = "Mar";
break;
case '04':
case 4:
$mes = "Abr";
break;
case '05':
case 5:
$mes = "Mai";
break;
case '06':
case 6:
$mes = "Jun";
break;
case '07':
case 7:
$mes = "Jul";
break;
case '08':
case 8:
$mes = "Ago";
break;
case '09':
case 9:
$mes = "Set";
break;
case '10':
case 10:
$mes = "Out";
break;
case '11':
case 11:
$mes = "Nov";
break;
case '12':
case 12:
$mes = "Dez";
break;
}
return $mes;
} | php | public static function extensionShortMonth($month) {
$mes = null;
switch ($month) {
case '01':
case 1:
$mes = "Jan";
break;
case '02':
case 2:
$mes = "Fev";
break;
case '03':
case 3:
$mes = "Mar";
break;
case '04':
case 4:
$mes = "Abr";
break;
case '05':
case 5:
$mes = "Mai";
break;
case '06':
case 6:
$mes = "Jun";
break;
case '07':
case 7:
$mes = "Jul";
break;
case '08':
case 8:
$mes = "Ago";
break;
case '09':
case 9:
$mes = "Set";
break;
case '10':
case 10:
$mes = "Out";
break;
case '11':
case 11:
$mes = "Nov";
break;
case '12':
case 12:
$mes = "Dez";
break;
}
return $mes;
} | Retorna o mês por extenso em formato reduzido
@param integer $month
@return string | https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L435-L489 |
gplcart/file_manager | handlers/commands/Rename.php | Rename.allowed | public function allowed($file)
{
return in_array($file->getType(), array('file', 'dir')) && $file->isWritable() && !$this->isInitialPath($file);
} | php | public function allowed($file)
{
return in_array($file->getType(), array('file', 'dir')) && $file->isWritable() && !$this->isInitialPath($file);
} | Whether the command is allowed for the file
@param \SplFileInfo $file
@return bool | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Rename.php#L23-L26 |
gplcart/file_manager | handlers/commands/Rename.php | Rename.submit | public function submit($controller)
{
set_time_limit(0);
$submitted = $controller->getSubmitted();
$file = reset($submitted['files']);
$path = $file->getRealPath();
$destination = $controller->getSubmitted('destination');
$query = array(
'cmd' => 'list',
'path' => $this->getRelativeDirectory($path)
);
$errors = $success = 0;
$this->move($path, $destination, $errors, $success);
$vars = array('@num_success' => $success, '@num_errors' => $errors);
return array(
'redirect' => $controller->url('', $query),
'severity' => empty($errors) ? 'success' : 'warning',
'message' => $this->translation->text('Renamed @num_success, errors: @num_errors', $vars)
);
} | php | public function submit($controller)
{
set_time_limit(0);
$submitted = $controller->getSubmitted();
$file = reset($submitted['files']);
$path = $file->getRealPath();
$destination = $controller->getSubmitted('destination');
$query = array(
'cmd' => 'list',
'path' => $this->getRelativeDirectory($path)
);
$errors = $success = 0;
$this->move($path, $destination, $errors, $success);
$vars = array('@num_success' => $success, '@num_errors' => $errors);
return array(
'redirect' => $controller->url('', $query),
'severity' => empty($errors) ? 'success' : 'warning',
'message' => $this->translation->text('Renamed @num_success, errors: @num_errors', $vars)
);
} | Rename a file
@param \gplcart\core\Controller $controller
@return array | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Rename.php#L47-L72 |
WolfMicrosystems/ldap | src/WMS/Library/Ldap/Collection/AccountNodeCollection.php | AccountNodeCollection.createEntry | protected function createEntry(array $data)
{
return Entity\AccountNode::fromNode(parent::createEntry($data), $this->getConnection()->getConfiguration());
} | php | protected function createEntry(array $data)
{
return Entity\AccountNode::fromNode(parent::createEntry($data), $this->getConnection()->getConfiguration());
} | Creates the data structure for the given entry data
@param array $data
@return Entity\AccountNode | https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Collection/AccountNodeCollection.php#L22-L25 |
xiewulong/yii2-wechat | Manager.php | Manager.sendTemplateMessageByType | public function sendTemplateMessageByType($touser, $type, $data, $url = null) {
return isset($this->templates[$type]) && $this->sendTemplateMessage($touser, $this->templates[$type], $data, $url);
} | php | public function sendTemplateMessageByType($touser, $type, $data, $url = null) {
return isset($this->templates[$type]) && $this->sendTemplateMessage($touser, $this->templates[$type], $data, $url);
} | Send template by type
@since 0.0.1
@param {string} $touser openid
@param {string} $type
@param {array} $data
@param {string} [$url]
@return {boolean}
@example \Yii::$app->wechat->sendTemplateMessageByType($touser, $type, $data, $url); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L93-L95 |
xiewulong/yii2-wechat | Manager.php | Manager.sendTemplateMessage | public function sendTemplateMessage($touser, $template_id, $data, $url = null) {
$this->getData('/cgi-bin/message/template/send', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'touser' => $touser,
'template_id' => $template_id,
'url' => $url,
'data' => $data,
]));
return $this->errcode == 0;
} | php | public function sendTemplateMessage($touser, $template_id, $data, $url = null) {
$this->getData('/cgi-bin/message/template/send', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'touser' => $touser,
'template_id' => $template_id,
'url' => $url,
'data' => $data,
]));
return $this->errcode == 0;
} | Send template
@since 0.0.1
@param {string} $touser openid
@param {string} $template_id
@param {array} $data
@param {string} [$url]
@return {boolean}
@example \Yii::$app->wechat->sendTemplateMessage($touser, $template_id, $data, $url); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L108-L119 |
xiewulong/yii2-wechat | Manager.php | Manager.deleteTemplate | public function deleteTemplate($template_id) {
$data = $this->getData('/cgi-bin/template/del_private_template', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'template_id' => $template_id,
]));
return $this->errcode == 0;
} | php | public function deleteTemplate($template_id) {
$data = $this->getData('/cgi-bin/template/del_private_template', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'template_id' => $template_id,
]));
return $this->errcode == 0;
} | Delete template
@since 0.0.1
@param {string} $template_id
@return {boolean}
@example \Yii::$app->wechat->deleteTemplate($template_id); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L129-L137 |
xiewulong/yii2-wechat | Manager.php | Manager.addTemplate | public function addTemplate($template_id_short) {
$data = $this->getData('/cgi-bin/template/api_add_template', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'template_id_short' => $template_id_short,
]));
if($this->errcode == 0) {
return $data['template_id'];
}
return null;
} | php | public function addTemplate($template_id_short) {
$data = $this->getData('/cgi-bin/template/api_add_template', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'template_id_short' => $template_id_short,
]));
if($this->errcode == 0) {
return $data['template_id'];
}
return null;
} | Add template
@since 0.0.1
@param {string} $template_id_short
@return {string}
@example \Yii::$app->wechat->addTemplate($template_id_short); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L147-L159 |
xiewulong/yii2-wechat | Manager.php | Manager.setTemplateIndustry | public function setTemplateIndustry($industry_id1, $industry_id2) {
$data = $this->getData('/cgi-bin/template/api_set_industry', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'industry_id1' => $industry_id1,
'industry_id2' => $industry_id2,
]));
return $this->errcode == 0;
} | php | public function setTemplateIndustry($industry_id1, $industry_id2) {
$data = $this->getData('/cgi-bin/template/api_set_industry', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'industry_id1' => $industry_id1,
'industry_id2' => $industry_id2,
]));
return $this->errcode == 0;
} | Set template industry
@since 0.0.1
@param {integer} $industry_id1 primary
@param {integer} $industry_id2 secondary
@return {boolean}
@example \Yii::$app->wechat->setTemplateIndustry($industry_id1, $industry_id2); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L208-L217 |
xiewulong/yii2-wechat | Manager.php | Manager.addNewsImage | public function addNewsImage($url_source) {
if($image = WechatNewsImage::findOne(['appid' => $this->app->appid, 'url_source' => $url_source])) {
return $image->id;
}
$image = new WechatNewsImage;
$image->url_source = $url_source;
$data = $this->getData('/cgi-bin/media/uploadimg', [
'access_token' => $this->getAccessToken(),
], ['media' => '@' . $image->localFile]);
$image->cleanTmp();
if($this->errcode == 0) {
$image->appid = $this->app->appid;
$image->url = $data['url'];
if($image->save()) {
return $image->id;
}
}
return 0;
} | php | public function addNewsImage($url_source) {
if($image = WechatNewsImage::findOne(['appid' => $this->app->appid, 'url_source' => $url_source])) {
return $image->id;
}
$image = new WechatNewsImage;
$image->url_source = $url_source;
$data = $this->getData('/cgi-bin/media/uploadimg', [
'access_token' => $this->getAccessToken(),
], ['media' => '@' . $image->localFile]);
$image->cleanTmp();
if($this->errcode == 0) {
$image->appid = $this->app->appid;
$image->url = $data['url'];
if($image->save()) {
return $image->id;
}
}
return 0;
} | 上传图文消息内的图片
@since 0.0.1
@param {string} $url_source 源url(非微信端)
@return {integer}
@example \Yii::$app->wechat->addNewsImage($url_source); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L227-L249 |
xiewulong/yii2-wechat | Manager.php | Manager.deleteNews | public function deleteNews($news_media_id) {
$media = WechatNewsMedia::findOne($news_media_id);
if(!$media) {
throw new ErrorException('数据查询失败');
}
return $this->deleteMaterial($media->media_id) && $media->delete();
} | php | public function deleteNews($news_media_id) {
$media = WechatNewsMedia::findOne($news_media_id);
if(!$media) {
throw new ErrorException('数据查询失败');
}
return $this->deleteMaterial($media->media_id) && $media->delete();
} | 删除图文消息
@since 0.0.1
@param {integer} $news_media_id 图文消息id
@return {boolean}
@example \Yii::$app->wechat->deleteNews($news_media_id); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L259-L266 |
xiewulong/yii2-wechat | Manager.php | Manager.updateNews | public function updateNews($news_media_id) {
$newsMedia = WechatNewsMedia::findOne($news_media_id);
if(!$newsMedia) {
throw new ErrorException('数据查询失败');
}
if($newsMedia->news->count_item == count($newsMedia->thumbMaterialMediaIdList)) {
$articles = $media->news->getArticles($this);
$thumb_material_media_ids = [];
$success = true;
foreach($articles as $index => $article) {
$thumb_material_media_ids[] = $article['thumb_material_media_id'];
$data = $this->getData('/cgi-bin/material/update_news', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'media_id' => $media->media_id,
'index' => $index,
'articles' => $article,
]));
if($this->errcode != 0) {
$success = false;
break;
}
}
if($success) {
$media->thumb_material_media_ids = Json::encode($thumb_material_media_ids);
if($details = $this->getNews($media->media_id)) {
$media->urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'url'));
$media->thumb_urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'thumb_url'));
}
if($media->save()) {
return $media->id;
}
}
} else {
$newsid = $media->newsid;
if($this->deleteNews($media->id)) {
return $this->addNews($newsid);
}
}
return 0;
} | php | public function updateNews($news_media_id) {
$newsMedia = WechatNewsMedia::findOne($news_media_id);
if(!$newsMedia) {
throw new ErrorException('数据查询失败');
}
if($newsMedia->news->count_item == count($newsMedia->thumbMaterialMediaIdList)) {
$articles = $media->news->getArticles($this);
$thumb_material_media_ids = [];
$success = true;
foreach($articles as $index => $article) {
$thumb_material_media_ids[] = $article['thumb_material_media_id'];
$data = $this->getData('/cgi-bin/material/update_news', [
'access_token' => $this->getAccessToken(),
], Json::encode([
'media_id' => $media->media_id,
'index' => $index,
'articles' => $article,
]));
if($this->errcode != 0) {
$success = false;
break;
}
}
if($success) {
$media->thumb_material_media_ids = Json::encode($thumb_material_media_ids);
if($details = $this->getNews($media->media_id)) {
$media->urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'url'));
$media->thumb_urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'thumb_url'));
}
if($media->save()) {
return $media->id;
}
}
} else {
$newsid = $media->newsid;
if($this->deleteNews($media->id)) {
return $this->addNews($newsid);
}
}
return 0;
} | 修改图文消息
@since 0.0.1
@param {integer} $news_media_id 图文消息id
@return {integer}
@example \Yii::$app->wechat->updateNews($news_media_id); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L276-L318 |
xiewulong/yii2-wechat | Manager.php | Manager.addNews | public function addNews($news_id) {
$news = WechatNews::findOne($news_id);
if(!$news) {
throw new ErrorException('数据查询失败');
} else if($newsMedia = WechatNewsMedia::findOne(['appid' => $this->app->appid, 'news_id' => $news->id])) {
return $newsMedia->id;
}
$articles = $news->getArticles($this);
$data = $this->getData('/cgi-bin/material/add_news', [
'access_token' => $this->getAccessToken(),
], Json::encode(['articles' => $articles]));
if($this->errcode == 0) {
$newsMedia = new WechatNewsMedia;
$newsMedia->appid = $this->app->appid;
$newsMedia->news_id = $news->id;
$newsMedia->media_id = $data['media_id'];
$newsMedia->thumb_material_media_ids = Json::encode(ArrayHelper::getColumn($articles, 'thumb_material_media_id'));
if($details = $this->getNews($newsMedia->media_id)) {
$newsMedia->urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'url'));
$newsMedia->thumb_urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'thumb_url'));
}
if($newsMedia->save()) {
return $newsMedia->id;
}
}
return 0;
} | php | public function addNews($news_id) {
$news = WechatNews::findOne($news_id);
if(!$news) {
throw new ErrorException('数据查询失败');
} else if($newsMedia = WechatNewsMedia::findOne(['appid' => $this->app->appid, 'news_id' => $news->id])) {
return $newsMedia->id;
}
$articles = $news->getArticles($this);
$data = $this->getData('/cgi-bin/material/add_news', [
'access_token' => $this->getAccessToken(),
], Json::encode(['articles' => $articles]));
if($this->errcode == 0) {
$newsMedia = new WechatNewsMedia;
$newsMedia->appid = $this->app->appid;
$newsMedia->news_id = $news->id;
$newsMedia->media_id = $data['media_id'];
$newsMedia->thumb_material_media_ids = Json::encode(ArrayHelper::getColumn($articles, 'thumb_material_media_id'));
if($details = $this->getNews($newsMedia->media_id)) {
$newsMedia->urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'url'));
$newsMedia->thumb_urls = Json::encode(ArrayHelper::getColumn($details['news_item'], 'thumb_url'));
}
if($newsMedia->save()) {
return $newsMedia->id;
}
}
return 0;
} | 新增图文消息
@since 0.0.1
@param {integer} $news_id 图文素材id
@return {integer}
@example \Yii::$app->wechat->addNews($news_id); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L328-L357 |
xiewulong/yii2-wechat | Manager.php | Manager.getNews | public function getNews($media_id = null, $all = true, $page = 1, $count = 20) {
return $media_id ? $this->getMaterial($media_id) : $this->getMaterials('news', $all, $page, $count);
} | php | public function getNews($media_id = null, $all = true, $page = 1, $count = 20) {
return $media_id ? $this->getMaterial($media_id) : $this->getMaterials('news', $all, $page, $count);
} | 获取图文消息
@since 0.0.1
@param {string} [$media_id] 媒体文件ID
@param {boolean} [$all=true] 是否返回所有
@param {integer} [$page=1] 页码
@param {integer} [$count=20] 每页数量
@return {array}
@example \Yii::$app->wechat->getNews($media_id, $all, $page, $count); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L370-L372 |
xiewulong/yii2-wechat | Manager.php | Manager.getMaterialCount | public function getMaterialCount() {
$data = $this->getData('/cgi-bin/material/get_materialcount', [
'access_token' => $this->getAccessToken(),
]);
if($this->errcode == 0) {
$this->app->count_image = $data['image_count'];
$this->app->count_voice = $data['voice_count'];
$this->app->count_video = $data['video_count'];
$this->app->count_news = $data['news_count'];
return $this->app->save();
}
return false;
} | php | public function getMaterialCount() {
$data = $this->getData('/cgi-bin/material/get_materialcount', [
'access_token' => $this->getAccessToken(),
]);
if($this->errcode == 0) {
$this->app->count_image = $data['image_count'];
$this->app->count_voice = $data['voice_count'];
$this->app->count_video = $data['video_count'];
$this->app->count_news = $data['news_count'];
return $this->app->save();
}
return false;
} | 获取素材总数
@since 0.0.1
@return {boolean}
@example \Yii::$app->wechat->getMaterialCount(); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L381-L395 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.